Programs & Examples On #Remote connection

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

Connecting to Postgresql in a docker container from outside

I tried to connect from localhost (mac) to a postgres container. I changed the port in the docker-compose file from 5432 to 3306 and started the container. No idea why I did it :|

Then I tried to connect to postgres via PSequel and adminer and the connection could not be established.

After switching back to port 5432 all works fine.

  db:
    image: postgres
    ports:
      - 5432:5432
    restart: always
    volumes:
      - "db_sql:/var/lib/mysql"
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
      POSTGRES_DB: postgres_db

This was my experience I wanted to share. Perhaps someone can make use of it.

Enable remote connections for SQL Server Express 2012

One More Thing...

Kyralessa provides great information but I have one other thing to add where I was stumped even after this article.

Under SQL Server Network Configuration > Protocols for Server > TCP/IP Enabled. Right Click TCP/IP and choose properties. Under the IP Addresses you need to set Enabled to Yes for each connection type that you are using.

enter image description here

Configure hibernate to connect to database via JNDI Datasource

Inside applicationContext.xml file of a maven Hibernet web app project below settings worked for me.

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee-3.0.xsd">



  <jee:jndi-lookup id="dataSource"
                 jndi-name="Give_DataSource_Path_From_Your_Server"
                 expected-type="javax.sql.DataSource" />


Hope It will help someone.Thanks!

How to declare std::unique_ptr and what is the use of it?

Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr

In this case:

unique_ptr<double> uptr2 (pd);

pd will be destroyed when uptr2 goes out of scope. This facilitates memory management by automatic deletion.

The case of unique_ptr<int> uptr (new int(3)); is not different, except that the raw pointer is not assigned to any variable here.

Create code first, many to many, with additional fields in association table

I'll just post the code to do this using the fluent API mapping.

public class User {
    public int UserID { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }

    public ICollection<UserEmail> UserEmails { get; set; }
}

public class Email {
    public int EmailID { get; set; }
    public string Address { get; set; }

    public ICollection<UserEmail> UserEmails { get; set; }
}

public class UserEmail {
    public int UserID { get; set; }
    public int EmailID { get; set; }
    public bool IsPrimary { get; set; }
}

On your DbContext derived class you could do this:

public class MyContext : DbContext {
    protected override void OnModelCreating(DbModelBuilder builder) {
        // Primary keys
        builder.Entity<User>().HasKey(q => q.UserID);
        builder.Entity<Email>().HasKey(q => q.EmailID);
        builder.Entity<UserEmail>().HasKey(q => 
            new { 
                q.UserID, q.EmailID
            });

        // Relationships
        builder.Entity<UserEmail>()
            .HasRequired(t => t.Email)
            .WithMany(t => t.UserEmails)
            .HasForeignKey(t => t.EmailID)

        builder.Entity<UserEmail>()
            .HasRequired(t => t.User)
            .WithMany(t => t.UserEmails)
            .HasForeignKey(t => t.UserID)
    }
}

It has the same effect as the accepted answer, with a different approach, which is no better nor worse.

How to remove text from a string?

Ex:-

var value="Data-123";
var removeData=value.replace("Data-","");
alert(removeData);

Hopefully this will work for you.

CAST DECIMAL to INT

The CAST() function does not support the "official" data type "INT" in MySQL, it's not in the list of supported types. With MySQL, "SIGNED" (or "UNSIGNED") could be used instead:

CAST(columnName AS SIGNED)

However, this seems to be MySQL-specific (not standardized), so it may not work with other databases. At least this document (Second Informal Review Draft) ISO/IEC 9075:1992, Database does not list "SIGNED"/"UNSIGNED" in section 4.4 Numbers.

But DECIMAL is both standardized and supported by MySQL, so the following should work for MySQL (tested) and other databases:

CAST(columnName AS DECIMAL(0))

According to the MySQL docs:

If the scale is 0, DECIMAL values contain no decimal point or fractional part.

Python: Differentiating between row and column vectors

I think you can use ndmin option of numpy.array. Keeping it to 2 says that it will be a (4,1) and transpose will be (1,4).

>>> a = np.array([12, 3, 4, 5], ndmin=2)
>>> print a.shape
>>> (1,4)
>>> print a.T.shape
>>> (4,1)

Unable to load DLL (Module could not be found HRESULT: 0x8007007E)

Ensure that all dependencies of your own dll are present near the dll, or in System32.

For Loop on Lua

By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:

Way1

names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end

Way2

names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end

Way1 uses the table index/key , on your table names each element has a key starting from 1, for example:

names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John

So you just make i go from 1 to 3.

On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:

names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end

prints the following:

1   John
2   Joe
myKey   myValue

Why write <script type="text/javascript"> when the mime type is set by the server?

Douglas Crockford says:

type="text/javascript"

This attribute is optional. Since Netscape 2, the default programming language in all browsers has been JavaScript. In XHTML, this attribute is required and unnecessary. In HTML, it is better to leave it out. The browser knows what to do.

He also says:

W3C did not adopt the language attribute, favoring instead a type attribute which takes a MIME type. Unfortunately, the MIME type was not standardized, so it is sometimes "text/javascript" or "application/ecmascript" or something else. Fortunately, all browsers will always choose JavaScript as the default programming language, so it is always best to simply write <script>. It is smallest, and it works on the most browsers.

For entertainment purposes only, I tried out the following five scripts

  <script type="application/ecmascript">alert("1");</script>
  <script type="text/javascript">alert("2");</script>
  <script type="baloney">alert("3");</script>
  <script type="">alert("4");</script>
  <script >alert("5");</script>

On Chrome, all but script 3 (type="baloney") worked. IE8 did not run script 1 (type="application/ecmascript") or script 3. Based on my non-extensive sample of two browsers, it looks like you can safely ignore the type attribute, but that it you use it you better use a legal (browser dependent) value.

Java executors: how to be notified, without blocking, when a task completes?

Just to add to Matt's answer, which helped, here is a more fleshed-out example to show the use of a callback.

private static Primes primes = new Primes();

public static void main(String[] args) throws InterruptedException {
    getPrimeAsync((p) ->
        System.out.println("onPrimeListener; p=" + p));

    System.out.println("Adios mi amigito");
}
public interface OnPrimeListener {
    void onPrime(int prime);
}
public static void getPrimeAsync(OnPrimeListener listener) {
    CompletableFuture.supplyAsync(primes::getNextPrime)
        .thenApply((prime) -> {
            System.out.println("getPrimeAsync(); prime=" + prime);
            if (listener != null) {
                listener.onPrime(prime);
            }
            return prime;
        });
}

The output is:

    getPrimeAsync(); prime=241
    onPrimeListener; p=241
    Adios mi amigito

How to paste into a terminal?

In Konsole (KDE terminal) is the same, Ctrl + Shift + V

Initialize array of strings

This example program illustrates initialization of an array of C strings.

#include <stdio.h>

const char * array[] = {
    "First entry",
    "Second entry",
    "Third entry",
};

#define n_array (sizeof (array) / sizeof (const char *))

int main ()
{
    int i;

    for (i = 0; i < n_array; i++) {
        printf ("%d: %s\n", i, array[i]);
    }
    return 0;
}

It prints out the following:

0: First entry
1: Second entry
2: Third entry

Window vs Page vs UserControl for WPF navigation?

All depends on the app you're trying to build. Use Windows if you're building a dialog based app. Use Pages if you're building a navigation based app. UserControls will be useful regardless of the direction you go as you can use them in both Windows and Pages.

A good place to start exploring is here: http://windowsclient.net/learn

C#: How would I get the current time into a string?

You can use format strings as well.

string time = DateTime.Now.ToString("hh:mm:ss"); // includes leading zeros
string date = DateTime.Now.ToString("dd/MM/yy"); // includes leading zeros

or some shortcuts if the format works for you

string time = DateTime.Now.ToShortTimeString();
string date = DateTime.Now.ToShortDateString();

Either should work.

Excel: Use a cell value as a parameter for a SQL query

queryString = "SELECT name FROM user WHERE id=" & Worksheets("Sheet1").Range("D4").Value

Alternative to google finance api

I'm way late, but check out Quandl. They have an API for stock prices and fundamentals.

Here's an example call, using Quandl-api download in csv

example:

https://www.quandl.com/api/v1/datasets/WIKI/AAPL.csv?column=4&sort_order=asc&collapse=quarterly&trim_start=2012-01-01&trim_end=2013-12-31

They support these languages. Their source data comes from Yahoo Finance, Google Finance, NSE, BSE, FSE, HKEX, LSE, SSE, TSE and more (see here).

Invoke-WebRequest, POST with parameters

This just works:

$body = @{
 "UserSessionId"="12345678"
 "OptionalEmail"="[email protected]"
} | ConvertTo-Json

$header = @{
 "Accept"="application/json"
 "connectapitoken"="97fe6ab5b1a640909551e36a071ce9ed"
 "Content-Type"="application/json"
} 

Invoke-RestMethod -Uri "http://MyServer/WSVistaWebClient/RESTService.svc/member/search" -Method 'Post' -Body $body -Headers $header | ConvertTo-HTML

How many characters in varchar(max)

From http://msdn.microsoft.com/en-us/library/ms176089.aspx

varchar [ ( n | max ) ] Variable-length, non-Unicode character data. n can be a value from 1 through 8,000. max indicates that the maximum storage size is 2^31-1 bytes. The storage size is the actual length of data entered + 2 bytes. The data entered can be 0 characters in length. The ISO synonyms for varchar are char varying or character varying.

1 character = 1 byte. And don't forget 2 bytes for the termination. So, 2^31-3 characters.

Get query from java.sql.PreparedStatement

I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.

Convert decimal to hexadecimal in UNIX shell script

This is not a shell script, but it is the cli tool I'm using to convert numbers among bin/oct/dec/hex:

    #!/usr/bin/perl

    if (@ARGV < 2) {
      printf("Convert numbers among bin/oct/dec/hex\n");
      printf("\nUsage: base b/o/d/x num num2 ... \n");
      exit;
    }

    for ($i=1; $i<@ARGV; $i++) {
      if ($ARGV[0] eq "b") {
                    $num = oct("0b$ARGV[$i]");
      } elsif ($ARGV[0] eq "o") {
                    $num = oct($ARGV[$i]);
      } elsif ($ARGV[0] eq "d") {
                    $num = $ARGV[$i];
      } elsif ($ARGV[0] eq "h") {
                    $num = hex($ARGV[$i]);
      } else {
                    printf("Usage: base b/o/d/x num num2 ... \n");
                    exit;
      }
      printf("0x%x = 0d%d = 0%o = 0b%b\n", $num, $num, $num, $num);
    }

Fatal error: Call to undefined function mb_detect_encoding()

Hope this helps some ppl, I got this error when i added the path and extension to "docref_root" "docref_ext" in my php.ini file, I then commented it out and it was ok, but cant get my help to work now.

SQL Server loop - how do I loop through a set of records

this way we can iterate into table data.

DECLARE @_MinJobID INT
DECLARE @_MaxJobID INT
CREATE  TABLE #Temp (JobID INT)

INSERT INTO #Temp SELECT * FROM DBO.STRINGTOTABLE(@JobID,',')
SELECT @_MinJID = MIN(JobID),@_MaxJID = MAX(JobID)  FROM #Temp

    WHILE @_MinJID <= @_MaxJID
    BEGIN

        INSERT INTO Mytable        
        (        
            JobID,        
        )        

        VALUES        
        (        
            @_MinJobID,        
        ) 

        SET @_MinJID = @_MinJID + 1;
    END

DROP TABLE #Temp

STRINGTOTABLE is user define function which will parse comma separated data and return table. thanks

What's the difference between & and && in MATLAB?

Both are logical AND operations. The && though, is a "short-circuit" operator. From the MATLAB docs:

They are short-circuit operators in that they evaluate their second operand only when the result is not fully determined by the first operand.

See more here.

ipython notebook clear cell output in code

You can use the IPython.display.clear_output to clear the output as mentioned in cel's answer. I would add that for me the best solution was to use this combination of parameters to print without any "shakiness" of the notebook:

from IPython.display import clear_output

for i in range(10):
    clear_output(wait=True)
    print(i, flush=True)

hibernate could not get next sequence value

You need to set your @GeneratedId column with strategy GenerationType.IDENTITY instead of GenerationType.AUTO

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "JUD_ID")
private Long _judId;

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

MySQL GROUP BY two columns

Using Concat on the group by will work

SELECT clients.id, clients.name, portfolios.id, SUM ( portfolios.portfolio + portfolios.cash ) AS total
FROM clients, portfolios
WHERE clients.id = portfolios.client_id
GROUP BY CONCAT(portfolios.id, "-", clients.id)
ORDER BY total DESC
LIMIT 30

Linq filter List<string> where it contains a string value from another List<string>

you can do that

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));

How to set cell spacing and UICollectionView - UICollectionViewFlowLayout size ratio?

If you are looking for Swift 3, Follow the steps to achieve this:

func viewDidLoad() {

    //Define Layout here
    let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()

    //Get device width
    let width = UIScreen.main.bounds.width

    //set section inset as per your requirement.
    layout.sectionInset = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 5)

    //set cell item size here 
    layout.itemSize = CGSize(width: width / 2, height: width / 2)

    //set Minimum spacing between 2 items
    layout.minimumInteritemSpacing = 0

    //set minimum vertical line spacing here between two lines in collectionview
    layout.minimumLineSpacing = 0

    //apply defined layout to collectionview
    collectionView!.collectionViewLayout = layout

}

This is verified on Xcode 8.0 with Swift 3.

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

Java Desktop application: SWT vs. Swing

I would use Swing for a couple of reasons.

  • It has been around longer and has had more development effort applied to it. Hence it is likely more feature complete and (maybe) has fewer bugs.

  • There is lots of documentation and other guidance on producing performant applications.

  • It seems like changes to Swing propagate to all platforms simultaneously while changes to SWT seem to appear on Windows first, then Linux.

If you want to build a very feature-rich application, you might want to check out the NetBeans RCP (Rich Client Platform). There's a learning curve, but you can put together nice applications quickly with a little practice. I don't have enough experience with the Eclipse platform to make a valid judgment.

If you don't want to use the entire RCP, NetBeans also has many useful components that can be pulled out and used independently.

One other word of advice, look into different layout managers. They tripped me up for a long time when I was learning. Some of the best aren't even in the standard library. The MigLayout (for both Swing and SWT) and JGoodies Forms tools are two of the best in my opinion.

PHP Multiple Checkbox Array

Try this, by for Loop

<form method="post">
<?php
for ($i=1; $i <5 ; $i++) 
{ 
    echo'<input type="checkbox" value="'.$i.'" name="checkbox[]"/>';
} 
?>
<input type="submit" name="submit" class="form-control" value="Submit">  
</form>

<?php 
if(isset($_POST['submit']))
{
    $check=implode(", ", $_POST['checkbox']);
    print_r($check);
}     
?>

Node.js request CERT_HAS_EXPIRED

I think the strictSSL: false should (should have worked, even in 2013) work. So in short are three possible ways:

  1. (obvious) Get your CA to renew the certificate, and put it on your server!
  2. Change the default settings of your request object:

    const myRequest = require('request').defaults({strictSSL: false})

    Many modules that use node-request internally also allow a request-object to be injected, so you can make them use your modified instance.
  3. (not recommended) Override all certificate checks for all HTTP(S) agent connections by setting the environment variable NODE_TLS_REJECT_UNAUTHORIZED=0 for the Node.js process.

Why does my 'git branch' have no master?

master is just the name of a branch, there's nothing magic about it except it's created by default when a new repository is created.

You can add it back with git checkout -b master.

Create an array or List of all dates between two dates

I know this is an old post but try using an extension method:

    public static IEnumerable<DateTime> Range(this DateTime startDate, DateTime endDate)
    {
        return Enumerable.Range(0, (endDate - startDate).Days + 1).Select(d => startDate.AddDays(d));
    }

and use it like this

    var dates = new DateTime(2000, 1, 1).Range(new DateTime(2000, 1, 31));

Feel free to choose your own dates, you don't have to restrict yourself to January 2000.

.htaccess - how to force "www." in a generic way?

This won't work with subdomains.

domain.com correctly gets redirected to www.domain.com

but

images.domain.com gets redirected to www.images.domain.com

Instead of checking if the subdomain is "not www", check if there are two dots:

RewriteCond %{HTTP_HOST} ^(.*)$ [NC]
RewriteCond %{HTTP_HOST} !^(.*)\.(.*)\. [NC]
RewriteCond %{HTTPS}s ^on(s)|
RewriteRule ^ HTTP%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

How to find the Windows version from the PowerShell command line

Since you have access to the .NET library, you could access the OSVersion property of the System.Environment class to get this information. For the version number, there is the Version property.

For example,

PS C:\> [System.Environment]::OSVersion.Version

Major  Minor  Build  Revision
-----  -----  -----  --------
6      1      7601   65536

Details of Windows versions can be found here.

Best way to represent a Grid or Table in AngularJS with Bootstrap 3?

I had the same requirement and solved it using these components:

The table component ng-grid is capable of displaying hundreds of rows in a scrollable grid. If you have to deal with thousands of entries you are better off using ng-grid's paginator. The documentation of ng-grid is excellent and contains many examples. Sorting and searching are supported even in combination with pagination.

Here is a screenshot from a current project to give you an impression how it looks like:

enter image description here

[UPDATE July 2017]

After having ng-grid in production for a couple of years, I can still tell that there are no major issues with this component. Yes, plenty of minor bugs, but no show stoppers (at least in my use cases). Having said that, I would strongly advice against using this component if you start a project from the scratch. This component is a good option only if you are bound to AngularJS 1.0.x. If you are free to choose the Angular version, go for a newer component. A list of table components for Angular 4 was compiled by Sam Deering in this blog.

jquery get height of iframe content when loaded

simple one-liner starts with a default min-height and increases to contents size.

_x000D_
_x000D_
<iframe src="http://url.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
_x000D_
_x000D_
_x000D_

Implementation difference between Aggregation and Composition in Java

Aggregation vs Composition

Aggregation implies a relationship where the child can exist independently of the parent. For example, Bank and Employee, delete the Bank and the Employee still exist.

whereas Composition implies a relationship where the child cannot exist independent of the parent. Example: Human and heart, heart don’t exist separate to a Human.

Aggregation relation is “has-a” and composition is “part-of” relation.

Composition is a strong Association whereas Aggregation is a weak Association.

How to run an .ipynb Jupyter Notebook from terminal?

I had the same problem and I found papermill. The advantages against the others solutions is that you can see the results while the notebook is running. I find this feature interesting when the notebook takes very long. It is very easy to use:

pip install papermill
papermill notebook.ipynb output.ipynb

It has also, other handy options as saving the output file to Amazon S3, Google Cloud, etc. See the page for more information.

127 Return code from $?

Generally it means:

127 - command not found

but it can also mean that the command is found,
but a library that is required by the command is NOT found.

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

The microsoft telnet.exe is not scriptable without using another script (which needs keyboard focus), as shown in another answer to this question, but there is a free

Telnet Scripting Tool v.1.0 by Albert Yale

that you can google for and which is both scriptable and loggable and can be launched from a batch file without needing keyboard focus.

The problem with telnet.exe and a second script when keyboard focus is being used is that if someone is using the computer at the time the script runs, then it is highly likely that the script will fail due to mouse clicks and keyboard use at that moment in time.

What are the advantages and disadvantages of recursion?

We should use recursion in following scenarios:

  • when we don't know the finite number of iteration for example our fuction exit condition is based on dynamic programming (memoization)
  • when we need to perform operations on reverse order of the elements. Meaning we want to process last element first and then n-1, n-2 and so on till first element

Recursion will save multiple traversals. And it will be useful, if we can divide the stack allocation like:

int N = 10;
int output = process(N) + process(N/2);
public void process(int n) {
    if (n==N/2 + 1 || n==1) {
       return 1;
    }

    return process(n-1) + process(n-2);
}

In this case only half stacks will be allocated at any given time.

Difference between Eclipse Europa, Helios, Galileo

To see a list of the Eclipse release name and it's corresponding version number go to this website. http://en.wikipedia.org/wiki/Eclipse_%28software%29#Release

  • Release Date Platform version
  • Juno ?? June 2012 4.2?
  • Indigo 22 June 2011 3.7
  • Helios 23 June 2010 3.6
  • Galileo 24 June 2009 3.5
  • Ganymede 25 June 2008 3.4
  • Europa 29 June 2007 3.3
  • Callisto 30 June 2006 3.2
  • Eclipse 3.1 28 June 2005 3.1
  • Eclipse 3.0 21 June 2004 3.0

I too dislike the way that the Eclipse foundation DOES NOT use the version number for their downloads or on the Help -> About Eclipse dialog. They do display the version on the download webpage, but the actual file name is something like:

  • eclipse-java-indigo-SR1-linux-gtk.tar.gz
  • eclipse-java-helios-linux-gtk.tar.gz

But over time, you forget what release name goes with what version number. I would much prefer a file naming convention like:

  • eclipse-3.7.1-java-indigo-SR1-linux-gtk.tar.gz
  • eclipse-3.6-java-helios-linux-gtk.tar.gz

This way you get BOTH from the file name and it is sortable in a directory listing. Fortunately, they mostly choose names are alphabetically after the previous one (except for 3.4-Ganymede vs the newer 3.5-Galileo).

angular.min.js.map not found, what is it exactly?

Monkey is right, according to the link given by monkey

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location.

I am not sure if it is angular's fault that no map files were generated. But you can turn off source map files by unchecking this option in chrome console setting

enter image description here

Replace image src location using CSS

you can use: content:url("image.jpg")

<style>
.your-class-name{
    content: url("http://imgur.com/SZ8Cm.jpg");
}
</style>

<img class="your-class-name" src="..."/>

Android Studio : unmappable character for encoding UTF-8

Check all 'C' characters. There are may be some cyrillic 'C's in english-looking word.
Reason for this is that in both english and russian keyboards 'C' occupies same physical button.

CSS div element - how to show horizontal scroll bars only?

I use the CSS properties : 1) "overflow-x: auto"; 2) "overflow-y: hidden"; 3) "white-space: nowrap";

Don't forget to set a Width, both for the container and inner DIVS components. The property "white-space : nowrap" allows the inner DIVS not to drop on a different line.

Considering the following HTML:

<div class="container"> 
  <div class="inner-1"></div>
  <div class="inner-2"></div>
  <div class="inner-3"></div>
</div>

I use the following CSS to have an horizontal scroll only:

.container {
  height: 80px;
  width: 600px;
  overflow-x: auto;
  overflow-y: hidden; 
  white-space: nowrap;
}
.inner-1,.inner-2,.inner-3 {
  height: 60px;
  max-width: 250px;
 display: inline-block; /* this should fix it */
}

Fiddle: https://jsfiddle.net/qrjh93x8/ (not working with the above code)

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

How can I select rows by range?

Assuming id is the primary key of table :

SELECT * FROM table WHERE id BETWEEN 10 AND 50

For first 20 results

SELECT * FROM table order by id limit 20;

How to count the number of occurrences of an element in a List

?If you use Eclipse Collections, you can use a Bag. A MutableBag can be returned from any implementation of RichIterable by calling toBag().

MutableList<String> animals = Lists.mutable.with("bat", "owl", "bat", "bat");
MutableBag<String> bag = animals.toBag();
Assert.assertEquals(3, bag.occurrencesOf("bat"));
Assert.assertEquals(1, bag.occurrencesOf("owl"));

The HashBag implementation in Eclipse Collections is backed by a MutableObjectIntMap.

Note: I am a committer for Eclipse Collections.

Correct way to delete cookies server-side

Use Max-Age=-1 rather than "Expires". It is shorter, less picky about the syntax, and Max-Age takes precedence over Expires anyway.

AngularJS ng-class if-else expression

I had a situation where I needed two 'if' statements that could both go true and an 'else' or default if neither were true, not sure if this is an improvement on Jossef's answer but it seemed cleaner to me:

ng-class="{'class-one' : value.one , 'class-two' : value.two}" class="else-class"

Where value.one and value.two are true, they take precedent over the .else-class

Using switch statement with a range of value in each case?

I know this post is old but I believe this answer deserves some recognition. There is no need to avoid the switch statement. This can be done in java but through the switch statement, not the cases. It involves using ternary operators.

public class Solution {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = Integer.parseInt(sc.nextLine());

        switch ((1 <= num && num <= 5 ) ? 0 :
                (6 <= num && num <= 10) ? 1 : 2) {

            case 0:
                System.out.println("I'm between one and five inclusive.");
                break;
            case 1:
                System.out.println("I'm between 6 and 10 inclusive.");
                break;
            case 2:
                System.out.println("I'm not between one and five or 6 and 10 inclusive.");
                break;
        }
    }
}

How to execute shell command in Javascript

With nashorn you can write a script like this:

$EXEC('find -type f');
var files = $OUT.split('\n');
files.forEach(...
...

and run it:

jjs -scripting each_file.js

Check if MySQL table exists or not

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

Referenced from the PHP docs.

Populating a data frame in R in a loop

this works too.

df = NULL
for (k in 1:10)
    {
       x = 1
       y = 2
       z = 3
       df = rbind(df, data.frame(x,y,z))
     }

output will look like this

df #enter

x y z #col names
1 2 3

What is the use of static constructors?

1.It can only access the static member(s) of the class.

Reason : Non static member is specific to the object instance. If static constructor are allowed to work on non static members it will reflect the changes in all the object instance, which is impractical.

2.There should be no parameter(s) in static constructor.

Reason: Since, It is going to be called by CLR, nobody can pass the parameter to it. 3.Only one static constructor is allowed.

Reason: Overloading needs the two methods to be different in terms of method/constructor definition which is not possible in static constructor.

4.There should be no access modifier to it.

Reason: Again the reason is same call to static constructor is made by CLR and not by the object, no need to have access modifier to it

Error C1083: Cannot open include file: 'stdafx.h'

You have to properly understand what is a "stdafx.h", aka precompiled header. Other questions or Wikipedia will answer that. In many cases a precompiled header can be avoided, especially if your project is small and with few dependencies. In your case, as you probably started from a template project, it was used to include Windows.h only for the _TCHAR macro.

Then, precompiled header is usually a per-project file in Visual Studio world, so:

  1. Ensure you have the file "stdafx.h" in your project. If you don't (e.g. you removed it) just create a new temporary project and copy the default one from there;
  2. Change the #include <stdafx.h> to #include "stdafx.h". It is supposed to be a project local file, not to be resolved in include directories.

Secondly: it's inadvisable to include the precompiled header in your own headers, to not clutter namespace of other source that can use your code as a library, so completely remove its inclusion in vector.h.

Assigning a variable NaN in python without numpy

Use float("nan"):

>>> float("nan")
nan

Use of min and max functions in C++

fmin and fmax, of fminl and fmaxl could be preferred when comparing signed and unsigned integers - you can take advantage of the fact that the entire range of signed and unsigned numbers and you don't have to worry about integer ranges and promotions.

unsigned int x = 4000000000;
int y = -1;

int z = min(x, y);
z = (int)fmin(x, y);

How do I loop through a date range?

You can use the DateTime.AddDays() function to add your DayInterval to the StartDate and check to make sure it is less than the EndDate.

Removing empty rows of a data file in R

This is similar to some of the above answers, but with this, you can specify if you want to remove rows with a percentage of missing values greater-than or equal-to a given percent (with the argument pct)

drop_rows_all_na <- function(x, pct=1) x[!rowSums(is.na(x)) >= ncol(x)*pct,]

Where x is a dataframe and pct is the threshold of NA-filled data you want to get rid of.

pct = 1 means remove rows that have 100% of its values NA. pct = .5 means remome rows that have at least half its values NA

How to Convert JSON object to Custom C# object?

public static class Utilities
{
    public static T Deserialize<T>(string jsonString)
    {
        using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
        {    
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            return (T)serializer.ReadObject(ms);
        }
    }
}

More information go to following link http://ishareidea.blogspot.in/2012/05/json-conversion.html

About DataContractJsonSerializer Class you can read here.

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

Negative matching using grep (match lines that do not contain foo)

In your case, you presumably don't want to use grep, but add instead a negative clause to the find command, e.g.

find /home/baumerf/public_html/ -mmin -60 -not -name error_log

If you want to include wildcards in the name, you'll have to escape them, e.g. to exclude files with suffix .log:

find /home/baumerf/public_html/ -mmin -60 -not -name \*.log

Find the min/max element of an array in JavaScript

Below script worked for me in ndoejs:

 var numbers = [1, 2, 3, 4];
 console.log('Value:: ' + Math.max.apply(null, numbers) ); // 4

What is the difference between "screen" and "only screen" in media queries?

The following is from Adobe docs.


The media queries specification also provides the keyword only, which is intended to hide media queries from older browsers. Like not, the keyword must come at the beginning of the declaration. For example:

media="only screen and (min-width: 401px) and (max-width: 600px)"

Browsers that don't recognize media queries expect a comma-separated list of media types, and the specification says they should truncate each value immediately before the first nonalphanumeric character that isn't a hyphen. So, an old browser should interpret the preceding example as this:

media="only"

Because there is no such media type as only, the stylesheet is ignored. Similarly, an old browser should interpret

media="screen and (min-width: 401px) and (max-width: 600px)"

as

media="screen"

In other words, it should apply the style rules to all screen devices, even though it doesn't know what the media queries mean.

Unfortunately, IE 6–8 failed to implement the specification correctly.

Instead of applying the styles to all screen devices, it ignores the style sheet altogether.

In spite of this behavior, it's still recommended to prefix media queries with only if you want to hide the styles from other, less common browsers.


So, using

media="only screen and (min-width: 401px)"

and

media="screen and (min-width: 401px)"

will have the same effect in IE6-8: both will prevent those styles from being used. They will, however, still be downloaded.

Also, in browsers that support CSS3 media queries, both versions will load the styles if the viewport width is larger than 401px and the media type is screen.

I'm not entirely sure which browsers that don't support CSS3 media queries would need the only version

media="only screen and (min-width: 401px)" 

as opposed to

media="screen and (min-width: 401px)"

to make sure it is not interpreted as

media="screen"

It would be a good test for someone with access to a device lab.

jQuery check if Cookie exists, if not create it

You can set the cookie after having checked if it exists with a value.

 $(document).ready(function(){            
      if ($.cookie('cookie')) { //if cookie isset
         //do stuff here like hide a popup when cookie isset
         //document.getElementById("hideElement").style.display = "none";
      }else{
         var CookieSet = $.cookie('cookie', 'value'); //set cookie
      }       
 });

Find a file with a certain extension in folder

The method below returns only the files with certain extension (eg: file with .txt but not .txt1)

public static IEnumerable<string> GetFilesByExtension(string directoryPath, string extension, SearchOption searchOption)
    {
        return
            Directory.EnumerateFiles(directoryPath, "*" + extension, searchOption)
                .Where(x => string.Equals(Path.GetExtension(x), extension, StringComparison.InvariantCultureIgnoreCase));
    }

Run function in script from command line (Node JS)

This one is dirty but works :)

I will be calling main() function from my script. Previously I just put calls to main at the end of script. However I did add some other functions and exported them from script (to use functions in some other parts of code) - but I dont want to execute main() function every time I import other functions in other scripts.

So I did this, in my script i removed call to main(), and instead at the end of script I put this check:

if (process.argv.includes('main')) {
   main();
}

So when I want to call that function in CLI: node src/myScript.js main

How to make Firefox headless programmatically in Selenium with Python?

The first answer does't work anymore.

This worked for me:

from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium import webdriver

options = FirefoxOptions()
options.add_argument("--headless")
driver = webdriver.Firefox(options=options)
driver.get("http://google.com")

Delete specific line number(s) from a text file using sed?

I would like to propose a generalization with awk.

When the file is made by blocks of a fixed size and the lines to delete are repeated for each block, awk can work fine in such a way

awk '{nl=((NR-1)%2000)+1; if ( (nl<714) || ((nl>1025)&&(nl<1029)) ) print  $0}'
 OriginFile.dat > MyOutputCuttedFile.dat

In this example the size for the block is 2000 and I want to print the lines [1..713] and [1026..1029].

  • NR is the variable used by awk to store the current line number.
  • % gives the remainder (or modulus) of the division of two integers;
  • nl=((NR-1)%BLOCKSIZE)+1 Here we write in the variable nl the line number inside the current block. (see below)
  • || and && are the logical operator OR and AND.
  • print $0 writes the full line

Why ((NR-1)%BLOCKSIZE)+1:
(NR-1) We need a shift of one because 1%3=1, 2%3=2, but 3%3=0.
  +1   We add again 1 because we want to restore the desired order.

+-----+------+----------+------------+
| NR  | NR%3 | (NR-1)%3 | (NR-1)%3+1 |
+-----+------+----------+------------+
|  1  |  1   |    0     |     1      |
|  2  |  2   |    1     |     2      |
|  3  |  0   |    2     |     3      |
|  4  |  1   |    0     |     1      |
+-----+------+----------+------------+

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

Flutter web

For me the error occurred when I run my application in "release" mode

flutter run -d chrome --release

and when I deployed the application on the Firebase hosting

firebase deploy

Solution

Since I initialized Firebase in the index.html, I had to change the implementation order of firebase and main.dart.js

<script>
  var firebaseConfig = {
  apiKey: "xxxxxxxxxxxxxxxxxxxxxx",
  authDomain: "xxxxxxxxxxx.firebaseapp.com",
  databaseURL: "https://xxxxxxxxxx.firebaseio.com",
  projectId: "xxxxxxxxxxx",
  storageBucket: "xxxxxxxx.appspot.com",
  messagingSenderId: "xxxxxxxxxxx",
  appId: "1:xxxxxxxxxx:web:xxxxxxxxxxxxx",
  measurementId: "G-xxxxxxxxx"
  };
  // Initialize Firebase
  firebase.initializeApp(firebaseConfig);
  firebase.analytics();
</script>

//moved below firebase init
<script src="main.dart.js" type="application/javascript"></script>

What does 'foo' really mean?

I think it's meant to mean nothing. The wiki says:

"Foo is commonly used with the metasyntactic variables bar and foobar."

Cannot find Dumpbin.exe

You probably need to open a command prompt with the PATH set up properly. Look for an icon in the start menu that says something like "Visual C++ 2005 Command Prompt". You should be able to run dumpbin (and all the other command line tools) from there.

Multiplication on command line terminal

The classical solution is:

 expr 5 \* 5

expr will only work with integer operands. Another nice option is:

 echo 5 5\*p | dc

dc can be made to work with non-integer operands.

Pass parameters in setInterval function

     setInterval(function(a,b,c){

          console.log(a + b +c);  

      }, 500, 1,2,3);

           //note the console will  print 6
          //here we are passing 1,2,3 for a,b,c arguments
         // tested in node v 8.11 and chrome 69

How can we programmatically detect which iOS version is device running on?

Best current version, without need to deal with numeric search within NSString is to define macros (See original answer: Check iPhone iOS Version)

Those macros do exist in github, see: https://github.com/carlj/CJAMacros/blob/master/CJAMacros/CJAMacros.h

Like this:

#define SYSTEM_VERSION_EQUAL_TO(v)                  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v)              ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v)                 ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v)     ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)

and use them like this:

if (SYSTEM_VERSION_LESS_THAN(@"5.0")) {
    // code here
}

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"6.0")) {
    // code here
}

Outdated version below

to get OS version:

[[UIDevice currentDevice] systemVersion]

returns string, which can be turned into int/float via

-[NSString floatValue]
-[NSString intValue]

like this

Both values (floatValue, intValue) will be stripped due to its type, 5.0.1 will become 5.0 or 5 (float or int), for comparing precisely, you will have to separate it to array of INTs check accepted answer here: Check iPhone iOS Version

NSString *ver = [[UIDevice currentDevice] systemVersion];
int ver_int = [ver intValue];
float ver_float = [ver floatValue];

and compare like this

NSLog(@"System Version is %@",[[UIDevice currentDevice] systemVersion]);
NSString *ver = [[UIDevice currentDevice] systemVersion];
float ver_float = [ver floatValue];
if (ver_float < 5.0) return false;

For Swift 4.0 syntax

below example is just checking if the device is of iOS11 or greater version.

let systemVersion = UIDevice.current.systemVersion
if systemVersion.cgFloatValue >= 11.0 {
    //"for ios 11"
  }
else{
   //"ios below 11")
  }

Unable to Connect to GitHub.com For Cloning

You can try to clone using the HTTPS protocol. Terminal command:

git clone https://github.com/RestKit/RestKit.git

Visual Studio Post Build Event - Copy to Relative Directory Location

If none of the TargetDir or other macros point to the right place, use the ".." directory to go backwards up the folder hierarchy.

ie. Use $(SolutionDir)\..\.. to get your base directory.


For list of all macros, see here:

http://msdn.microsoft.com/en-us/library/c02as0cs.aspx

How do you count the elements of an array in java

What I think you may want is an ArrayList<Integer> instead of an array. This will allow you do to:

ArrayList<Integer> arr = new ArrayList<Integer>(20);
System.out.println(arr.size());

The output will be 0.

Then, you can add things to the list, and it will keep track of the count for you. (It will also grow the size of the backing storage as you need as well.)

Command for restarting all running docker containers?

To start all the containers:

  docker restart $(docker ps -a -q)

Use sudo if you don't have permission to perform this:

sudo docker restart $(sudo docker ps -a -q)

What does Docker add to lxc-tools (the userspace LXC tools)?

The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.

LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.

LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.

Key features of LXD are:

  • Secure by design (unprivileged containers, resource restrictions and much more)
  • Scalable (from containers on your laptop to thousand of compute nodes)
  • Intuitive (simple, clear API and crisp command line experience)
  • Image based (no more distribution templates, only good, trusted images) Live migration

There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.

However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.

The OpenStack nclxd plugin a list of features supported include:

stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support

By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.

How to dynamically build a JSON object with Python?

All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object

(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)

import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)

enter image description here

How to create a new instance from a class object in Python

I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.

class k:
  pass

a = k()
k2 = a.__class__
a2 = k2()

At this point, a and a2 are both instances of the same class (class k).

How to use HTTP_X_FORWARDED_FOR properly?

If you use it in a database, this is a good way:

Set the ip field in database to varchar(250), and then use this:

$theip = $_SERVER["REMOTE_ADDR"];

if (!empty($_SERVER["HTTP_X_FORWARDED_FOR"])) {
    $theip .= '('.$_SERVER["HTTP_X_FORWARDED_FOR"].')';
}

if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
    $theip .= '('.$_SERVER["HTTP_CLIENT_IP"].')';
}

$realip = substr($theip, 0, 250);

Then you just check $realip against the database ip field

How do I create and read a value from cookie?

function setCookie(cname,cvalue,exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays*24*60*60*1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname+"="+cvalue+"; "+expires;
}

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function checkCookie() {
    var user=getCookie("username");
    if (user != "") {
        alert("Welcome again " + user);
    } else {
       user = prompt("Please enter your name:","");
       if (user != "" && user != null) {
           setCookie("username", user, 30);
       }
    }
}

Enter key in textarea

You need to consider the case where the user presses enter in the middle of the text, not just at the end. I'd suggest detecting the enter key in the keyup event, as suggested, and use a regular expression to ensure the value is as you require:

<textarea id="t" rows="4" cols="80"></textarea>
<script type="text/javascript">
    function formatTextArea(textArea) {
        textArea.value = textArea.value.replace(/(^|\r\n|\n)([^*]|$)/g, "$1*$2");
    }

    window.onload = function() {
        var textArea = document.getElementById("t");
        textArea.onkeyup = function(evt) {
            evt = evt || window.event;

            if (evt.keyCode == 13) {
                formatTextArea(this);
            }
        };
    };
</script>

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

I am not sure this will help but I resolved the issue by importing mongoose like below and implementing it as below

const mongoose = require('mongoose')

_id: new mongoose.Types.ObjectId(),

Django REST Framework: adding additional field to ModelSerializer

My response to a similar question (here) might be useful.

If you have a Model Method defined in the following way:

class MyModel(models.Model):
    ...

    def model_method(self):
        return "some_calculated_result"

You can add the result of calling said method to your serializer like so:

class MyModelSerializer(serializers.ModelSerializer):
    model_method_field = serializers.CharField(source='model_method')

p.s. Since the custom field isn't really a field in your model, you'll usually want to make it read-only, like so:

class Meta:
    model = MyModel
    read_only_fields = (
        'model_method_field',
        )

How do you monitor network traffic on the iPhone?

Run it through a proxy and monitor the traffic using Wireshark.

Splitting strings in PHP and get last part

You can use array_pop combined with explode

Code:

$string = 'abc-123-xyz-789';
$output = array_pop(explode("-",$string));
echo $output;

DEMO: Click here

Finding non-numeric rows in dataframe in pandas?

Already some great answers to this question, however here is a nice snippet that I use regularly to drop rows if they have non-numeric values on some columns:

# Eliminate invalid data from dataframe (see Example below for more context)

num_df = (df.drop(data_columns, axis=1)
         .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

num_df = num_df[num_df[data_columns].notnull().all(axis=1)]

The way this works is we first drop all the data_columns from the df, and then use a join to put them back in after passing them through pd.to_numeric (with option 'coerce', such that all non-numeric entries are converted to NaN). The result is saved to num_df.

On the second line we use a filter that keeps only rows where all values are not null.

Note that pd.to_numeric is coercing to NaN everything that cannot be converted to a numeric value, so strings that represent numeric values will not be removed. For example '1.25' will be recognized as the numeric value 1.25.

Disclaimer: pd.to_numeric was introduced in pandas version 0.17.0

Example:

In [1]: import pandas as pd

In [2]: df = pd.DataFrame({"item": ["a", "b", "c", "d", "e"],
   ...:                    "a": [1,2,3,"bad",5],
   ...:                    "b":[0.1,0.2,0.3,0.4,0.5]})

In [3]: df
Out[3]: 
     a    b item
0    1  0.1    a
1    2  0.2    b
2    3  0.3    c
3  bad  0.4    d
4    5  0.5    e

In [4]: data_columns = ['a', 'b']

In [5]: num_df = (df
   ...:           .drop(data_columns, axis=1)
   ...:           .join(df[data_columns].apply(pd.to_numeric, errors='coerce')))

In [6]: num_df
Out[6]: 
  item   a    b
0    a   1  0.1
1    b   2  0.2
2    c   3  0.3
3    d NaN  0.4
4    e   5  0.5

In [7]: num_df[num_df[data_columns].notnull().all(axis=1)]
Out[7]: 
  item  a    b
0    a  1  0.1
1    b  2  0.2
2    c  3  0.3
4    e  5  0.5

Log record changes in SQL server in an audit table

Take a look at this article on Simple-talk.com by Pop Rivett. It walks you through creating a generic trigger that will log the OLDVALUE and the NEWVALUE for all updated columns. The code is very generic and you can apply it to any table you want to audit, also for any CRUD operation i.e. INSERT, UPDATE and DELETE. The only requirement is that your table to be audited should have a PRIMARY KEY (which most well designed tables should have anyway).

Here's the code relevant for your GUESTS Table.

  1. Create AUDIT Table.
    IF NOT EXISTS
          (SELECT * FROM sysobjects WHERE id = OBJECT_ID(N'[dbo].[Audit]') 
                   AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
           CREATE TABLE Audit 
                   (Type CHAR(1), 
                   TableName VARCHAR(128), 
                   PK VARCHAR(1000), 
                   FieldName VARCHAR(128), 
                   OldValue VARCHAR(1000), 
                   NewValue VARCHAR(1000), 
                   UpdateDate datetime, 
                   UserName VARCHAR(128))
    GO
  1. CREATE an UPDATE Trigger on the GUESTS Table as follows.
    CREATE TRIGGER TR_GUESTS_AUDIT ON GUESTS FOR UPDATE
    AS
    
    DECLARE @bit INT ,
           @field INT ,
           @maxfield INT ,
           @char INT ,
           @fieldname VARCHAR(128) ,
           @TableName VARCHAR(128) ,
           @PKCols VARCHAR(1000) ,
           @sql VARCHAR(2000), 
           @UpdateDate VARCHAR(21) ,
           @UserName VARCHAR(128) ,
           @Type CHAR(1) ,
           @PKSelect VARCHAR(1000)
           
    
    --You will need to change @TableName to match the table to be audited. 
    -- Here we made GUESTS for your example.
    SELECT @TableName = 'GUESTS'
    
    -- date and user
    SELECT         @UserName = SYSTEM_USER ,
           @UpdateDate = CONVERT (NVARCHAR(30),GETDATE(),126)
    
    -- Action
    IF EXISTS (SELECT * FROM inserted)
           IF EXISTS (SELECT * FROM deleted)
                   SELECT @Type = 'U'
           ELSE
                   SELECT @Type = 'I'
    ELSE
           SELECT @Type = 'D'
    
    -- get list of columns
    SELECT * INTO #ins FROM inserted
    SELECT * INTO #del FROM deleted
    
    -- Get primary key columns for full outer join
    SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                   + ' i.' + c.COLUMN_NAME + ' = d.' + c.COLUMN_NAME
           FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
    
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE   pk.TABLE_NAME = @TableName
           AND     CONSTRAINT_TYPE = 'PRIMARY KEY'
           AND     c.TABLE_NAME = pk.TABLE_NAME
           AND     c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
    
    -- Get primary key select for insert
    SELECT @PKSelect = COALESCE(@PKSelect+'+','') 
           + '''<' + COLUMN_NAME 
           + '=''+convert(varchar(100),
    coalesce(i.' + COLUMN_NAME +',d.' + COLUMN_NAME + '))+''>''' 
           FROM    INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk ,
                   INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE   pk.TABLE_NAME = @TableName
           AND     CONSTRAINT_TYPE = 'PRIMARY KEY'
           AND     c.TABLE_NAME = pk.TABLE_NAME
           AND     c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME
    
    IF @PKCols IS NULL
    BEGIN
           RAISERROR('no PK on table %s', 16, -1, @TableName)
           RETURN
    END
    
    SELECT         @field = 0, 
           @maxfield = MAX(ORDINAL_POSITION) 
           FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName
    WHILE @field < @maxfield
    BEGIN
           SELECT @field = MIN(ORDINAL_POSITION) 
                   FROM INFORMATION_SCHEMA.COLUMNS 
                   WHERE TABLE_NAME = @TableName 
                   AND ORDINAL_POSITION > @field
           SELECT @bit = (@field - 1 )% 8 + 1
           SELECT @bit = POWER(2,@bit - 1)
           SELECT @char = ((@field - 1) / 8) + 1
           IF SUBSTRING(COLUMNS_UPDATED(),@char, 1) & @bit > 0
                                           OR @Type IN ('I','D')
           BEGIN
                   SELECT @fieldname = COLUMN_NAME 
                           FROM INFORMATION_SCHEMA.COLUMNS 
                           WHERE TABLE_NAME = @TableName 
                           AND ORDINAL_POSITION = @field
                   SELECT @sql = '
    insert Audit (    Type, 
                   TableName, 
                   PK, 
                   FieldName, 
                   OldValue, 
                   NewValue, 
                   UpdateDate, 
                   UserName)
    select ''' + @Type + ''',''' 
           + @TableName + ''',' + @PKSelect
           + ',''' + @fieldname + ''''
           + ',convert(varchar(1000),d.' + @fieldname + ')'
           + ',convert(varchar(1000),i.' + @fieldname + ')'
           + ',''' + @UpdateDate + ''''
           + ',''' + @UserName + ''''
           + ' from #ins i full outer join #del d'
           + @PKCols
           + ' where i.' + @fieldname + ' <> d.' + @fieldname 
           + ' or (i.' + @fieldname + ' is null and  d.'
                                    + @fieldname
                                    + ' is not null)' 
           + ' or (i.' + @fieldname + ' is not null and  d.' 
                                    + @fieldname
                                    + ' is null)' 
                   EXEC (@sql)
           END
    END
    
    GO

How to join two sets in one line without using "|"

Assuming you also can't use s.union(t), which is equivalent to s | t, you could try

>>> from itertools import chain
>>> set(chain(s,t))
set([1, 2, 3, 4, 5, 6])

Or, if you want a comprehension,

>>> {i for j in (s,t) for i in j}
set([1, 2, 3, 4, 5, 6])

How to convert comma-delimited string to list in Python?

You can use the str.split method.

>>> my_string = 'A,B,C,D,E'
>>> my_list = my_string.split(",")
>>> print my_list
['A', 'B', 'C', 'D', 'E']

If you want to convert it to a tuple, just

>>> print tuple(my_list)
('A', 'B', 'C', 'D', 'E')

If you are looking to append to a list, try this:

>>> my_list.append('F')
>>> print my_list
['A', 'B', 'C', 'D', 'E', 'F']

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

Using WAMP is perforce option if we want to use more then one version of php.

How to select a single child element using jQuery?

Not jQuery, as the question asks for, but natively (i.e., no libraries required) I think the better tool for the job is querySelector to get a single instance of a selector:

let el = document.querySelector('img');
console.log(el);

For all matching instances, use document.querySelectorAll(), or for those within another element you can chain as follows:

// Get some wrapper, with class="parentClassName"
let parentEl = document.querySelector('.parentClassName');
// Get all img tags within the parent element by parentEl variable
let childrenEls = parentEl.querySelectorAll('img');

Note the above is equivalent to:

let childrenEls = document.querySelector('.parentClassName').querySelectorAll('img');

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Plenty of responses already, but you can use this:

Sub runQry(qDefName)
    Dim db As DAO.Database, qd As QueryDef, par As Parameter

    Set db = CurrentDb
    Set qd = db.QueryDefs(qDefName)

    On Error Resume Next
    For Each par In qd.Parameters
        Err.Clear
        par.Value = Eval(par.Name)          'try evaluating param
        If Err.Number <> 0 Then             'failed ?
            par.Value = InputBox(par.Name)  'ask for value
        End If
    Next par
    On Error GoTo 0

    qd.Execute dbFailOnError
End Sub

Sub runQry_test()
    runQry "test"  'qryDef name
End Sub

How to change value of process.env.PORT in node.js?

EDIT: Per @sshow's comment, if you're trying to run your node app on port 80, the below is not the best way to do it. Here's a better answer: How do I run Node.js on port 80?

Original Answer:

If you want to do this to run on port 80 (or want to set the env variable more permanently),

  1. Open up your bash profile vim ~/.bash_profile
  2. Add the environment variable to the file export PORT=80
  3. Open up the sudoers config file sudo visudo
  4. Add the following line to the file exactly as so Defaults env_keep +="PORT"

Now when you run sudo node app.js it should work as desired.

How to connect android wifi to adhoc wifi?

I did notice something of interest here: In my 2.3.4 phone I can't see AP/AdHoc SSIDs in the Settings > Wireless & Networks menu. On an Acer A500 running 4.0.3 I do see them, prefixed by (*)

However in the following bit of code that I adapted from (can't remember source, sorry!) I do see the Ad Hoc show up in the Wifi Scan on my 2.3.4 phone. I am still looking to actually connect and create a socket + input/outputStream. But, here ya go:

    public class MainActivity extends Activity {

private static final String CHIPKIT_BSSID = "E2:14:9F:18:40:1C";
private static final int CHIPKIT_WIFI_PRIORITY = 1;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final Button btnDoSomething = (Button) findViewById(R.id.btnDoSomething);
    final Button btnNewScan = (Button) findViewById(R.id.btnNewScan);
    final TextView textWifiManager = (TextView) findViewById(R.id.WifiManager);
    final TextView textWifiInfo = (TextView) findViewById(R.id.WifiInfo);
    final TextView textIp = (TextView) findViewById(R.id.Ip);

    final WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    final WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();

    WifiConfiguration wifiConfiguration = new WifiConfiguration();
    wifiConfiguration.BSSID = CHIPKIT_BSSID;
    wifiConfiguration.priority = CHIPKIT_WIFI_PRIORITY;
    wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
    wifiConfiguration.allowedKeyManagement.set(KeyMgmt.NONE);
    wifiConfiguration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
    wifiConfiguration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
    wifiConfiguration.status = WifiConfiguration.Status.ENABLED;

    myWifiManager.setWifiEnabled(true);

    int netID = myWifiManager.addNetwork(wifiConfiguration);

    myWifiManager.enableNetwork(netID, true);

    textWifiInfo.setText("SSID: " + myWifiInfo.getSSID() + '\n' 
            + myWifiManager.getWifiState() + "\n\n");

    btnDoSomething.setOnClickListener(new View.OnClickListener() {          
        public void onClick(View v) {
            clearTextViews(textWifiManager, textIp);                
        }           
    });

    btnNewScan.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            getNewScan(myWifiManager, textWifiManager, textIp);
        }
    });     
}

private void clearTextViews(TextView...tv) {
    for(int i = 0; i<tv.length; i++){
        tv[i].setText("");
    }       
}

public void getNewScan(WifiManager wm, TextView...textViews) {
    wm.startScan();

    List<ScanResult> scanResult = wm.getScanResults();

    String scan = "";

    for (int i = 0; i < scanResult.size(); i++) {
        scan += (scanResult.get(i).toString() + "\n\n");
    }

    textViews[0].setText(scan);
    textViews[1].setText(wm.toString());
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

Don't forget that in Eclipse you can use Ctrl+Shift+[letter O] to fill in the missing imports...

and my manifest:

    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.digilent.simpleclient"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

Hope that helps!

How do I check if a variable exists?

for objects/modules, you can also

'var' in dir(obj)

For example,

>>> class Something(object):
...     pass
...
>>> c = Something()
>>> c.a = 1
>>> 'a' in dir(c)
True
>>> 'b' in dir(c)
False

How to transfer some data to another Fragment?

getArguments() is returning null because "Its doesn't get anything"

Try this code to handle this situation

if(getArguments()!=null)
{
int myInt = getArguments().getInt(key, defaultValue);
}

How do I select a random value from an enumeration?

You could just do this:

var rnd = new Random();
return (MyEnum) rnd.Next(Enum.GetNames(typeof(MyEnum)).Length);

No need to store arrays

Is there any simple way to convert .xls file to .csv file? (Excel)

Here's a C# method to do this. Remember to add your own error handling - this mostly assumes that things work for the sake of brevity. It's 4.0+ framework only, but that's mostly because of the optional worksheetNumber parameter. You can overload the method if you need to support earlier versions.

static void ConvertExcelToCsv(string excelFilePath, string csvOutputFile, int worksheetNumber = 1) {
   if (!File.Exists(excelFilePath)) throw new FileNotFoundException(excelFilePath);
   if (File.Exists(csvOutputFile)) throw new ArgumentException("File exists: " + csvOutputFile);

   // connection string
   var cnnStr = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Extended Properties=\"Excel 8.0;IMEX=1;HDR=NO\"", excelFilePath);
   var cnn = new OleDbConnection(cnnStr);

   // get schema, then data
   var dt = new DataTable();
   try {
      cnn.Open();
      var schemaTable = cnn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
      if (schemaTable.Rows.Count < worksheetNumber) throw new ArgumentException("The worksheet number provided cannot be found in the spreadsheet");
      string worksheet = schemaTable.Rows[worksheetNumber - 1]["table_name"].ToString().Replace("'", "");
      string sql = String.Format("select * from [{0}]", worksheet);
      var da = new OleDbDataAdapter(sql, cnn);
      da.Fill(dt);
   }
   catch (Exception e) {
      // ???
      throw e;
   }
   finally {
      // free resources
      cnn.Close();
   }

   // write out CSV data
   using (var wtr = new StreamWriter(csvOutputFile)) {
      foreach (DataRow row in dt.Rows) {
         bool firstLine = true;
         foreach (DataColumn col in dt.Columns) {
            if (!firstLine) { wtr.Write(","); } else { firstLine = false; }
            var data = row[col.ColumnName].ToString().Replace("\"", "\"\"");
            wtr.Write(String.Format("\"{0}\"", data));
         }
         wtr.WriteLine();
      }
   }
}

XPath to select element based on childs child value

Almost there. In your predicate, you want a relative path, so change

./book[/author/name = 'John'] 

to either

./book[author/name = 'John'] 

or

./book[./author/name = 'John'] 

and you will match your element. Your current predicate goes back to the root of the document to look for an author.

What does href expression <a href="javascript:;"></a> do?

<a href="javascript:alert('Hello');"></a>

is just shorthand for:

<a href="" onclick="alert('Hello'); return false;"></a>

Android Animation Alpha

View.setOnTouchListener { v, event ->
    when (event.action) {
        MotionEvent.ACTION_DOWN -> {
            v.alpha = 0f
            v.invalidate()
        }
        MotionEvent.ACTION_UP -> {
            v.alpha = 1f
            v.invalidate()


        }
    }
    false
}

How can I delete derived data in Xcode 8?

Go to Xcode -> Project Settings

enter image description here

You can find the way to go to derived Data

enter image description here

SQL: How do I SELECT only the rows with a unique value on certain column?

Utilizing the "dynamic table" capability in SQL Server (querying against a parenthesis-surrounded query), you can return 2000, 49 w/ the following. If your platform doesn't offer an equivalent to the "dynamic table" ANSI-extention, you can always utilize a temp table in two-steps/statement by inserting the results within the "dynamic table" to a temp table, and then performing a subsequent select on the temp table.

DECLARE  @T TABLE(
    [contract] INT,
    project INT,
    activity INT
)

INSERT INTO @T VALUES( 1000,    8000,    10 )
INSERT INTO @T VALUES( 1000,    8000,    20 )
INSERT INTO @T VALUES( 1000,    8001,    10 )
INSERT INTO @T VALUES( 2000,    9000,    49 )
INSERT INTO @T VALUES( 2000,    9001,    49 )
INSERT INTO @T VALUES( 3000,    9000,    79 )
INSERT INTO @T VALUES( 3000,    9000,    78 )

SELECT
    [contract],
    [Activity] =  max (activity)
FROM
    (
    SELECT
        [contract],
        [Activity]
    FROM
        @T
    GROUP BY
        [contract],
        [Activity]
    ) t
GROUP BY
    [contract]
HAVING count (*) = 1

How to set the max value and min value of <input> in html5 by javascript or jquery?

jQuery makes it easy to set any attributes for an element - just use the .attr() method:

$(document).ready(function() {
    $("input").attr({
       "max" : 10,        // substitute your own
       "min" : 2          // values (or variables) here
    });
});

The document ready handler is not required if your script block appears after the element(s) you want to manipulate.

Using a selector of "input" will set the attributes for all inputs though, so really you should have some way to identify the input in question. If you gave it an id you could say:

$("#idHere").attr(...

...or with a class:

$(".classHere").attr(...

How to set a Postgresql default value datestamp like 'YYYYMM'?

Right. Better to use a function:

CREATE OR REPLACE FUNCTION yyyymm() RETURNS text
    LANGUAGE 'plpgsql' AS $$
DECLARE
    retval text;
    m integer;
BEGIN
    retval := EXTRACT(year from current_timestamp);
    m := EXTRACT(month from current_timestamp);
    IF m < 10 THEN retval := retval || '0'; END IF;
    RETURN retval || m;
END $$;

SELECT yyyymm();

DROP TABLE foo;
CREATE TABLE foo (
    key             int PRIMARY KEY,
    colname text DEFAULT yyyymm()
    );
INSERT INTO foo (key) VALUES (0);
SELECT * FROM FOO;

This gives me

 key | colname 
-----+---------
   0 | 200905

Make sure you run createlang plpgsql from the Unix command line, if necessary.

Create directory if it does not exist

I had the exact same problem. You can use something like this:

$local = Get-Location;
$final_local = "C:\Processing";

if(!$local.Equals("C:\"))
{
    cd "C:\";
    if((Test-Path $final_local) -eq 0)
    {
        mkdir $final_local;
        cd $final_local;
        liga;
    }

    ## If path already exists
    ## DB Connect
    elseif ((Test-Path $final_local) -eq 1)
    {
        cd $final_local;
        echo $final_local;
        liga;  (function created by you TODO something)
    }
}

How to get an object's methods?

for me, the only reliable way to get the methods of the final extending class, was to do like this:

function getMethodsOf(obj){
  const methods = {}
  Object.getOwnPropertyNames( Object.getPrototypeOf(obj) ).forEach(methodName => {
    methods[methodName] = obj[methodName]
  })
  return methods
}

Issue pushing new code in Github

Assuming that you added the Readme.md file through the interface provided by github, the readme is not yet in your local folder. Hence, when you try to push to the remote repo, you get an error, because your local repo is lacking the readme file - it's "behind the times", so to speak. Hence, as is suggested in the error message, try "git pull" first. This will pull the readme from the remote repository and merge it with your local directory. After that, you should have no problem pushing to the remote repo (the commands you posted look valid to me).

Replace negative values in an numpy array

And yet another possibility:

In [2]: a = array([1, 2, 3, -4, 5])

In [3]: where(a<0, 0, a)
Out[3]: array([1, 2, 3, 0, 5])

How to position a div scrollbar on the left hand side?

Here is what I have done to make the right scroll bar work. The only thing needed to be considered is when using 'direction: rtl' and whole table also need to be changed. Hopefully this gives you an idea how to do it.

Example:

<table dir='rtl'><tr><td>Display Last</td><td>Display Second</td><td>Display First</td></table>

Check this: JSFiddle

Deep copy, shallow copy, clone

  • Deep copy: Clone this object and every reference to every other object it has
  • Shallow copy: Clone this object and keep its references
  • Object clone() throws CloneNotSupportedException: It is not specified whether this should return a deep or shallow copy, but at the very least: o.clone() != o

How to create threads in nodejs

You can get multi-threading using Napa.js.

https://github.com/Microsoft/napajs

"Napa.js is a multi-threaded JavaScript runtime built on V8, which was originally designed to develop highly iterative services with non-compromised performance in Bing. As it evolves, we find it useful to complement Node.js in CPU-bound tasks, with the capability of executing JavaScript in multiple V8 isolates and communicating between them. Napa.js is exposed as a Node.js module, while it can also be embedded in a host process without Node.js dependency."

Explanation of <script type = "text/template"> ... </script>

By setting script tag type other than text/javascript, browser will not execute the internal code of script tag. This is called micro template. This concept is widely used in Single page application(aka SPA).

<script type="text/template">I am a Micro template. 
  I am going to make your web page faster.</script>

For micro template, type of the script tag is text/template. It is very well explained by Jquery creator John Resig http://ejohn.org/blog/javascript-micro-templating/

String to decimal conversion: dot separation instead of comma

I had faced the similar issue while using Convert.ToSingle(my_value) If the OS language settings is English 2.5 (example) will be taken as 2.5 If the OS language is German, 2.5 will be treated as 2,5 which is 25 I used the invariantculture IFormat provided and it works. It always treats '.' as '.' instead of ',' irrespective of the system language.

float var = Convert.ToSingle(my_value, System.Globalization.CultureInfo.InvariantCulture);

What is the difference between display: inline and display: inline-block?

splattne's answer probably covered most of everything so I won't repeat the same thing, but: inline and inline-block behave differently with the direction CSS property.

Within the next snippet you see one two (in order) is rendered, like it does in LTR layouts. I suspect the browser here auto-detected the English part as LTR text and rendered it from left to right.

_x000D_
_x000D_
body {_x000D_
  text-align: right;_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
  display: inline;_x000D_
}
_x000D_
<h2>_x000D_
  ??? ????? ????_x000D_
  <span>one</span>_x000D_
  <span>two</span>_x000D_
</h2>
_x000D_
_x000D_
_x000D_

However, if I go ahead and set display to inline-block, the browser appears to respect the direction property and render the elements from right to left in order, so that two one is rendered.

_x000D_
_x000D_
body {_x000D_
  text-align: right;_x000D_
  direction: rtl;_x000D_
}_x000D_
_x000D_
h2 {_x000D_
  display: block; /* just being explicit */_x000D_
}_x000D_
_x000D_
span {_x000D_
  display: inline-block;_x000D_
}
_x000D_
<h2>_x000D_
  ??? ????? ????_x000D_
  <span>one</span>_x000D_
  <span>two</span>_x000D_
</h2>
_x000D_
_x000D_
_x000D_

I don't know if there are any other quirks to this, I only found about this empirically on Chrome.

Return index of greatest value in an array

If you are utilizing underscore, you can use this nice short one-liner:

_.indexOf(arr, _.max(arr))

It will first find the value of the largest item in the array, in this case 22. Then it will return the index of where 22 is within the array, in this case 2.

Swift 3 - Comparing Date objects

in Swift 3,4 you should use "Compare". for example:

DateArray.sort { (($0)?.compare($1))! == .orderedDescending }

Edittext change border color with shape.xml

Use root tag as shape instead of selector in your shape.xml file, and it will resolve your problem!

Android Studio: “Execution failed for task ':app:mergeDebugResources'” if project is created on drive C:

For developers who live in Iran, Just rebuild while offline. You're done! (it's related to sanctions!)

How to use BeginInvoke C#

I guess your code relates to Windows Forms.
You call BeginInvoke if you need something to be executed asynchronously in the UI thread: change control's properties in most of the cases.
Roughly speaking this is accomplished be passing the delegate to some procedure which is being periodically executed. (message loop processing and the stuff like that)

If BeginInvoke is called for Delegate type the delegate is just invoked asynchronously.
(Invoke for the sync version.)

If you want more universal code which works perfectly for WPF and WinForms you can consider Task Parallel Library and running the Task with the according context. (TaskScheduler.FromCurrentSynchronizationContext())

And to add a little to already said by others: Lambdas can be treated either as anonymous methods or expressions.
And that is why you cannot just use var with lambdas: compiler needs a hint.

UPDATE:

this requires .Net v4.0 and higher

// This line must be called in UI thread to get correct scheduler
var scheduler = System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext();

// this can be called anywhere
var task = new System.Threading.Tasks.Task( () => someformobj.listBox1.SelectedIndex = 0);

// also can be called anywhere. Task  will be scheduled for execution.
// And *IF I'm not mistaken* can be (or even will be executed synchronously)
// if this call is made from GUI thread. (to be checked) 
task.Start(scheduler);

If you started the task from other thread and need to wait for its completition task.Wait() will block calling thread till the end of the task.

Read more about tasks here.

Curl error 60, SSL certificate issue: self signed certificate in certificate chain

Answers suggesting to disable CURLOPT_SSL_VERIFYPEER should not be accepted. The question is "Why doesn't it work with cURL", and as correctly pointed out by Martijn Hols, it is dangerous.

The error is probably caused by not having an up-to-date bundle of CA root certificates. This is typically a text file with a bunch of cryptographic signatures that curl uses to verify a host’s SSL certificate.

You need to make sure that your installation of PHP has one of these files, and that it’s up to date (otherwise download one here: http://curl.haxx.se/docs/caextract.html).

Then set in php.ini:

curl.cainfo = <absolute_path_to> cacert.pem

If you are setting it at runtime, use:

curl_setopt ($ch, CURLOPT_CAINFO, dirname(__FILE__)."/cacert.pem");

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

I had same problem, but it worked for me.

  1. check if you have mysql installed

    enter image description here

If you don't have mysql installed, download from this link: https://dev.mysql.com/downloads/mysql/

  1. follow this instructions to install https://dev.mysql.com/doc/mysql-osx-excerpt/5.7/en/osx-installation-pkg.html

  2. You can test the connection without any problem.

(Sorry for my english, I agree fix me please)

I Hope I've helped. Greetings.

How can I reverse a NSArray in Objective-C?

Try this:

for (int i = 0; i < [arr count]; i++)
{
    NSString *str1 = [arr objectAtIndex:[arr count]-1];
    [arr insertObject:str1 atIndex:i];
    [arr removeObjectAtIndex:[arr count]-1];
}

Adding backslashes without escaping [Python]

There is no extra backslash, it's just formatted that way in the interactive environment. Try:

print string

Then you can see that there really is no extra backslash.

How to bind Dataset to DataGridView in windows application

you can set the dataset to grid as follows:

//assuming your dataset object is ds

datagridview1.datasource= ds;
datagridview1.datamember= tablename.ToString();

tablename is the name of the table, which you want to show on the grid.

I hope, it helps.

B.R.

What happens to C# Dictionary<int, int> lookup if the key does not exist?

Consider the option of encapsulating this particular dictionary and provide a method to return the value for that key:

public static class NumbersAdapter
{
    private static readonly Dictionary<string, string> Mapping = new Dictionary<string, string>
    {
        ["1"] = "One",
        ["2"] = "Two",
        ["3"] = "Three"
    };

    public static string GetValue(string key)
    {
        return Mapping.ContainsKey(key) ? Mapping[key] : key;
    }
}

Then you can manage the behaviour of this dictionary.

For example here: if the dictionary doesn't have the key, it returns key that you pass by parameter.

How to create a table from select query result in SQL Server 2008

Please try:

SELECT * INTO NewTable FROM OldTable

How to build a 2 Column (Fixed - Fluid) Layout with Twitter Bootstrap?

Update 2018

Bootstrap 4

Now that BS4 is flexbox, the fixed-fluid is simple. Just set the width of the fixed column, and use the .col class on the fluid column.

.sidebar {
    width: 180px;
    min-height: 100vh;
}

<div class="row">
    <div class="sidebar p-2">Fixed width</div>
    <div class="col bg-dark text-white pt-2">
        Content
    </div>
</div>

http://www.codeply.com/go/7LzXiPxo6a

Bootstrap 3..

One approach to a fixed-fluid layout is using media queries that align with Bootstrap's breakpoints so that you only use the fixed width columns are larger screens and then let the layout stack responsively on smaller screens...

@media (min-width:768px) {
  #sidebar {
      min-width: 300px;
      max-width: 300px;
  }
  #main {
      width:calc(100% - 300px);
  }
}

Working Bootstrap 3 Fixed-Fluid Demo

Related Q&A:
Fixed width column with a container-fluid in bootstrap
How to left column fixed and right scrollable in Bootstrap 4, responsive?

align an image and some text on the same line without using div width?

Just set the img css to be display:inline or display:inline-block

Can you do greater than comparison on a date in a Rails 3 search?

Rails 6.1 added a new 'syntax' for comparison operators in where conditions, for example:

Post.where('id >': 9)
Post.where('id >=': 9)
Post.where('id <': 3)
Post.where('id <=': 3)

So your query can be rewritten as follows:

Note
  .where(user_id: current_user.id, notetype: p[:note_type], 'date >', p[:date])
  .order(date: :asc, created_at: :asc)

Here is a link to PR where you can find more examples.

Add a column to a table, if it does not already exist

IF NOT EXISTS (SELECT 1  FROM SYS.COLUMNS WHERE  
OBJECT_ID = OBJECT_ID(N'[dbo].[Person]') AND name = 'DateOfBirth')
BEGIN
ALTER TABLE [dbo].[Person] ADD DateOfBirth DATETIME
END

jquery append external html file into my page

<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.6.4.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(function () {
                $.get("banner.html", function (data) {
                    $("#appendToThis").append(data);
                });
            });
        </script>
    </head>
    <body>
        <div id="appendToThis"></div>
    </body>
</html>

Animated GIF in IE stopping

The accepted solution did not work for me.

After some more research I came across this workaround, and it actually does work.

Here is the gist of it:

function showProgress() {
    var pb = document.getElementById("progressBar");
    pb.innerHTML = '<img src="./progress-bar.gif" width="200" height ="40"/>';
    pb.style.display = '';
}

and in your html:

<input type="submit" value="Submit" onclick="showProgress()" />
<div id="progressBar" style="display: none;">
    <img src="./progress-bar.gif" width="200" height ="40"/>
</div>

So when the form is submitted, the <img/> tag is inserted, and for some reason it is not affected by the ie animation issues.

Tested in Firefox, ie6, ie7 and ie8.

Android Studio - local path doesn't exist

delete de out directory and .ide folder work for me

How to check a channel is closed or not without reading it?

There's no way to write a safe application where you need to know whether a channel is open without interacting with it.

The best way to do what you're wanting to do is with two channels -- one for the work and one to indicate a desire to change state (as well as the completion of that state change if that's important).

Channels are cheap. Complex design overloading semantics isn't.

[also]

<-time.After(1e9)

is a really confusing and non-obvious way to write

time.Sleep(time.Second)

Keep things simple and everyone (including you) can understand them.

How do I change the font size and color in an Excel Drop Down List?

I created a custom view that is at 100%. Use the dropdowns then click to view page layout to go back to a smaller view.

How to call a MySQL stored procedure from within PHP code?

This is my solution with prepared statements and stored procedure is returning several rows not only one value.

<?php

require 'config.php';
header('Content-type:application/json');
$connection->set_charset('utf8');

$mIds = $_GET['ids'];

$stmt = $connection->prepare("CALL sp_takes_string_returns_table(?)");
$stmt->bind_param("s", $mIds);

$stmt->execute();

$result = $stmt->get_result();
$response = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($response);

$stmt->close();
$connection->close();

How do I get list of all tables in a database using TSQL?

SELECT sobjects.name
FROM sysobjects sobjects
WHERE sobjects.xtype = 'U' 

How to redirect to another page using PHP

The simplest approach is that your script validates the form-posted login data "on top" of the script before any output.

If the login is valid you'll redirect using the "header" function.

Even if you use "ob_start()" it sometimes happens that you miss a single whitespace which results in output. But you will see a statement in your error logs then.

<?php
ob_start();
if (FORMPOST) {
    if (POSTED_DATA_VALID) {
        header("Location: https://www.yoursite.com/profile/");
        ob_end_flush();
        exit;
    }
}
/** YOUR LOGINBOX OUTPUT, ERROR MESSAGES ... **/
ob_end_flush();
?>

How to increase time in web.config for executing sql query

You should add the httpRuntime block and deal with executionTimeout (in seconds).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
 <system.web>
   <httpRuntime executionTimeout="90" maxRequestLength="4096"
    useFullyQualifiedRedirectUrl="false"
    minFreeThreads="8"
    minLocalRequestFreeThreads="4"
    appRequestQueueLimit="100" />
 </system.web>
... 
</configuration>

For more information, please, see msdn page.

Why would one use nested classes in C++?

I don't use nested classes much, but I do use them now and then. Especially when I define some kind of data type, and I then want to define a STL functor designed for that data type.

For example, consider a generic Field class that has an ID number, a type code and a field name. If I want to search a vector of these Fields by either ID number or name, I might construct a functor to do so:

class Field
{
public:
  unsigned id_;
  string name_;
  unsigned type_;

  class match : public std::unary_function<bool, Field>
  {
  public:
    match(const string& name) : name_(name), has_name_(true) {};
    match(unsigned id) : id_(id), has_id_(true) {};
    bool operator()(const Field& rhs) const
    {
      bool ret = true;
      if( ret && has_id_ ) ret = id_ == rhs.id_;
      if( ret && has_name_ ) ret = name_ == rhs.name_;
      return ret;
    };
    private:
      unsigned id_;
      bool has_id_;
      string name_;
      bool has_name_;
  };
};

Then code that needs to search for these Fields can use the match scoped within the Field class itself:

vector<Field>::const_iterator it = find_if(fields.begin(), fields.end(), Field::match("FieldName"));

Laravel Eloquent: Ordering results of all()

DO THIS:

$results = Project::orderBy('name')->get();

Why? Because it's fast! The ordering is done in the database.

DON'T DO THIS:

$results = Project::all()->sortBy('name');

Why? Because it's slow. First, the the rows are loaded from the database, then loaded into Laravel's Collection class, and finally, ordered in memory.

Find Active Tab using jQuery and Twitter Bootstrap

First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.

  <ul class='nav nav-tabs'>
    <li class='active'><a href='#home'>Home</a></li>
    <li><a href='#menu1'>Menu 1</a></li>
    <li><a href='#menu2'>Menu 2</a></li>
    <li><a href='#menu3'>Menu 3</a></li>
  </ul>

  <div class='tab-content'>
    <div id='home' class='tab-pane fade in active'>
      <h3>HOME</h3>
    <div id='menu1' class='tab-pane fade'>
      <h3>Menu 1</h3>
    </div>
    <div id='menu2' class='tab-pane fade'>
      <h3>Menu 2</h3>
    </div>
    <div id='menu3' class='tab-pane fade'>
      <h3>Menu 3</h3>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
// Handling data-toggle manually
    $('.nav-tabs a').click(function(){
        $(this).tab('show');
    });
// The on tab shown event
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
        alert('Hello from the other siiiiiide!');
        var current_tab = e.target;
        var previous_tab = e.relatedTarget;
    });
});
</script>

How to avoid pressing Enter with getchar() for reading a single character only?

getchar() is a standard function that on many platforms requires you to press ENTER to get the input, because the platform buffers input until that key is pressed. Many compilers/platforms support the non-standard getch() that does not care about ENTER (bypasses platform buffering, treats ENTER like just another key).

Online code beautifier and formatter

For PHP, Java, C++, C, Perl, JavaScript, CSS you can try:

http://www.prettyprinter.de/index.php

Sizing elements to percentage of screen width/height

There is many way to do this.

1. Using MediaQuery : Its return fullscreen of your device including appbar,toolbar

 Container(
        width: MediaQuery.of(context).size.width * 0.50,
        height: MediaQuery.of(context).size.height*0.50, 
        color: Colors.blueAccent[400],
 )

enter image description here


2. Using Expanded : You can set width/height in ratio

 Container(
        height: MediaQuery.of(context).size.height * 0.50,
        child: Row(
          children: <Widget>[
            Expanded(
              flex: 70,
              child: Container(
                color: Colors.lightBlue[400],
              ),
            ),
            Expanded(
              flex: 30,
              child: Container(
                color: Colors.deepPurple[800],
              ),
            )
          ],
        ),
    )

enter image description here



3. Others Like Flexible and AspectRatio and FractionallySizedBox

How to filter keys of an object with lodash?

A non-lodash way to solve this in a fairly readable and efficient manner:

_x000D_
_x000D_
function filterByKeys(obj, keys = []) {_x000D_
  const filtered = {}_x000D_
  keys.forEach(key => {_x000D_
    if (obj.hasOwnProperty(key)) {_x000D_
      filtered[key] = obj[key]_x000D_
    }_x000D_
  })_x000D_
  return filtered_x000D_
}_x000D_
_x000D_
const myObject = {_x000D_
  a: 1,_x000D_
  b: 'bananas',_x000D_
  d: null_x000D_
}_x000D_
_x000D_
const result = filterByKeys(myObject, ['a', 'd', 'e']) // {a: 1, d: null}_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

How do I create an .exe for a Java program?

You could try exe4j. This is effectively what we use through its cousin install4j.

What is HTML5 ARIA?

What is ARIA?

ARIA emerged as a way to address the accessibility problem of using a markup language intended for documents, HTML, to build user interfaces (UI). HTML includes a great many features to deal with documents (P, h3,UL,TABLE) but only basic UI elements such as A, INPUT and BUTTON. Windows and other operating systems support APIs that allow (Assistive Technology) AT to access the functionality of UI controls. Internet Explorer and other browsers map the native HTML elements to the accessibility API, but the html controls are not as rich as the controls common on desktop operating systems, and are not enough for modern web applications Custom controls can extend html elements to provide the rich UI needed for modern web applications. Before ARIA, the browser had no way to expose this extra richness to the accessibility API or AT. The classic example of this issue is adding a click handler to an image. It creates what appears to be a clickable button to a mouse user, but is still just an image to a keyboard or AT user.

The solution was to create a set of attributes that allow developers to extend HTML with UI semantics. The ARIA term for a group of HTML elements that have custom functionality and use ARIA attributes to map these functions to accessibility APIs is a “Widget. ARIA also provides a means for authors to document the role of content itself, which in turn, allows AT to construct alternate navigation mechanisms for the content that are much easier to use than reading the full text or only iterating over a list of the links.

It is important to remember that in simple cases, it is much preferred to use native HTML controls and style them rather than using ARIA. That is don’t reinvent wheels, or checkboxes, if you don’t have to.

Fortunately, ARIA markup can be added to existing sites without changing the behavior for mainstream users. This greatly reduces the cost of modifying and testing the website or application.

Using grep and sed to find and replace a string

You can use find and -exec directly into sed rather than first locating oldstr with grep. It's maybe a bit less efficient, but that might not be important. This way, the sed replacement is executed over all files listed by find, but if oldstr isn't there it obviously won't operate on it.

find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \;

addClass - can add multiple classes on same div?

You can do

$('.page-address-edit').addClass('test1 test2');

More here:

More than one class may be added at a time, separated by a space, to the set of matched elements, like so:

$("p").addClass("myClass yourClass");

Is it possible to remove inline styles with jQuery?

The Lazy way (which will cause future designers to curse your name and murder you in your sleep):

#myelement 
{
    display: none !important;
}

Disclaimer: I do not advocate this approach, but it certainly is the lazy way.

How to cast Object to its actual type?

Cast it to its real type if you now the type for example it is oriented from class named abc. You can call your function in this way :

(abc)(obj)).MyFunction();

if you don't know the function it can be done in a different way. Not easy always. But you can find it in some way by it's signature. If this is your case, you should let us know.

Auto-fit TextView for Android

If you are looking for something easier:

 public MyTextView extends TextView{

    public void resize(String text, float textViewWidth, float textViewHeight) {
       Paint p = new Paint();
       Rect bounds = new Rect();
       p.setTextSize(1);
       p.getTextBounds(text, 0, text.length(), bounds);
       float widthDifference = (textViewWidth)/bounds.width();
       float heightDifference = (textViewHeight);
       textSize = Math.min(widthDifference, heightDifference);
       setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
}

Convert a string to an enum in C#

If the property name is different from what you want to call it (i.e. language differences) you can do like this:

MyType.cs

using System;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

[JsonConverter(typeof(StringEnumConverter))]
public enum MyType
{
    [EnumMember(Value = "person")]
    Person,
    [EnumMember(Value = "annan_deltagare")]
    OtherPerson,
    [EnumMember(Value = "regel")]
    Rule,
}

EnumExtensions.cs

using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

public static class EnumExtensions
{
    public static TEnum ToEnum<TEnum>(this string value) where TEnum : Enum
    {
        var jsonString = $"'{value.ToLower()}'";
        return JsonConvert.DeserializeObject<TEnum>(jsonString, new StringEnumConverter());
    }

    public static bool EqualsTo<TEnum>(this string strA, TEnum enumB) where TEnum : Enum
    {
        TEnum enumA;
        try
        {
            enumA = strA.ToEnum<TEnum>();
        }
        catch
        {
            return false;
        }
        return enumA.Equals(enumB);
    }
}

Program.cs

public class Program
{
    static public void Main(String[] args) 
    { 
        var myString = "annan_deltagare";
        var myType = myString.ToEnum<MyType>();
        var isEqual = myString.EqualsTo(MyType.OtherPerson);
        //Output: true
    }     
}

Using Chrome, how to find to which events are bound to an element

(Latest as of 2020) For version Chrome Version 83.0.4103.61 :

Chrome Developer Tools - Event Listener

  1. Select the element you want to inspect

  2. Choose the Event Listeners tab

  3. Make sure to check the Framework listeners to show the real javascript file instead of the jquery function.

How to limit google autocomplete results to City and Country only

<html>
  <head>
    <title>Example Using Google Complete API</title>   
  </head>
  <body>

<form>
   <input id="geocomplete" type="text" placeholder="Type an address/location"/>
    </form>
   <script src="http://maps.googleapis.com/maps/api/js?sensor=false&amp;libraries=places"></script>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

  <script src="http://ubilabs.github.io/geocomplete/jquery.geocomplete.js"></script>
  <script>
   $(function(){        
    $("#geocomplete").geocomplete();                           
   });
  </script>
 </body>
</html>

For more information visit this link

How do you extract a column from a multi-dimensional array?

One more way using matrices

>>> from numpy import matrix
>>> a = [ [1,2,3],[4,5,6],[7,8,9] ]
>>> matrix(a).transpose()[1].getA()[0]
array([2, 5, 8])
>>> matrix(a).transpose()[0].getA()[0]
array([1, 4, 7])

Swift 2: Call can throw, but it is not marked with 'try' and the error is not handled

When calling a function that is declared with throws in Swift, you must annotate the function call site with try or try!. For example, given a throwing function:

func willOnlyThrowIfTrue(value: Bool) throws {
  if value { throw someError }
}

this function can be called like:

func foo(value: Bool) throws {
  try willOnlyThrowIfTrue(value)
}

Here we annotate the call with try, which calls out to the reader that this function may throw an exception, and any following lines of code might not be executed. We also have to annotate this function with throws, because this function could throw an exception (i.e., when willOnlyThrowIfTrue() throws, then foo will automatically rethrow the exception upwards.

If you want to call a function that is declared as possibly throwing, but which you know will not throw in your case because you're giving it correct input, you can use try!.

func bar() {
  try! willOnlyThrowIfTrue(false)
}

This way, when you guarantee that code won't throw, you don't have to put in extra boilerplate code to disable exception propagation.

try! is enforced at runtime: if you use try! and the function does end up throwing, then your program's execution will be terminated with a runtime error.

Most exception handling code should look like the above: either you simply propagate exceptions upward when they occur, or you set up conditions such that otherwise possible exceptions are ruled out. Any clean up of other resources in your code should occur via object destruction (i.e. deinit()), or sometimes via defered code.

func baz(value: Bool) throws {

  var filePath = NSBundle.mainBundle().pathForResource("theFile", ofType:"txt")
  var data = NSData(contentsOfFile:filePath)

  try willOnlyThrowIfTrue(value)

  // data and filePath automatically cleaned up, even when an exception occurs.
}

If for whatever reason you have clean up code that needs to run but isn't in a deinit() function, you can use defer.

func qux(value: Bool) throws {
  defer {
    print("this code runs when the function exits, even when it exits by an exception")
  }

  try willOnlyThrowIfTrue(value)
}

Most code that deals with exceptions simply has them propagate upward to callers, doing cleanup on the way via deinit() or defer. This is because most code doesn't know what to do with errors; it knows what went wrong, but it doesn't have enough information about what some higher level code is trying to do in order to know what to do about the error. It doesn't know if presenting a dialog to the user is appropriate, or if it should retry, or if something else is appropriate.

Higher level code, however, should know exactly what to do in the event of any error. So exceptions allow specific errors to bubble up from where they initially occur to the where they can be handled.

Handling exceptions is done via catch statements.

func quux(value: Bool) {
  do {
    try willOnlyThrowIfTrue(value)
  } catch {
    // handle error
  }
}

You can have multiple catch statements, each catching a different kind of exception.

  do {
    try someFunctionThatThowsDifferentExceptions()
  } catch MyErrorType.errorA {
    // handle errorA
  } catch MyErrorType.errorB {
    // handle errorB
  } catch {
    // handle other errors
  }

For more details on best practices with exceptions, see http://exceptionsafecode.com/. It's specifically aimed at C++, but after examining the Swift exception model, I believe the basics apply to Swift as well.

For details on the Swift syntax and error handling model, see the book The Swift Programming Language (Swift 2 Prerelease).

Change the background color of a pop-up dialog

You can use a custom style:

  <!-- Alert Dialog -->
  <style name="ThemeOverlay.MaterialComponents.MaterialAlertDialog_Background" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
    <!-- Background Color-->
    <item name="android:background">@color/.....</item>
    <!-- Text Color for title and message -->
    <item name="colorOnSurface">@color/......</item>
    <!-- Style for positive button -->
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    <!-- Style for negative button -->
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
  </style>

  <style name="PositiveButtonStyle" parent="@style/Widget.MaterialComponents.Button">
    <!-- text color for the button -->
    <item name="android:textColor">@color/.....</item>
    <!-- Background tint for the button -->
    <item name="backgroundTint">@color/primaryDarkColor</item>
  </style>

And just use the default MaterialAlertDialogBuilder:

    new MaterialAlertDialogBuilder(AlertDialogActivity.this,
        R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog_Background)
        .setTitle("Dialog")
        .setMessage("Message...  ....")
        .setPositiveButton("Ok", /* listener = */ null)
        .show();

enter image description here

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

1:Go to: Tools > Options > Projects and Solutions > Web Projects > Use the 64 bit version of IIS Express 2: change below setting for web service project. enter image description here

Relative paths based on file location instead of current working directory

Just one line will be OK.

cat "`dirname $0`"/../some.txt

What is difference between cacerts and keystore?

'cacerts' is a truststore. A trust store is used to authenticate peers. A keystore is used to authenticate yourself.

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

How I can get web page's content and save it into the string variable

I've run into issues with Webclient.Downloadstring before. If you do, you can try this:

WebRequest request = WebRequest.Create("http://www.google.com");
WebResponse response = request.GetResponse();
Stream data = response.GetResponseStream();
string html = String.Empty;
using (StreamReader sr = new StreamReader(data))
{
    html = sr.ReadToEnd();
}

SQL Server Convert Varchar to Datetime

You can have all the different styles to datetime conversion :

https://www.w3schools.com/sql/func_sqlserver_convert.asp

This has range of values :-

CONVERT(data_type(length),expression,style)

For style values,
Choose anyone you need like I needed 106.

How to get the new value of an HTML input after a keypress has modified it?

<html>
    <head>
        <script>
        function callme(field) {
            alert("field:" + field.value);
        }
        </script>
    </head>
    <body>
        <form name="f1">
            <input type="text" onkeyup="callme(this);" name="text1">
        </form>
    </body>
</html>

It looks like you can use the onkeyup to get the new value of the HTML input control. Hope it helps.

Use jQuery to get the file input's selected filename without the path

maybe some addition for avoid fakepath:

var fileName = $('input[type=file]').val();
var clean=fileName.split('\\').pop(); // clean from C:\fakepath OR C:\fake_path 
alert('clean file name : '+ fileName);

Resize image proportionally with CSS?

Try

transform: scale(0.5, 0.5);
-ms-transform: scale(0.5, 0.5);
-webkit-transform: scale(0.5, 0.5);

ConcurrentModificationException for ArrayList

You can't remove from list if you're browsing it with "for each" loop. You can use Iterator. Replace:

for (DrugStrength aDrugStrength : aDrugStrengthList) {
    if (!aDrugStrength.isValidDrugDescription()) {
        aDrugStrengthList.remove(aDrugStrength);
    }
}

With:

for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) {
    DrugStrength aDrugStrength = it.next();
    if (!aDrugStrength.isValidDrugDescription()) {
        it.remove();
    }
}

How to reset the state of a Redux store?

Simply have your logout link clear session and refresh the page. No additional code needed for your store. Any time you want to completely reset the state a page refresh is a simple and easily repeatable way to handle it.

How do I share variables between different .c files?

The 2nd file needs to know about the existance of your variable. To do this you declare the variable again but use the keyword extern in front of it. This tells the compiler that the variable is available but declared somewhere else, thus prevent instanciating it (again, which would cause clashes when linking). While you can put the extern declaration in the C file itself it's common style to have an accompanying header (i.e. .h) file for each .c file that provides functions or variables to others which hold the extern declaration. This way you avoid copying the extern declaration, especially if it's used in multiple other files. The same applies for functions, though you don't need the keyword extern for them.

That way you would have at least three files: the source file that declares the variable, it's acompanying header that does the extern declaration and the second source file that #includes the header to gain access to the exported variable (or any other symbol exported in the header). Of course you need all source files (or the appropriate object files) when trying to link something like that, as the linker needs to resolve the symbol which is only possible if it actually exists in the files linked.

How to create a fixed sidebar layout with Bootstrap 4?

My version:

div#dashmain { margin-left:150px; }
div#dashside {position:fixed; width:150px; height:100%; }
<div id="dashside"></div>
<div id="dashmain">                        
    <div class="container-fluid">
        <div class="row">
            <div class="col-md-12">Content</div>
        </div>            
    </div>        
</div>

Ajax call Into MVC Controller- Url Issue

In order for this to work that Javascript must be placed within a Razor view so that the line

@Url.Action("Action","Controller")

is parsed by Razor and the real value replaced.

If you don't want to move your Javascript into your View you could look at creating a settings object in the view and then referencing that from your Javascript file.

e.g.

var MyAppUrlSettings = {
    MyUsefulUrl : '@Url.Action("Action","Controller")'
}

and in your .js file

$.ajax({
 type: "POST",
 url: MyAppUrlSettings.MyUsefulUrl,
 data: "{queryString:'" + searchVal + "'}",
 contentType: "application/json; charset=utf-8",
 dataType: "html",
 success: function (data) {
 alert("here" + data.d.toString());
});

or alternatively look at levering the framework's built in Ajax methods within the HtmlHelpers which allow you to achieve the same without "polluting" your Views with JS code.

How do you do natural logs (e.g. "ln()") with numpy in Python?

from numpy.lib.scimath import logn
from math import e

#using: x - var
logn(e, x)

Java regular expression OR operator

You can just use the pipe on its own:

"string1|string2"

for example:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|string2", "blah"));

Output:

blah, blah, string3

The main reason to use parentheses is to limit the scope of the alternatives:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(1|2)", "blah"));

has the same output. but if you just do this:

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string1|2", "blah"));

you get:

blah, stringblah, string3

because you've said "string1" or "2".

If you don't want to capture that part of the expression use ?::

String s = "string1, string2, string3";
System.out.println(s.replaceAll("string(?:1|2)", "blah"));

pip cannot install anything

I had that problem too, after I tried to reset my network settings. it solves problem.

Logging best practices

We use Log4Net at work as the logging provider, with a singleton wrapper for the log instance (although the singleton is under review, questioning whether they are a good idea or not).

We chose it for the following reasons:

  • Simple configuration/ reconfiguration on various environments
  • Good number of pre-built appenders
  • One of the CMS's we use already had it built in
  • Nice number of log levels and configurations around them

I should mention, this is speaking from an ASP.NET development point of view

I can see some merits in using the Trace that is in the .NET framework but I'm not entirely sold on it, mainly because the components I work with don't really do any Trace calls. The only thing that I frequently use that does is System.Net.Mail from what I can tell.

So we have a library which wraps log4net and within our code we just need stuff like this:

Logger.Instance.Warn("Something to warn about");
Logger.Instance.Fatal("Something went bad!", new Exception());

try {
  var i = int.Parse("Hello World");
} catch(FormatException, ex) {
  Logger.Instance.Error(ex);
}

Within the methods we do a check to see if the logging level is enabled, so you don't have redundant calls to the log4net API (so if Debug isn't enabled, the debug statements are ignored), but when I get some time I'll be updating it to expose those so that you can do the checks yourself. This will prevent evaluations being undertaken when they shouldn't, eg:

Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);

This will become:

if(Logger.DebugEnabled) Logger.Instance.Debug(string.Format("Something to debug at {0}", DateTime.Now);

(Save a bit of execusion time)

By default we log at two locations:

  1. File system of the website (in a non-served file extension)
  2. Email sending for Error & Fatal

Files are done as rolling of each day or 10mb (IIRC). We don't use the EventLog as it can require higher security than we often want to give a site.

I find Notepad works just fine for reading logs.

Electron: jQuery is not defined

I face the same issue and this worked for me!

Install jQuery using npm

$ npm install jquery

Then include jQuery in one of the following ways.

Using script tag

<script>window.$ = window.jQuery = require('jquery');</script>

Using Babel

import $ from 'jquery';

Using Webpack

const $ = require('jquery');

Sum values from multiple rows using vlookup or index/match functions

You should use Ctrl+shift+enter when using the =SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE)) that results in {=SUM(VLOOKUP(A9,A1:D5,{2,3,4,},FALSE))} en also works.

Java - Relative path of a file in a java web application

You may be able to simply access a pre-arranged file path on the system. This is preferable since files added to the webapp directory might be lost or the webapp may not be unpacked depending on system configuration.

In our server, we define a system property set in the App Server's JVM which points to the "home directory" for our app's external data. Of course this requires modification of the App Server's configuration (-DAPP_HOME=... added to JVM_OPTS at startup), we do it mainly to ease testing of code run outside the context of an App Server.

You could just as easily retrieve a path from the servlet config:

<web-app>
<context-param>
    <param-name>MyAppHome</param-name>
    <param-value>/usr/share/myapp</param-value>
</context-param>
...
</web-app>

Then retrieve this path and use it as the base path to read the file supplied by the client.

public class MyAppConfig implements ServletContextListener {

    // NOTE: static references are not a great idea, shown here for simplicity
    static File appHome;
    static File customerDataFile;

    public void contextInitialized(ServletContextEvent e) {

        appHome = new File(e.getServletContext().getInitParameter("MyAppHome"));
        File customerDataFile = new File(appHome, "SuppliedFile.csv");
    }
}

class DataProcessor {
    public void processData() {
        File dataFile = MyAppConfig.customerDataFile;
        // ...
    }
}

As I mentioned the most likely problem you'll encounter is security restrictions. Nothing guarantees webapps can ready any files above their webapp root. But there are generally simple methods for granting exceptions for specific paths to specific webapps.

Regardless of the code in which you then need to access this file, since you are running within a web application you are guaranteed this is initialized first, and can stash it's value somewhere convenient for the rest of your code to refer to, as in my example or better yet, just simply pass the path as a paramete to the code which needs it.

Format date in a specific timezone

You can Try this ,

Here you can get the date based on the Client Timezone (Browser).

moment(new Date().getTime()).zone(new Date().toString().match(/([-\+][0-9]+)\s/)[1]).format('YYYY-MM-DD HH:mm:ss')

The regex basically gets you the offset value.

Cheers!!

What does the construct x = x || y mean?

To add some explanation to all said before me, I should give you some examples to understand logical concepts.

var name = false || "Mohsen"; # name equals to Mohsen
var family = true || "Alizadeh" # family equals to true

It means if the left side evaluated as a true statement it will be finished and the left side will be returned and assigned to the variable. in other cases the right side will be returned and assigned.

And operator have the opposite structure like below.

var name = false && "Mohsen" # name equals to false
var family = true && "Alizadeh" # family equals to Alizadeh

Why does z-index not work?

If you set position to other value than static but your element's z-index still doesn't seem to work, it may be that some parent element has z-index set.

The stacking contexts have hierarchy, and each stacking context is considered in the stacking order of the parent's stacking context.

So with following html

_x000D_
_x000D_
div { border: 2px solid #000; width: 100px; height: 30px; margin: 10px; position: relative; background-color: #FFF; }_x000D_
#el3 { background-color: #F0F; width: 100px; height: 60px; top: -50px; }
_x000D_
<div id="el1" style="z-index: 5"></div>_x000D_
<div id="el2" style="z-index: 3">_x000D_
  <div id="el3" style="z-index: 8"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

no matter how big the z-index of el3 will be set, it will always be under el1 because it's parent has lower stacking context. You can imagine stacking order as levels where stacking order of el3 is actually 3.8 which is lower than 5.

If you want to check stacking contexts of parent elements, you can use this:

var el = document.getElementById("#yourElement"); // or use $0 in chrome;
do {
    var styles = window.getComputedStyle(el);
    console.log(styles.zIndex, el);
} while(el.parentElement && (el = el.parentElement));

There is a great article about stacking contexts on MDN

How do I increase the cell width of the Jupyter/ipython notebook in my browser?

You can set the CSS of a notebook by calling a stylesheet from any cell. As an example, take a look at the 12 Steps to Navier Stokes course.

In particular, creating a file containing

<style>
    div.cell{
        width:100%;
        margin-left:1%;
        margin-right:auto;
    }
</style>

should give you a starting point. However, it may be necessary to also adjust e.g div.text_cell_render to deal with markdown as well as code cells.

If that file is custom.css then add a cell containing:

from IPython.core.display import HTML
def css_styling():
    styles = open("custom.css", "r").read()
    return HTML(styles)
css_styling()

This will apply all the stylings, and, in particular, change the cell width.

Matching strings with wildcard

*X*YZ* = string contains X and contains YZ

@".*X.*YZ"

X*YZ*P = string starts with X, contains YZ and ends with P.

@"^X.*YZ.*P$"

Save PHP array to MySQL?

I would suggest using implode/explode with a character that you know will not be contained in any of the individual array items. Then store it in SQL as a string.

How to compare oldValues and newValues on React Hooks useEffect?

Option 1 - run useEffect when value changes

const Component = (props) => {

  useEffect(() => {
    console.log("val1 has changed");
  }, [val1]);

  return <div>...</div>;
};

Demo

Option 2 - useHasChanged hook

Comparing a current value to a previous value is a common pattern, and justifies a custom hook of it's own that hides implementation details.

const Component = (props) => {
  const hasVal1Changed = useHasChanged(val1)

  useEffect(() => {
    if (hasVal1Changed ) {
      console.log("val1 has changed");
    }
  });

  return <div>...</div>;
};

const useHasChanged= (val: any) => {
    const prevVal = usePrevious(val)
    return prevVal !== val
}

const usePrevious = (value) => {
    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });
    return ref.current;
}


Demo

Why do we have to specify FromBody and FromUri?

Just addition to above answers ..

[FromUri] can also be used to bind complex types from uri parameters instead of passing parameters from querystring

For Ex..

public class GeoPoint
{
    public double Latitude { get; set; } 
    public double Longitude { get; set; }
}

[RoutePrefix("api/Values")]
public ValuesController : ApiController
{
    [Route("{Latitude}/{Longitude}")]
    public HttpResponseMessage Get([FromUri] GeoPoint location) { ... }
}

Can be called like:

http://localhost/api/values/47.678558/-122.130989