Programs & Examples On #Custom eventlog

How do I pass the this context to a function?

Use function.call:

var f = function () { console.log(this); }
f.call(that, arg1, arg2, etc);

Where that is the object which you want this in the function to be.

Name does not exist in the current context

In our case, beside changing ToolsVersion from 14.0 to 15.0 on .csproj projet file, as stated by Dominik Litschauer, we also had to install an updated version of MSBuild, since compilation is being triggered by a Jenkins job. After installing Build Tools for Visual Studio 2019, we had got MsBuild version 16.0 and all new C# features compiled ok.

Maven with Eclipse Juno

You should be able to install m2e (maven project for eclipse) using the Help -> Install New Software dialog. On that dialog open the Juno site (http://download.eclipse.org/releases/juno) and expand the Collaboration group (or type m2e into the filter). Select the two m2e options and follow the installation dialog

How to select the last column of dataframe

Use iloc and select all rows (:) against the last column (-1):

df.iloc[:,-1:]

URL for public Amazon S3 bucket

The URL structure you're referring to is called the REST endpoint, as opposed to the Web Site Endpoint.


Note: Since this answer was originally written, S3 has rolled out dualstack support on REST endpoints, using new hostnames, while leaving the existing hostnames in place. This is now integrated into the information provided, below.


If your bucket is really in the us-east-1 region of AWS -- which the S3 documentation formerly referred to as the "US Standard" region, but was subsequently officially renamed to the "U.S. East (N. Virginia) Region" -- then http://s3-us-east-1.amazonaws.com/bucket/ is not the correct form for that endpoint, even though it looks like it should be. The correct format for that region is either http://s3.amazonaws.com/bucket/ or http://s3-external-1.amazonaws.com/bucket/

The format you're using is applicable to all the other S3 regions, but not US Standard US East (N. Virginia) [us-east-1].

S3 now also has dual-stack endpoint hostnames for the REST endpoints, and unlike the original endpoint hostnames, the names of these have a consistent format across regions, for example s3.dualstack.us-east-1.amazonaws.com. These endpoints support both IPv4 and IPv6 connectivity and DNS resolution, but are otherwise functionally equivalent to the existing REST endpoints.

If your permissions and configuration are set up such that the web site endpoint works, then the REST endpoint should work, too.

However... the two endpoints do not offer the same functionality.

Roughly speaking, the REST endpoint is better-suited for machine access and the web site endpoint is better suited for human access, since the web site endpoint offers friendly error messages, index documents, and redirects, while the REST endpoint doesn't. On the other hand, the REST endpoint offers HTTPS and support for signed URLs, while the web site endpoint doesn't.

Choose the correct type of endpoint (REST or web site) for your application:

http://docs.aws.amazon.com/AmazonS3/latest/dev/WebsiteEndpoints.html#WebsiteRestEndpointDiff


¹ s3-external-1.amazonaws.com has been referred to as the "Northern Virginia endpoint," in contrast to the "Global endpoint" s3.amazonaws.com. It was unofficially possible to get read-after-write consistency on new objects in this region if the "s3-external-1" hostname was used, because this would send you to a subset of possible physical endpoints that could provide that functionality. This behavior is now officially supported on this endpoint, so this is probably the better choice in many applications. Previously, s3-external-2 had been referred to as the "Pacific Northwest endpoint" for US-Standard, though it is now a CNAME in DNS for s3-external-1 so s3-external-2 appears to have no purpose except backwards-compatibility.

How do I create JavaScript array (JSON format) dynamically?

Our array of objects

var someData = [
   {firstName: "Max", lastName: "Mustermann", age: 40},
   {firstName: "Hagbard", lastName: "Celine", age: 44},
   {firstName: "Karl", lastName: "Koch", age: 42},
];

with for...in

var employees = {
    accounting: []
};

for(var i in someData) {    

    var item = someData[i];   

    employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

or with Array.prototype.map(), which is much cleaner:

var employees = {
    accounting: []
};

someData.map(function(item) {        
   employees.accounting.push({ 
        "firstName" : item.firstName,
        "lastName"  : item.lastName,
        "age"       : item.age 
    });
}

Nodejs cannot find installed module on Windows

For Windows 10, I had to locally install gulp in the folder:

C:\Users\myaccount\AppData\Roaming\npm\node_modules

npm install gulp

This fixed my issue of "gulp is not recognized"

Syncing Android Studio project with Gradle files

I've had this problem after installing the genymotion (another android amulator) plugin. A closer inspection reveled that gradle needs SDK tools version 19.1.0 in order to run (I had 19.0.3 previously).

To fix it, I had to edit build.gradle and under android I changed to: buildToolsVersion 19.1.0

Then I had to rebuild again, and the error was gone.

What's is the difference between include and extend in use case diagram?

Diagram Elements

  • Actors: Also referred to as Roles. Name and stereotype of an actor can be changed in its Properties tab.

  • Inheritance: Refinement relations between actors. This relation can carry a name and a stereotype.

  • Use cases: These can have Extension Points.

  • Extension Points: This defines a location where an extension can be added.

  • Associations: Between roles and use cases. It is useful to give associations speaking names.

  • Dependencies: Between use cases. Dependencies often have a stereotype to better define the role of the dependency. To select a stereotype, select the dependency from the diagram or the Navigation pane, then change the stereotype in the Properties tab. There are two special kinds of dependencies: <<extend>> and <<include>>, for which Poseidon offers own buttons (see below).

  • Extend relationship: A uni-directional relationship between two use cases. An extend relationship between use case B and use case A means that the behavior of B can be included in A.

  • Include relationship: A uni-directional relationship between two use cases. Such a relationship between use cases A and B means, that the behavior of B is always included in A.

  • System border: The system border is actually not implemented as model element in Poseidon for UML. You can simply draw a rectangle, send it to the background and use it as system border by putting all corresponding use cases inside the rectangle.

Where does the iPhone Simulator store its data?

To Open the dictories where you App are that you build in xCode on the simulators, do the following:

  1. open a Finder windor ( smiley face icon )
  2. then click GO -> Go to Folder
  3. type: ~/Library/Application Support/iPhone Simulator
  4. The Directories are the iOS version of the different Simulators
  5. The Sub Directories are the Apps install on the simulator
  6. The Documents folder is where the user generated content which gets backup up onto iCloud

Should I use Vagrant or Docker for creating an isolated environment?

I'm the author of Docker.

The short answer is that if you want to manage machines, you should use Vagrant. And if you want to build and run applications environments, you should use Docker.

Vagrant is a tool for managing virtual machines. Docker is a tool for building and deploying applications by packaging them into lightweight containers. A container can hold pretty much any software component along with its dependencies (executables, libraries, configuration files, etc.), and execute it in a guaranteed and repeatable runtime environment. This makes it very easy to build your app once and deploy it anywhere - on your laptop for testing, then on different servers for live deployment, etc.

It's a common misconception that you can only use Docker on Linux. That's incorrect; you can also install Docker on Mac, and Windows. When installed on Mac, Docker bundles a tiny Linux VM (25 MB on disk!) which acts as a wrapper for your container. Once installed this is completely transparent; you can use the Docker command-line in exactly the same way. This gives you the best of both worlds: you can test and develop your application using containers, which are very lightweight, easy to test and easy to move around (see for example https://hub.docker.com for sharing reusable containers with the Docker community), and you don't need to worry about the nitty-gritty details of managing virtual machines, which are just a means to an end anyway.

In theory it's possible to use Vagrant as an abstraction layer for Docker. I recommend against this for two reasons:

  • First, Vagrant is not a good abstraction for Docker. Vagrant was designed to manage virtual machines. Docker was designed to manage an application runtime. This means that Docker, by design, can interact with an application in richer ways, and has more information about the application runtime. The primitives in Docker are processes, log streams, environment variables, and network links between components. The primitives in Vagrant are machines, block devices, and ssh keys. Vagrant simply sits lower in the stack, and the only way it can interact with a container is by pretending it's just another kind of machine, that you can "boot" and "log into". So, sure, you can type "vagrant up" with a Docker plugin and something pretty will happen. Is it a substitute for the full breadth of what Docker can do? Try native Docker for a couple days and see for yourself :)

  • Second, the lock-in argument. "If you use Vagrant as an abstraction, you will not be locked into Docker!". From the point of view of Vagrant, which is designed to manage machines, this makes perfect sense: aren't containers just another kind of machine? Just like Amazon EC2 and VMware, we must be careful not to tie our provisioning tools to any particular vendor! This would create lock-in - better to abstract it all away with Vagrant. Except this misses the point of Docker entirely. Docker doesn't provision machines; it wraps your application in a lightweight portable runtime which can be dropped anywhere.

What runtime you choose for your application has nothing to do with how you provision your machines! For example it's pretty frequent to deploy applications to machines which are provisioned by someone else (for example an EC2 instance deployed by your system administrator, perhaps using Vagrant), or to bare metal machines which Vagrant can't provision at all. Conversely, you may use Vagrant to provision machines which have nothing to do with developing your application - for example a ready-to-use Windows IIS box or something. Or you may use Vagrant to provision machines for projects which don't use Docker - perhaps they use a combination of rubygems and rvm for dependency management and sandboxing for example.

In summary: Vagrant is for managing machines, and Docker is for building and running application environments.

grep a file, but show several surrounding lines?

grep astring myfile -A 5 -B 5

That will grep "myfile" for "astring", and show 5 lines before and after each match

Example of waitpid() in use?

Syntax of waitpid():

pid_t waitpid(pid_t pid, int *status, int options);

The value of pid can be:

  • < -1: Wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

  • WNOHANG: Return immediately if no child has exited.
  • WUNTRACED: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED: Also return if a stopped child has been resumed by delivery of SIGCONT.

For more help, use man waitpid.

How to use apply a custom drawable to RadioButton?

if you want to change the only icon of radio button then you can only add android:button="@drawable/ic_launcher" to your radio button and for making sensitive on click then you have to use the selector

 <?xml version="1.0" encoding="utf-8"?>
 <selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:drawable="@drawable/image_what_you_want_on_select_state" android:state_checked="true"/>
<item android:drawable="@drawable/image_what_you_want_on_un_select_state"    android:state_checked="false"/>


 </selector>

and set to your radio android:background="@drawable/name_of_selector"

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

Using Sockets to send and receive data

    //Client

    import java.io.*;
    import java.net.*;

    public class Client {
        public static void main(String[] args) {

        String hostname = "localhost";
        int port = 6789;

        // declaration section:
        // clientSocket: our client socket
        // os: output stream
        // is: input stream

            Socket clientSocket = null;  
            DataOutputStream os = null;
            BufferedReader is = null;

        // Initialization section:
        // Try to open a socket on the given port
        // Try to open input and output streams

            try {
                clientSocket = new Socket(hostname, port);
                os = new DataOutputStream(clientSocket.getOutputStream());
                is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            } catch (UnknownHostException e) {
                System.err.println("Don't know about host: " + hostname);
            } catch (IOException e) {
                System.err.println("Couldn't get I/O for the connection to: " + hostname);
            }

        // If everything has been initialized then we want to write some data
        // to the socket we have opened a connection to on the given port

        if (clientSocket == null || os == null || is == null) {
            System.err.println( "Something is wrong. One variable is null." );
            return;
        }

        try {
            while ( true ) {
            System.out.print( "Enter an integer (0 to stop connection, -1 to stop server): " );
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String keyboardInput = br.readLine();
            os.writeBytes( keyboardInput + "\n" );

            int n = Integer.parseInt( keyboardInput );
            if ( n == 0 || n == -1 ) {
                break;
            }

            String responseLine = is.readLine();
            System.out.println("Server returns its square as: " + responseLine);
            }

            // clean up:
            // close the output stream
            // close the input stream
            // close the socket

            os.close();
            is.close();
            clientSocket.close();   
        } catch (UnknownHostException e) {
            System.err.println("Trying to connect to unknown host: " + e);
        } catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
        }           
    }





//Server




import java.io.*;
import java.net.*;

public class Server1 {
    public static void main(String args[]) {
    int port = 6789;
    Server1 server = new Server1( port );
    server.startServer();
    }

    // declare a server socket and a client socket for the server

    ServerSocket echoServer = null;
    Socket clientSocket = null;
    int port;

    public Server1( int port ) {
    this.port = port;
    }

    public void stopServer() {
    System.out.println( "Server cleaning up." );
    System.exit(0);
    }

    public void startServer() {
    // Try to open a server socket on the given port
    // Note that we can't choose a port less than 1024 if we are not
    // privileged users (root)

        try {
        echoServer = new ServerSocket(port);
        }
        catch (IOException e) {
        System.out.println(e);
        }   

    System.out.println( "Waiting for connections. Only one connection is allowed." );

    // Create a socket object from the ServerSocket to listen and accept connections.
    // Use Server1Connection to process the connection.

    while ( true ) {
        try {
        clientSocket = echoServer.accept();
        Server1Connection oneconnection = new Server1Connection(clientSocket, this);
        oneconnection.run();
        }   
        catch (IOException e) {
        System.out.println(e);
        }
    }
    }
}

class Server1Connection {
    BufferedReader is;
    PrintStream os;
    Socket clientSocket;
    Server1 server;

    public Server1Connection(Socket clientSocket, Server1 server) {
    this.clientSocket = clientSocket;
    this.server = server;
    System.out.println( "Connection established with: " + clientSocket );
    try {
        is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
        os = new PrintStream(clientSocket.getOutputStream());
    } catch (IOException e) {
        System.out.println(e);
    }
    }

    public void run() {
        String line;
    try {
        boolean serverStop = false;

            while (true) {
                line = is.readLine();
        System.out.println( "Received " + line );
                int n = Integer.parseInt(line);
        if ( n == -1 ) {
            serverStop = true;
            break;
        }
        if ( n == 0 ) break;
                os.println("" + n*n ); 
            }

        System.out.println( "Connection closed." );
            is.close();
            os.close();
            clientSocket.close();

        if ( serverStop ) server.stopServer();
    } catch (IOException e) {
        System.out.println(e);
    }
    }
}

VBA copy cells value and format

This page from Microsoft's Excel VBA documentation helped me: https://docs.microsoft.com/en-us/office/vba/api/excel.xlpastetype

It gives a bunch of options to customize how you paste. For instance, you could xlPasteAll (probably what you're looking for), or xlPasteAllUsingSourceTheme, or even xlPasteAllExceptBorders.

Access mysql remote database from command line

There is simple command.

mysql -h {hostip} -P {port} -u {username} -p {database}

Example

mysql -h 192.16.16.2 -P 45012 -u rockbook -p rockbookdb

Windows error 2 occured while loading the Java VM

If you get the error after installation: Find the .lax file with the matching exe name and update current vm path from:

lax.nl.current.vm=C:\ProgramData\Oracle\Java\javapath\java.exe

to

lax.nl.current.vm=C:\Program Files\Java\jre1.8.0_144\bin\java.exe

How do I check if an array includes a value in JavaScript?

While array.indexOf(x)!=-1 is the most concise way to do this (and has been supported by non-Internet Explorer browsers for over decade...), it is not O(1), but rather O(N), which is terrible. If your array will not be changing, you can convert your array to a hashtable, then do table[x]!==undefined or ===undefined:

Array.prototype.toTable = function() {
    var t = {};
    this.forEach(function(x){t[x]=true});
    return t;
}

Demo:

var toRemove = [2,4].toTable();
[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})

(Unfortunately, while you can create an Array.prototype.contains to "freeze" an array and store a hashtable in this._cache in two lines, this would give wrong results if you chose to edit your array later. JavaScript has insufficient hooks to let you keep this state, unlike Python for example.)

Casting interfaces for deserialization in JSON.NET

For those that might be curious about the ConcreteListTypeConverter that was referenced by Oliver, here is my attempt:

public class ConcreteListTypeConverter<TInterface, TImplementation> : JsonConverter where TImplementation : TInterface 
{
    public override bool CanConvert(Type objectType)
    {
        return true;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var res = serializer.Deserialize<List<TImplementation>>(reader);
        return res.ConvertAll(x => (TInterface) x);
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        serializer.Serialize(writer, value);
    }
}

Pressed <button> selector

You could use :focus which will remain the style as long as the user doesn't click elsewhere.

button:active {
    border: 2px solid green;
}

button:focus {
    border: 2px solid red;
}

Is it possible to have a multi-line comments in R?

if(FALSE) {
...
}

precludes multiple lines from being executed. However, these lines still have to be syntactically correct, i.e., can't be comments in the proper sense. Still helpful for some cases though.

plot with custom text for x axis points

This worked for me. Each month on X axis

str_month_list = ['January','February','March','April','May','June','July','August','September','October','November','December']
ax.set_xticks(range(0,12))
ax.set_xticklabels(str_month_list)

Turn Pandas Multi-Index into column

As @cs95 mentioned in a comment, to drop only one level, use:

df.reset_index(level=[...])

This avoids having to redefine your desired index after reset.

How do I select the "last child" with a specific class name in CSS?

You can't target the last instance of the class name in your list without JS.

However, you may not be entirely out-of-css-luck, depending on what you are wanting to achieve. For example, by using the next sibling selector, I have added a visual divider after the last of your .list elements here: http://jsbin.com/vejixisudo/edit?html,css,output

creating a random number using MYSQL

As RAND produces a number 0 <= v < 1.0 (see documentation) you need to use ROUND to ensure that you can get the upper bound (500 in this case) and the lower bound (100 in this case)

So to produce the range you need:

SELECT name, address, ROUND(100.0 + 400.0 * RAND()) AS random_number
FROM users

How to change the value of attribute in appSettings section with Web.config transformation

Replacing all AppSettings

This is the overkill case where you just want to replace an entire section of the web.config. In this case I will replace all AppSettings in the web.config will new settings in web.release.config. This is my baseline web.config appSettings:

<appSettings>
  <add key="KeyA" value="ValA"/>
  <add key="KeyB" value="ValB"/>
</appSettings>

Now in my web.release.config file, I am going to create a appSettings section except I will include the attribute xdt:Transform=”Replace” since I want to just replace the entire element. I did not have to use xdt:Locator because there is nothing to locate – I just want to wipe the slate clean and replace everything.

<appSettings xdt:Transform="Replace">
  <add key="ProdKeyA" value="ProdValA"/>
  <add key="ProdKeyB" value="ProdValB"/>
  <add key="ProdKeyC" value="ProdValC"/>
</appSettings>

Note that in the web.release.config file my appSettings section has three keys instead of two, and the keys aren’t even the same. Now let’s look at the generated web.config file what happens when we publish:

<appSettings>
   <add key="ProdKeyA" value="ProdValA"/>
   <add key="ProdKeyB" value="ProdValB"/>
   <add key="ProdKeyC" value="ProdValC"/>
 </appSettings>

Just as we expected – the web.config appSettings were completely replaced by the values in web.release config. That was easy!

iOS 10: "[App] if we're in the real pre-commit handler we can't actually add any new fences due to CA restriction"

To fix, I deleted the app from Simulator.

I also ran Clean first.

I do not think anything orientation-related triggered it. The biggest thing that changed before this symptom started is that a Swift framework started calling NSLog on worker threads instead of main thread.

Adb install failure: INSTALL_CANCELED_BY_USER

In MIUI 8 go to Developer Settings and toggle "Install over USB" to enable it.

Call a REST API in PHP

Use HTTPFUL

Httpful is a simple, chainable, readable PHP library intended to make speaking HTTP sane. It lets the developer focus on interacting with APIs instead of sifting through curl set_opt pages and is an ideal PHP REST client.

Httpful includes...

  • Readable HTTP Method Support (GET, PUT, POST, DELETE, HEAD, and OPTIONS)
  • Custom Headers
  • Automatic "Smart" Parsing
  • Automatic Payload Serialization
  • Basic Auth
  • Client Side Certificate Auth
  • Request "Templates"

Ex.

Send off a GET request. Get automatically parsed JSON response.

The library notices the JSON Content-Type in the response and automatically parses the response into a native PHP object.

$uri = "https://www.googleapis.com/freebase/v1/mqlread?query=%7B%22type%22:%22/music/artist%22%2C%22name%22:%22The%20Dead%20Weather%22%2C%22album%22:%5B%5D%7D";
$response = \Httpful\Request::get($uri)->send();

echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";

What is the best way to remove a table row with jQuery?

function removeRow(row) {
    $(row).remove();
}

<tr onmousedown="removeRow(this)"><td>Foo</td></tr>

Maybe something like this could work as well? I haven't tried doing something with "this", so I don't know if it works or not.

multiple conditions for JavaScript .includes() method

That should work even if one, and only one of the conditions is true :

var str = "bonjour le monde vive le javascript";
var arr = ['bonjour','europe', 'c++'];

function contains(target, pattern){
    var value = 0;
    pattern.forEach(function(word){
      value = value + target.includes(word);
    });
    return (value === 1)
}

console.log(contains(str, arr));

What's the difference between session.persist() and session.save() in Hibernate?

I have done good research on the save() vs. persist() including running it on my local machine several times. All the previous explanations are confusing and incorrect. I compare save() and persist() methods below after a thorough research.

Save()

  1. Returns generated Id after saving. Its return type is Serializable;
  2. Saves the changes to the database outside of the transaction;
  3. Assigns the generated id to the entity you are persisting;
  4. session.save() for a detached object will create a new row in the table.

Persist()

  1. Does not return generated Id after saving. Its return type is void;
  2. Does not save the changes to the database outside of the transaction;
  3. Assigns the generated Id to the entity you are persisting;
  4. session.persist() for a detached object will throw a PersistentObjectException, as it is not allowed.

All these are tried/tested on Hibernate v4.0.1.

How to set up Spark on Windows?

Trying to work with spark-2.x.x, building Spark source code didn't work for me.

  1. So, although I'm not going to use Hadoop, I downloaded the pre-built Spark with hadoop embeded : spark-2.0.0-bin-hadoop2.7.tar.gz

  2. Point SPARK_HOME on the extracted directory, then add to PATH: ;%SPARK_HOME%\bin;

  3. Download the executable winutils from the Hortonworks repository, or from Amazon AWS platform winutils.

  4. Create a directory where you place the executable winutils.exe. For example, C:\SparkDev\x64. Add the environment variable %HADOOP_HOME% which points to this directory, then add %HADOOP_HOME%\bin to PATH.

  5. Using command line, create the directory:

    mkdir C:\tmp\hive
    
  6. Using the executable that you downloaded, add full permissions to the file directory you created but using the unixian formalism:

    %HADOOP_HOME%\bin\winutils.exe chmod 777 /tmp/hive
    
  7. Type the following command line:

    %SPARK_HOME%\bin\spark-shell
    

Scala command line input should be shown automatically.

Remark : You don't need to configure Scala separately. It's built-in too.

How can I remove the last character of a string in python?

No need to use expensive regex, if barely needed then try- Use r'(/)(?=$)' pattern that is capture last / and replace with r'' i.e. blank character.

>>>re.sub(r'(/)(?=$)',r'','/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/')
>>>'/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg'

vagrant login as root by default

vagrant destroy
vagrant up

Please add this to vagrant file:

config.ssh.username = 'vagrant'
config.ssh.password = 'vagrant'
config.ssh.insert_key = 'true'

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

Delete %LocalAppData%\Microsoft\VisualStudio\14.0\ComponentModelCache and restart Visual Studio.

Alternatively, use the Clear MEF Component Cache extension.

Unknown Column In Where Clause

Just had this problem.

Make sure there is no space in the name of the entity in the database.

e.g. ' user_name' instead of 'user_name'

How do I install Maven with Yum?

Do you need to install it with yum? There's plenty other possibilities:

  • Grab the binary from http://maven.apache.org/download.html and put it in your /usr/bn
  • If you are using Eclipse you can get the m2eclipse plugin (http://m2eclipse.sonatype.org/) which bundles a version of maven

Bootstrap: wider input field

Use the bootstrap built in classes input-large, input-medium, ... : <input type="text" class="input-large search-query">

Or use your own css:

  1. Give the element a unique classname class="search-query input-mysize"
  2. Add this in your css file (not the bootstrap.less or css files):
    .input-mysize { width: 150px }

Difference between @click and v-on:click Vuejs

They may look a bit different from normal HTML, but : and @ are valid chars for attribute names and all Vue.js supported browsers can parse it correctly. In addition, they do not appear in the final rendered markup. The shorthand syntax is totally optional, but you will likely appreciate it when you learn more about its usage later.

Source: official documentation.

How do I disable a href link in JavaScript?

you can deactivate all links in a page with this style class:

a {
    pointer-events:none;
}

now of course the trick is deactivate the links only when you need to, this is how to do it:

use an empty A class, like this:

a {}

then when you want to deactivate the links, do this:

    GetStyleClass('a').pointerEvents = "none"

    function GetStyleClass(className)
    {
       for (var i=0; i< document.styleSheets.length; i++) {
          var styleSheet = document.styleSheets[i]

          var rules = styleSheet.cssRules || styleSheet.rules

          for (var j=0; j<rules.length; j++) {
             var rule = rules[j]

             if (rule.selectorText === className) {
                return(rule.style)
             }
          }
       }

       return 0
    }

NOTE: CSS rule names are transformed to lower case in some browsers, and this code is case sensitive, so better use lower case class names for this

to reactivate links:

GetStyleClass('a').pointerEvents = ""

check this page http://caniuse.com/pointer-events for information about browser compatibility

i think this is the best way to do it, but sadly IE, like always, will not allow it :) i'm posting this anyway, because i think this contains information that can be useful, and because some projects use a know browser, like when you are using web views on mobile devices.

if you just want to deactivate ONE link (i only realize THAT was the question), i would use a function that manualy sets the url of the current page, or not, based on that condition. (like the solution you accepted)

this question was a LOT easier than i thought :)

Python calling method in class

The first argument of all methods is usually called self. It refers to the instance for which the method is being called.

Let's say you have:

class A(object):
    def foo(self):
        print 'Foo'

    def bar(self, an_argument):
        print 'Bar', an_argument

Then, doing:

a = A()
a.foo() #prints 'Foo'
a.bar('Arg!') #prints 'Bar Arg!'

There's nothing special about this being called self, you could do the following:

class B(object):
    def foo(self):
        print 'Foo'

    def bar(this_object):
        this_object.foo()

Then, doing:

b = B()
b.bar() # prints 'Foo'

In your specific case:

dangerous_device = MissileDevice(some_battery)
dangerous_device.move(dangerous_device.RIGHT) 

(As suggested in comments MissileDevice.RIGHT could be more appropriate here!)

You could declare all your constants at module level though, so you could do:

dangerous_device.move(RIGHT)

This, however, is going to depend on how you want your code to be organized!

ng is not recognized as an internal or external command

I don't have a global Angular install, only project level. One of my projects kept throwing this error while others with same setup worked fine! I just

  1. Removed the node_modules folder from the project
  2. Ran npm i in the project

Works fine now.

Is Java a Compiled or an Interpreted programming language ?

Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program.

mysql: SOURCE error 2?

On my windows 8.1, and mysql 5.7.9 MySQL Community Server (GPL), I had to remove the ; after the file path.

This failed: source E:/jokoni/db/Banking/createTables.sql;

This Worked: source E:/jokoni/db/Banking/createTables.sql (without termination, and forward slashes instead of windows' backslashes in path)

Python 3 turn range to a list

You can just construct a list from the range object:

my_list = list(range(1, 1001))

This is how you do it with generators in python2.x as well. Typically speaking, you probably don't need a list though since you can come by the value of my_list[i] more efficiently (i + 1), and if you just need to iterate over it, you can just fall back on range.

Also note that on python2.x, xrange is still indexable1. This means that range on python3.x also has the same property2

1print xrange(30)[12] works for python2.x

2The analogous statement to 1 in python3.x is print(range(30)[12]) and that works also.

CSS Custom Dropdown Select that works across all browsers IE7+ FF Webkit

As per Link: http://bavotasan.com/2011/style-select-box-using-only-css/ there are lot of extra rework that needs to be done(Put extra div and position the image there. Also the design will break as the option drilldown will be mis alligned to the the select.

Here is an easy and simple way which will allow you to put your own dropdown image and remove the browser default dropdown.(Without using any extra div). Its cross browser as well.

HTML

<select class="dropdown" name="drop-down">
  <option value="select-option">Please select...</option>
  <option value="Local-Community-Enquiry">Option 1</option>
  <option value="Bag-Packing-in-Store">Option 2</option>
</select>

CSS

select.dropdown {
  margin: 0px;
  margin-top: 12px;
  height: 48px;
  width: 100%;
  border-width: 1px;
  border-style: solid;
  border-color: #666666;
  padding: 9px;
  font-family: tescoregular;
  font-size: 16px;
  color: #666666;
  -webkit-appearance: none;
  -webkit-border-radius: 0px;
  -moz-appearance: none;
  appearance: none;
  background: url('yoururl/dropdown.png') no-repeat 97% 50% #ffffff;
  background-size: 11px 7px;
}

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

In case someone is using git svn, I had the same problem but could not remove the file since it was not there!. After checking permissions, touching the file and deleting it, and I don't remember what else, this did the trick:

  • checkout the master branch.
  • git svn rebase (on master)
  • checkout the branch you were working on
  • git svn rebase

How to configure slf4j-simple

I noticed that Eemuli said that you can't change the log level after they are created - and while that might be the design, it isn't entirely true.

I ran into a situation where I was using a library that logged to slf4j - and I was using the library while writing a maven mojo plugin.

Maven uses a (hacked) version of the slf4j SimpleLogger, and I was unable to get my plugin code to reroute its logging to something like log4j, which I could control.

And I can't change the maven logging config.

So, to quiet down some noisy info messages, I found I could use reflection like this, to futz with the SimpleLogger at runtime.

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.spi.LocationAwareLogger;
    try
    {
        Logger l = LoggerFactory.getLogger("full.classname.of.noisy.logger");  //This is actually a MavenSimpleLogger, but due to various classloader issues, can't work with the directly.
        Field f = l.getClass().getSuperclass().getDeclaredField("currentLogLevel");
        f.setAccessible(true);
        f.set(l, LocationAwareLogger.WARN_INT);
    }
    catch (Exception e)
    {
        getLog().warn("Failed to reset the log level of " + loggerName + ", it will continue being noisy.", e);
    }

Of course, note, this isn't a very stable / reliable solution... as it will break the next time the maven folks change their logger.

What is difference between mutable and immutable String in java

What is difference between mutable and immutable String in java

immutable exist, mutable don't.

Pass PDO prepared statement to variables

You could do $stmt->queryString to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.

How to convert enum value to int?

Sometime some C# approach makes the life easier in Java world..:

class XLINK {
static final short PAYLOAD = 102, ACK = 103, PAYLOAD_AND_ACK = 104;
}
//Now is trivial to use it like a C# enum:
int rcv = XLINK.ACK;

Error 'tunneling socket' while executing npm install

according to this it's proxy isssues, try to disable ssl and set registry to http instead of https . hope it helps!

npm config set registry=http://registry.npmjs.org/
npm config set strict-ssl false

PHP - Fatal error: Unsupported operand types

I guess you want to do this:

$total_rating_count = count($total_rating_count);
if ($total_rating_count > 0) // because you can't divide through zero
   $avg = round($total_rating_points / $total_rating_count, 1);

Change one value based on another value in pandas

I found it much easier to debut by printing out where each row meets the condition:

for n in df.columns:
    if(np.where(df[n] == 103)):
        print(n)
        print(df[df[n] == 103].index)

Javascript Array of Functions

Execution of many functions through an ES6 callback

_x000D_
_x000D_
const f = (funs) => {_x000D_
  funs().forEach((fun) => fun)_x000D_
}_x000D_
_x000D_
f(() => [_x000D_
  console.log(1),_x000D_
  console.log(2),_x000D_
  console.log(3)_x000D_
])
_x000D_
_x000D_
_x000D_

Casting int to bool in C/C++

There some kind of old school 'Marxismic' way to the cast int -> bool without C4800 warnings of Microsoft's cl compiler - is to use negation of negation.

int  i  = 0;
bool bi = !!i;

int  j  = 1;
bool bj = !!j;

Limit String Length

$res = explode("\n",wordwrap('12345678910', 8, "...\n",true))[0];

// $res will be  : "12345678..."

Download file of any type in Asp.Net MVC using FileResult?

Phil Haack has a nice article where he created a Custom File Download Action Result class. You only need to specify the virtual path of the file and the name to be saved as.

I used it once and here's my code.

        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Download(int fileID)
        {
            Data.LinqToSql.File file = _fileService.GetByID(fileID);

            return new DownloadResult { VirtualPath = GetVirtualPath(file.Path),
                                        FileDownloadName = file.Name };
        }

In my example i was storing the physical path of the files so i used this helper method -that i found somewhere i can't remember- to convert it to a virtual path

        private string GetVirtualPath(string physicalPath)
        {
            string rootpath = Server.MapPath("~/");

            physicalPath = physicalPath.Replace(rootpath, "");
            physicalPath = physicalPath.Replace("\\", "/");

            return "~/" + physicalPath;
        }

Here's the full class as taken from Phill Haack's article

public class DownloadResult : ActionResult {

    public DownloadResult() {}

    public DownloadResult(string virtualPath) {
        this.VirtualPath = virtualPath;
    }

    public string VirtualPath {
        get;
        set;
    }

    public string FileDownloadName {
        get;
        set;
    }

    public override void ExecuteResult(ControllerContext context) {
        if (!String.IsNullOrEmpty(FileDownloadName)) {
            context.HttpContext.Response.AddHeader("content-disposition", 
            "attachment; filename=" + this.FileDownloadName)
        }

        string filePath = context.HttpContext.Server.MapPath(this.VirtualPath);
        context.HttpContext.Response.TransmitFile(filePath);
    }
}

Create an empty object in JavaScript with {} or new Object()?

The object and array literal syntax {}/[] was introduced in JavaScript 1.2, so is not available (and will produce a syntax error) in versions of Netscape Navigator prior to 4.0.

My fingers still default to saying new Array(), but I am a very old man. Thankfully Netscape 3 is not a browser many people ever have to consider today...

How to add text inside the doughnut chart using Chart.js?

I create a demo with 7 jQueryUI Slider and ChartJs (with dynamic text inside)

Chart.types.Doughnut.extend({
        name: "DoughnutTextInside",
        showTooltip: function() {
            this.chart.ctx.save();
            Chart.types.Doughnut.prototype.showTooltip.apply(this, arguments);
            this.chart.ctx.restore();
        },
        draw: function() {
            Chart.types.Doughnut.prototype.draw.apply(this, arguments);

            var width = this.chart.width,
                height = this.chart.height;

            var fontSize = (height / 140).toFixed(2);
            this.chart.ctx.font = fontSize + "em Verdana";
            this.chart.ctx.textBaseline = "middle";

            var red = $( "#red" ).slider( "value" ),
            green = $( "#green" ).slider( "value" ),
            blue = $( "#blue" ).slider( "value" ),
            yellow = $( "#yellow" ).slider( "value" ),
            sienna = $( "#sienna" ).slider( "value" ),
            gold = $( "#gold" ).slider( "value" ),
            violet = $( "#violet" ).slider( "value" );
            var text = (red+green+blue+yellow+sienna+gold+violet) + " minutes";
            var textX = Math.round((width - this.chart.ctx.measureText(text).width) / 2);
            var textY = height / 2;
            this.chart.ctx.fillStyle = '#000000';
            this.chart.ctx.fillText(text, textX, textY);
        }
    });


var ctx = $("#myChart").get(0).getContext("2d");
var myDoughnutChart = new Chart(ctx).DoughnutTextInside(data, {
    responsive: false
});

DEMO IN JSFIDDLE

enter image description here

What is the most "pythonic" way to iterate over a list in chunks?

In your second method, I would advance to the next group of 4 by doing this:

ints = ints[4:]

However, I haven't done any performance measurement so I don't know which one might be more efficient.

Having said that, I would usually choose the first method. It's not pretty, but that's often a consequence of interfacing with the outside world.

Oracle SQL, concatenate multiple columns + add text

select 'i like' || type_column || ' with' ect....

generate random string for div id

2018 edit: I think this answer has some interesting info, but for any practical applications you should use Joe's answer instead.

A simple way to create a unique ID in JavaScript is to use the Date object:

var uniqid = Date.now();

That gives you the total milliseconds elapsed since January 1st 1970, which is a unique value every time you call that.

The problem with that value now is that you cannot use it as an element's ID, since in HTML, IDs need to start with an alphabetical character. There is also the problem that two users doing an action at the exact same time might result in the same ID. We could lessen the probability of that, and fix our alphabetical character problem, by appending a random letter before the numerical part of the ID.

var randLetter = String.fromCharCode(65 + Math.floor(Math.random() * 26));
var uniqid = randLetter + Date.now();

This still has a chance, however slim, of colliding though. Your best bet for a unique id is to keep a running count, increment it every time, and do all that in a single place, ie, on the server.

How to get parameter value for date/time column from empty MaskedTextBox

You're storing the .Text properties of the textboxes directly into the database, this doesn't work. The .Text properties are Strings (i.e. simple text) and not typed as DateTime instances. Do the conversion first, then it will work.

Do this for each date parameter:

Dim bookIssueDate As DateTime = DateTime.ParseExact( txtBookDateIssue.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture ) cmd.Parameters.Add( New OleDbParameter("@Date_Issue", bookIssueDate ) ) 

Note that this code will crash/fail if a user enters an invalid date, e.g. "64/48/9999", I suggest using DateTime.TryParse or DateTime.TryParseExact, but implementing that is an exercise for the reader.

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

Does a valid XML file require an XML declaration?

It is only required if you aren't using the default values for version and encoding (which you are in that example).

Best way to show a loading/progress indicator?

Use ProgressDialog

ProgressDialog.show(Context context, CharSequence title, CharSequence message);

enter image description here

However this is considered as an anti pattern today (2013): http://www.youtube.com/watch?v=pEGWcMTxs3I

php form action php self

You can use an echo shortcut also instead of typing out "echo blah;" as shown below:

<form method="POST" action="<?=($_SERVER['PHP_SELF'])?>">

Selenium wait until document is ready

For C# NUnit, you need to convert WebDriver to JSExecuter and then execute the script to check if document.ready state is complete or not. Check below code for reference:

 public static void WaitForLoad(IWebDriver driver)
    {
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        int timeoutSec = 15;
        WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0, 0, timeoutSec));
        wait.Until(wd => js.ExecuteScript("return document.readyState").ToString() == "complete");
    }

This will wait until the condition is satisfied or timeout.

Google maps API V3 method fitBounds()

 var map = new google.maps.Map(document.getElementById("map"),{
                mapTypeId: google.maps.MapTypeId.ROADMAP

            });
var bounds = new google.maps.LatLngBounds();

for (i = 0; i < locations.length; i++){
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(locations[i][1], locations[i][2]),
            map: map
        });
bounds.extend(marker.position);
}
map.fitBounds(bounds);

Step out of current function with GDB

You can use the finish command.

finish: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated as fin.

(See 5.2 Continuing and Stepping.)

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You need to open the file in binary mode i.e. wb instead of w. If you don't, the end of line characters are auto-converted to OS specific ones.

Here is an excerpt from Python reference about open().

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

nginx error connect to php5-fpm.sock failed (13: Permission denied)

I had the similar error.

All recommendations didn't help.

The only replacement www-data with nginx has helped:

$ sudo chown nginx:nginx /var/run/php/php7.2-fpm.sock

/var/www/php/fpm/pool.d/www.conf

user = nginx
group = nginx
...
listen.owner = nginx
listen.group = nginx
listen.mode = 0660

How do you do relative time in Rails?

What about

30.seconds.ago
2.days.ago

Or something else you were shooting for?

How to convert strings into integers in Python?

See this function

def parse_int(s):
    try:
        res = int(eval(str(s)))
        if type(res) == int:
            return res
    except:
        return

Then

val = parse_int('10')  # Return 10
val = parse_int('0')  # Return 0
val = parse_int('10.5')  # Return 10
val = parse_int('0.0')  # Return 0
val = parse_int('Ten')  # Return None

You can also check

if val == None:  # True if input value can not be converted
    pass  # Note: Don't use 'if not val:'

How to cache data in a MVC application

HttpContext.Current.Cache.Insert("subjectlist", subjectlist);

Using Python to execute a command on every file in a folder

Or you could use the os.path.walk function, which does more work for you than just os.walk:

A stupid example:

def walk_func(blah_args, dirname,names):
    print ' '.join(('In ',dirname,', called with ',blah_args))
    for name in names:
        print 'Walked on ' + name

if __name__ == '__main__':
    import os.path
    directory = './'
    arguments = '[args go here]'
    os.path.walk(directory,walk_func,arguments)

How do I set a fixed background image for a PHP file?

You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do

<head>
    <?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
    <title>Title</title>
</hea>

Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.

Pip freeze vs. pip list

pip list shows ALL installed packages.

pip freeze shows packages YOU installed via pip (or pipenv if using that tool) command in a requirements format.

Remark below that setuptools, pip, wheel are installed when pipenv shell creates my virtual envelope. These packages were NOT installed by me using pip:

test1 % pipenv shell
Creating a virtualenv for this project…
Pipfile: /Users/terrence/Development/Python/Projects/test1/Pipfile
Using /usr/local/Cellar/pipenv/2018.11.26_3/libexec/bin/python3.8 (3.8.1) to create virtualenv…
? Creating virtual environment...
<SNIP>
Installing setuptools, pip, wheel...
done.
? Successfully created virtual environment! 
<SNIP>

Now review & compare the output of the respective commands where I've only installed cool-lib and sampleproject (of which peppercorn is a dependency):

test1 % pip freeze       <== Packages I'VE installed w/ pip

-e git+https://github.com/gdamjan/hello-world-python-package.git@10<snip>71#egg=cool_lib
peppercorn==0.6
sampleproject==1.3.1


test1 % pip list         <== All packages, incl. ones I've NOT installed w/ pip

Package       Version Location                                                                    
------------- ------- --------------------------------------------------------------------------
cool-lib      0.1  /Users/terrence/.local/share/virtualenvs/test1-y2Zgz1D2/src/cool-lib           <== Installed w/ `pip` command
peppercorn    0.6       <== Dependency of "sampleproject"
pip           20.0.2  
sampleproject 1.3.1     <== Installed w/ `pip` command
setuptools    45.1.0  
wheel         0.34.2

Biggest advantage to using ASP.Net MVC vs web forms

MVC lets you have more than one form on a page, A small feature I know but it is handy!

Also the MVC pattern I feel make the code easier to maintain, esp. when you revisiting it after a few months.

Visual Studio Expand/Collapse keyboard shortcuts

For collapse, you can try CTRL + M + O and expand using CTRL + M + P. This works in VS2008.

Getting the folder name from a path

This is ugly but avoids allocations:

private static string GetFolderName(string path)
{
    var end = -1;
    for (var i = path.Length; --i >= 0;)
    {
        var ch = path[i];
        if (ch == System.IO.Path.DirectorySeparatorChar ||
            ch == System.IO.Path.AltDirectorySeparatorChar ||
            ch == System.IO.Path.VolumeSeparatorChar)
        {
            if (end > 0)
            {
                return path.Substring(i + 1, end - i - 1);
            }

            end = i;
        }
    }

    if (end > 0)
    {
        return path.Substring(0, end);
    }

    return path;
}

JSON.parse unexpected token s

What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.

so something is not a valid JSON but "something" is.

A valid JSON is -

JSON = null
    /* boolean literal */
    or true or false
    /* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/
    or JSONNumber
    /* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/
    or JSONString

    /* Property names must be double-quoted strings; trailing commas are forbidden. */
    or JSONObject
    or JSONArray

Examples -

JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null 
JSON.parse("'foo'"); // error since string should be wrapped by double quotes

You may want to look JSON.

Programmatically set image to UIImageView with Xcode 6.1/Swift

In Swift 4, if the image is returned as nil.

Click on image, on the right hand side (Utilities) -> Check Target Membership

Keystore change passwords

KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.

  1. Open an existing KeyStore
  2. Tools -> Set KeyStore password

How to implement zoom effect for image view in android?

I prefered the library davemorrissey/subsampling-scale-image-view over chrisbanes/PhotoView (answer of star18bit)

  • Both are active projects (both have some commits in 2015)
  • Both have a Demo on the PlayStore
  • subsampling-scale-image-view supports large images (above 1080p) without memory exception due to sub sampling, which PhotoView doesn't support
  • subsampling-scale-image-view seems to have larger API and better documentation

See How to convert AAR to JAR, if you like to use subsampling-scale-image-view with Eclipse/ADT

How can I check whether a numpy array is empty or not?

You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array:

import numpy as np
a = np.array([])

if a.size == 0:
    # Do something when `a` is empty

Open URL in new window with JavaScript

Don't confuse, if you won't give any strWindowFeatures then it will open in a new tab.

window.open('https://play.google.com/store/apps/details?id=com.drishya');

How to get anchor text/href on click using jQuery?

Updated code

$('a','div.res').click(function(){
  var currentAnchor = $(this);
  alert(currentAnchor.text());
  alert(currentAnchor.attr('href'));
});

Is JVM ARGS '-Xms1024m -Xmx2048m' still useful in Java 8?

What I know is one reason when “GC overhead limit exceeded” error is thrown when 2% of the memory is freed after several GC cycles

By this error your JVM is signalling that your application is spending too much time in garbage collection. so the little amount GC was able to clean will be quickly filled again thus forcing GC to restart the cleaning process again.

You should try changing the value of -Xmx and -Xms.

C# : changing listbox row color?

Once you've added your listbox item to your form, change DrawMode with OwnerDrawFixed option from the Properties panel. If you forget to do this, none of the codes below will work. Then click DrawItem event from the Events area.

private void listBox1_DrawItem(object sender, DrawItemEventArgs e)
{
   // 1. Get the item
   string selectedItem = listBox1.Items[e.Index].ToString();
                    
   // 2. Choose font 
   Font font = new Font("Arial", 12);
        
   // 3. Choose colour
   SolidBrush solidBrush = new SolidBrush(Color.Red);
        
   // 4. Get bounds
   int left = e.Bounds.Left;
   int top = e.Bounds.Top;
                    
   // 5. Use Draw the background within the bounds
   e.DrawBackground();
        
   // 6. Colorize listbox items
   e.Graphics.DrawString(selectedItem, font, solidBrush, left, top);
}

CORS header 'Access-Control-Allow-Origin' missing

in your ajax request, adding:

dataType: "jsonp",

after line :

type: 'GET',

should solve this problem ..

hope this help you

Get the position of a div/span tag

You can call the method getBoundingClientRect() on a reference to the element. Then you can examine the top, left, right and/or bottom properties...

var offsets = document.getElementById('11a').getBoundingClientRect();
var top = offsets.top;
var left = offsets.left;

If using jQuery, you can use the more succinct code...

var offsets = $('#11a').offset();
var top = offsets.top;
var left = offsets.left;

Understanding __get__ and __set__ and Python descriptors

I tried (with minor changes as suggested) the code from Andrew Cooke's answer. (I am running python 2.7).

The code:

#!/usr/bin/env python
class Celsius:
    def __get__(self, instance, owner): return 9 * (instance.fahrenheit + 32) / 5.0
    def __set__(self, instance, value): instance.fahrenheit = 32 + 5 * value / 9.0

class Temperature:
    def __init__(self, initial_f): self.fahrenheit = initial_f
    celsius = Celsius()

if __name__ == "__main__":

    t = Temperature(212)
    print(t.celsius)
    t.celsius = 0
    print(t.fahrenheit)

The result:

C:\Users\gkuhn\Desktop>python test2.py
<__main__.Celsius instance at 0x02E95A80>
212

With Python prior to 3, make sure you subclass from object which will make the descriptor work correctly as the get magic does not work for old style classes.

Is there any way to start with a POST request using Selenium?

Well, i agree with the @Mishkin Berteig - Agile Coach answer. Using the form is the quick way to use the POST features.

Anyway, i see some mention about javascript, but no code. I have that for my own needs, which includes jquery for easy POST plus others.

Basically, using the driver.execute_script() you can send any javascript, including Ajax queries.

#/usr/local/env/python
# -*- coding: utf8 -*-
# proxy is used to inspect data involved on the request without so much code.
# using a basic http written in python. u can found it there: http://voorloopnul.com/blog/a-python-proxy-in-less-than-100-lines-of-code/

import selenium
from selenium import webdriver
import requests
from selenium.webdriver.common.proxy import Proxy, ProxyType

jquery = open("jquery.min.js", "r").read()
#print jquery

proxy = Proxy()
proxy.proxy_type = ProxyType.MANUAL
proxy.http_proxy = "127.0.0.1:3128"
proxy.socks_proxy = "127.0.0.1:3128"
proxy.ssl_proxy = "127.0.0.1:3128"

capabilities = webdriver.DesiredCapabilities.PHANTOMJS
proxy.add_to_capabilities(capabilities)

driver = webdriver.PhantomJS(desired_capabilities=capabilities)

driver.get("http://httpbin.org")
driver.execute_script(jquery) # ensure we have jquery

ajax_query = '''
            $.post( "post", {
                "a" : "%s",
                "b" : "%s"
            });
            ''' % (1,2)

ajax_query = ajax_query.replace(" ", "").replace("\n", "")
print ajax_query

result = driver.execute_script("return " + ajax_query)
#print result

#print driver.page_source

driver.close()

# this retuns that from the proxy, and is OK
'''
POST http://httpbin.org/post HTTP/1.1
Accept: */*
Referer: http://httpbin.org/
Origin: http://httpbin.org
X-Requested-With: XMLHttpRequest
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.0.0 Safari/538.1
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Content-Length: 7
Cookie: _ga=GAxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx; _gat=1
Connection: Keep-Alive
Accept-Encoding: gzip, deflate
Accept-Language: es-ES,en,*
Host: httpbin.org


None
a=1&b=2  <<---- that is OK, is the data contained into the POST
None
'''

How to access the value of a promise?

promiseA(pram).then(
     result => { 
     //make sure promiseA function allready success and response
     //do something here
}).catch(err => console.log(err)) => {
     // handle error with try catch
}

Convert Unix timestamp to a date string

awk 'BEGIN { print strftime("%c", 1271603087); }'

ActiveSheet.UsedRange.Columns.Count - 8 what does it mean?

Seems like you want to move around. Try this:

ActiveSheet.UsedRange.select

results in....

enter image description here

If you want to move that selection 3 rows up then try this

ActiveSheet.UsedRange.offset(-3).select

does this...

enter image description here

How to show a dialog to confirm that the user wishes to exit an Android Activity?

Have modified @user919216 code .. and made it compatible with WebView

@Override
public void onBackPressed() {
    if (webview.canGoBack()) {
        webview.goBack();

    }
    else
    {
     AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
       .setCancelable(false)
       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                finish();
           }
       })
       .setNegativeButton("No", new DialogInterface.OnClickListener() {
           public void onClick(DialogInterface dialog, int id) {
                dialog.cancel();
           }
       });
AlertDialog alert = builder.create();
alert.show();
    }

}

MVC 3 file upload and model binding

Solved

Model

public class Book
{
public string Title {get;set;}
public string Author {get;set;}
}

Controller

public class BookController : Controller
{
     [HttpPost]
     public ActionResult Create(Book model, IEnumerable<HttpPostedFileBase> fileUpload)
     {
         throw new NotImplementedException();
     }
}

And View

@using (Html.BeginForm("Create", "Book", FormMethod.Post, new { enctype = "multipart/form-data" }))
{      
     @Html.EditorFor(m => m)

     <input type="file" name="fileUpload[0]" /><br />      
     <input type="file" name="fileUpload[1]" /><br />      
     <input type="file" name="fileUpload[2]" /><br />      

     <input type="submit" name="Submit" id="SubmitMultiply" value="Upload" />
}

Note title of parameter from controller action must match with name of input elements IEnumerable<HttpPostedFileBase> fileUpload -> name="fileUpload[0]"

fileUpload must match

rotating axis labels in R

As Maciej Jonczyk mentioned, you may also need to increase margins

par(las=2)
par(mar=c(8,8,1,1)) # adjust as needed
plot(...)

Where is shared_ptr?

for VS2008 with feature pack update, shared_ptr can be found under namespace std::tr1.

std::tr1::shared_ptr<int> MyIntSmartPtr = new int;

of

if you had boost installation path (for example @ C:\Program Files\Boost\boost_1_40_0) added to your IDE settings:

#include <boost/shared_ptr.hpp>

Unable to open project... cannot be opened because the project file cannot be parsed

This is because project names are not suppose to have blank spaces in between them

Opening Android Settings programmatically

In case anyone finds this question and you want to open up settings for your specific application:

    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
    intent.data = Uri.parse("package:" + context.packageName)
    startActivity(intent)

Insert a new row into DataTable

@William You can use NewRow method of the datatable to get a blank datarow and with the schema as that of the datatable. You can populate this datarow and then add the row to the datatable using .Rows.Add(DataRow) OR .Rows.InsertAt(DataRow, Position). The following is a stub code which you can modify as per your convenience.

//Creating dummy datatable for testing
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("col1", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col2", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col3", typeof(String));
dt.Columns.Add(dc);

dc = new DataColumn("col4", typeof(String));
dt.Columns.Add(dc);

DataRow dr = dt.NewRow();

dr[0] = "coldata1";
dr[1] = "coldata2";
dr[2] = "coldata3";
dr[3] = "coldata4";

dt.Rows.Add(dr);//this will add the row at the end of the datatable
//OR
int yourPosition = 0;
dt.Rows.InsertAt(dr, yourPosition);

How to print multiple variable lines in Java

You can create Class Person with fields firstName and lastName and define method toString(). Here I created a util method which returns String presentation of a Person object.

This is a sample

Main

public class Main {

    public static void main(String[] args) {
        Person person = generatePerson();
        String personStr = personToString(person);
        System.out.println(personStr);
    }

    private static Person generatePerson() {
        String firstName = "firstName";//generateFirstName();
        String lastName = "lastName";//generateLastName;
        return new Person(firstName, lastName);
    }

    /*
     You can even put this method into a separate util class.
    */
    private static String personToString(Person person) {
        return person.getFirstName() + "\n" + person.getLastName();
    }
}

Person

public class Person {

    private String firstName;
    private String lastName;

    //getters, setters, constructors.
}

I prefer a separate util method to toString(), because toString() is used for debug. https://stackoverflow.com/a/3615741/4587961

I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.

Custom UITableViewCell from nib in Swift

swift 4.1.2

xib.

Create ImageCell2.swift

Step 1

import UIKit

class ImageCell2: UITableViewCell {

    @IBOutlet weak var imgBookLogo: UIImageView!
    @IBOutlet weak var lblTitle: UILabel!
    @IBOutlet weak var lblPublisher: UILabel!
    override func awakeFromNib() {
        super.awakeFromNib()
        // Initialization code
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
    }

}

step 2 . According Viewcontroller class

  import UIKit

    class ImageListVC: UIViewController,UITableViewDataSource,UITableViewDelegate {
    @IBOutlet weak var tblMainVC: UITableView!

    var arrBook : [BookItem] = [BookItem]()

    override func viewDidLoad() {
        super.viewDidLoad()
         //Regester Cell
        self.tblMainVC.register(UINib.init(nibName: "ImageCell2", bundle: nil), forCellReuseIdentifier: "ImageCell2")
        // Response Call adn Disply Record
        APIManagerData._APIManagerInstance.getAPIBook { (itemInstance) in
            self.arrBook = itemInstance.arrItem!
            self.tblMainVC.reloadData()
        }
    }
    //MARK: DataSource & delegate
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.arrBook.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//    [enter image description here][2]
        let cell  = tableView.dequeueReusableCell(withIdentifier: "ImageCell2") as! ImageCell2
        cell.lblTitle.text = self.arrBook[indexPath.row].title
        cell.lblPublisher.text = self.arrBook[indexPath.row].publisher
        if let authors = self.arrBook[indexPath.row].author {
            for item in authors{
                print(" item \(item)")
            }
        }
        let  url  = self.arrBook[indexPath.row].imageURL
        if url == nil {
            cell.imgBookLogo.kf.setImage(with: URL.init(string: ""), placeholder: UIImage.init(named: "download.jpeg"))
        }
        else{
            cell.imgBookLogo.kf.setImage(with: URL(string: url!)!, placeholder: UIImage.init(named: "download.jpeg"))
        }
        return cell
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 90
    } 

}

How to enter quotes in a Java string?

Here is full java example:-

public class QuoteInJava {     

public static void main (String args[])
    {
            System.out.println ("If you need to 'quote' in Java");
            System.out.println ("you can use single \' or double \" quote");
    }
}

Here is Out PUT:-

If you need to 'quote' in Java
you can use single ' or double " quote

enter image description here

Update MongoDB field using value of another field

For a database with high activity, you may run into issues where your updates affect actively changing records and for this reason I recommend using snapshot()

db.person.find().snapshot().forEach( function (hombre) {
    hombre.name = hombre.firstName + ' ' + hombre.lastName; 
    db.person.save(hombre); 
});

http://docs.mongodb.org/manual/reference/method/cursor.snapshot/

map function for objects (instead of arrays)

Use following map function to define myObject.map

o => f=> Object.keys(o).reduce((a,c)=> c=='map' ? a : (a[c]=f(o[c],c),a), {})

_x000D_
_x000D_
let map = o => f=> Object.keys(o).reduce((a,c)=> c=='map' ? a : (a[c]=f(o[c],c),a), {})



// TEST init

myObject = { 'a': 1, 'b': 2, 'c': 3 }
myObject.map = map(myObject);        

// you can do this instead above line but it is not recommended 
// ( you will see `map` key any/all objects)
// Object.prototype.map = map(myObject);

// OP desired interface described in question
newObject = myObject.map(function (value, label) {
    return  value * value;
});

console.log(newObject);
_x000D_
_x000D_
_x000D_

Change the value in app.config file dynamically

 XmlReaderSettings _configsettings = new XmlReaderSettings();
 _configsettings.IgnoreComments = true;

 XmlReader _configreader = XmlReader.Create(ConfigFilePath, _configsettings);
 XmlDocument doc_config = new XmlDocument();
 doc_config.Load(_configreader);
 _configreader.Close();

 foreach (XmlNode RootName in doc_config.DocumentElement.ChildNodes)
 {
     if (RootName.LocalName == "appSettings")
     {
         if (RootName.HasChildNodes)
         {
             foreach (XmlNode _child in RootName.ChildNodes)
             {
                 if (_child.Attributes["key"].Value == "HostName")
                 {
                     if (_child.Attributes["value"].Value == "false")
                         _child.Attributes["value"].Value = "true";
                 }
             }
         }
     }
 }
 doc_config.Save(ConfigFilePath);

Printing an array in C++?

Most of the libraries commonly used in C++ can't print arrays, per se. You'll have to loop through it manually and print out each value.

Printing arrays and dumping many different kinds of objects is a feature of higher level languages.

How to find the difference in days between two dates?

For MacOS sierra (maybe from Mac OS X yosemate),

To get epoch time(Seconds from 1970) from a file, and save it to a var: old_dt=`date -j -r YOUR_FILE "+%s"`

To get epoch time of current time new_dt=`date -j "+%s"`

To calculate difference of above two epoch time (( diff = new_dt - old_dt ))

To check if diff is more than 23 days (( new_dt - old_dt > (23*86400) )) && echo Is more than 23 days

NodeJS/express: Cache and 304 status code

  • Operating system: Windows
  • Browser: Chrome

I used Ctrl + F5 keyboard combination. By doing so, instead of reading from cache, I wanted to get a new response. The solution is to do hard refresh the page.

On MDN Web Docs:

"The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource."

Is there a decent wait function in C++?

Please note that the code above was tested on Code::Blocks 12.11 and Visual Studio 2012
on Windows 7.

For forcing your programme stop or wait, you have several options :


  • sleep(unsigned int)

The value has to be a positive integer in millisecond. That means that if you want your programme wait for 2 seconds, enter 2000.

Here's an example :

#include <iostream>     //for using cout
#include <stdlib.h>     //for using the function sleep

using namespace std;    //for using cout

int main(void)         
{
   cout << "test" << endl;
   sleep(5000);         //make the programme waiting for 5 seconds
   cout << "test" << endl;
   sleep(2000);         // wait for 2 seconds before closing

   return 0;
}

If you wait too long, that probably means the parameter is in seconds. So change it to this:

sleep(5);

For those who get error message or problem using sleep try to replace it by _sleep or Sleep especially on Code::Bloks.
And if you still getting problems, try to add of one this library on the beginning of the code.

#include <stdio.h>
#include <time.h>
#include <unistd.h>
#include <dos.h>
#include <windows.h>

  • system("PAUSE")

A simple "Hello world" programme on windows console application would probably close before you can see anything. That the case where you can use system("Pause").

#include <iostream>    

using namespace std;   

int main(void)         
{
    cout << "Hello world!" << endl;

    system("PAUSE");

    return 0;
}

If you get the message "error: 'system' was not declared in this scope" just add the following line at the biggining of the code :

#include <cstdlib>

  • cin.ignore()

The same result can be reached by using cin.ignore() :

#include <iostream>     

using namespace std;    

int main(void)         
{
    cout << "Hello world!" << endl;

    cin.ignore();

    return 0;
}

  • cin.get()

example :

#include <iostream>     

using namespace std;    

int main(void)         
{
    cout << "Hello world!" << endl;

    cin.get();

    return 0;
}

  • getch()

Just don't forget to add the library conio.h :

#include <iostream>     
#include <conio.h>    //for using the function getch()

using namespace std;    

int main(void)
{

    cout << "Hello world!" << endl;

    getch();

    return 0;
}

You can have message telling you to use _getch() insted of getch

iOS 7 status bar overlapping UI

With the release of iOS 7.0.4, the iOS7 fix broke in my current project, as 7.0.4 works w/o the fix. So added a minor control to just run it if running minor release 3 or less.

NSArray *vComp = [[UIDevice currentDevice].systemVersion componentsSeparatedByString:@"."];
if ([[vComp objectAtIndex:0] intValue] == 7 && [[vComp objectAtIndex:1] intValue] == 0 && [[vComp      objectAtIndex:2] intValue] <= 3 ) {
    CGRect oldBounds = [self.view bounds];
    CGRect newViewBounds = CGRectMake( 0, -10, oldBounds.size.width, oldBounds.size.height-20 );
    CGRect newWebViewBounds = CGRectMake( 0, -20, oldBounds.size.width, oldBounds.size.height-40 );
    [self.view setBounds:newViewBounds];
    [self.webView setBounds:newWebViewBounds];
}

SQL Update with row_number()

One more option

UPDATE x
SET x.CODE_DEST = x.New_CODE_DEST
FROM (
      SELECT CODE_DEST, ROW_NUMBER() OVER (ORDER BY [RS_NOM]) AS New_CODE_DEST
      FROM DESTINATAIRE_TEMP
      ) x

Angular2 - Radio Button Binding

Simplest solution and workaround:

<input name="toRent" type="radio" (click)="setToRentControl(false)">
<input name="toRent" type="radio" (click)="setToRentControl(true)">

setToRentControl(value){
    this.vm.toRent.updateValue(value);
    alert(value); //true/false
}

Changing a specific column name in pandas DataFrame

Since inplace argument is available, you don't need to copy and assign the original data frame back to itself, but do as follows:

df.rename(columns={'two':'new_name'}, inplace=True)

Changing Tint / Background color of UITabBar

When you just use addSubview your buttons will lose clickability, so instead of

[[self tabBar] addSubview:v];

use:

[[self tabBar] insertSubview:v atIndex:0];

How to navigate to a section of a page

Use an call thru section, it works

<div id="content">
     <section id="home">
               ...
     </section>

Call the above the thru

 <a href="#home">page1</a>

Scrolling needs jquery paste this.. on above to ending body closing tag..

<script>
  $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
          if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
              var target = $(this.hash);
              target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
              if (target.length) {
                  $('html,body').animate({
                      scrollTop: target.offset().top
                  }, 1000);
                  return false;
              }
          }
      });
  });
</script>

C#: List All Classes in Assembly

Use Assembly.GetTypes. For example:

Assembly mscorlib = typeof(string).Assembly;
foreach (Type type in mscorlib.GetTypes())
{
    Console.WriteLine(type.FullName);
}

How to import a bak file into SQL Server Express

I had the same error. What worked for me is when you go for the SMSS GUI option, look at General, Files in Options settings. After I did that (replace DB, set location) all went well.

Simplest code for array intersection in javascript

not about efficiency, but easy to follow, here is an example of unions and intersections of sets, it handles arrays of sets and sets of sets.

http://jsfiddle.net/zhulien/NF68T/

// process array [element, element...], if allow abort ignore the result
function processArray(arr_a, cb_a, blnAllowAbort_a)
{
    var arrResult = [];
    var blnAborted = false;
    var intI = 0;

    while ((intI < arr_a.length) && (blnAborted === false))
    {
        if (blnAllowAbort_a)
        {
            blnAborted = cb_a(arr_a[intI]);
        }
        else
        {
            arrResult[intI] = cb_a(arr_a[intI]);
        }
        intI++;
    }

    return arrResult;
}

// process array of operations [operation,arguments...]
function processOperations(arrOperations_a)
{
    var arrResult = [];
    var fnOperationE;

    for(var intI = 0, intR = 0; intI < arrOperations_a.length; intI+=2, intR++) 
    {
        var fnOperation = arrOperations_a[intI+0];
        var fnArgs = arrOperations_a[intI+1];
        if (fnArgs === undefined)
        {
            arrResult[intR] = fnOperation();
        }
        else
        {
            arrResult[intR] = fnOperation(fnArgs);
        }
    }

    return arrResult;
}

// return whether an element exists in an array
function find(arr_a, varElement_a)
{
    var blnResult = false;

    processArray(arr_a, function(varToMatch_a)
    {
        var blnAbort = false;

        if (varToMatch_a === varElement_a)
        {
            blnResult = true;
            blnAbort = true;
        }

        return blnAbort;
    }, true);

    return blnResult;
}

// return the union of all sets
function union(arr_a)
{
    var arrResult = [];
    var intI = 0;

    processArray(arr_a, function(arrSet_a)
    {
        processArray(arrSet_a, function(varElement_a)
        {
            // if the element doesn't exist in our result
            if (find(arrResult, varElement_a) === false)
            {
                // add it
                arrResult[intI] = varElement_a;
                intI++;
            }
        });
    });

    return arrResult;
}

// return the intersection of all sets
function intersection(arr_a)
{
    var arrResult = [];
    var intI = 0;

    // for each set
    processArray(arr_a, function(arrSet_a)
    {
        // every number is a candidate
        processArray(arrSet_a, function(varCandidate_a)
        {
            var blnCandidate = true;

            // for each set
            processArray(arr_a, function(arrSet_a)
            {
                // check that the candidate exists
                var blnFoundPart = find(arrSet_a, varCandidate_a);

                // if the candidate does not exist
                if (blnFoundPart === false)
                {
                    // no longer a candidate
                    blnCandidate = false;
                }
            });

            if (blnCandidate)
            {
                // if the candidate doesn't exist in our result
                if (find(arrResult, varCandidate_a) === false)
                {
                    // add it
                    arrResult[intI] = varCandidate_a;
                    intI++;
                }
            }
        });
    });

    return arrResult;
}

var strOutput = ''

var arrSet1 = [1,2,3];
var arrSet2 = [2,5,6];
var arrSet3 = [7,8,9,2];

// return the union of the sets
strOutput = union([arrSet1, arrSet2, arrSet3]);
alert(strOutput);

// return the intersection of 3 sets
strOutput = intersection([arrSet1, arrSet2, arrSet3]);
alert(strOutput);

// of 3 sets of sets, which set is the intersecting set
strOutput = processOperations([intersection,[[arrSet1, arrSet2], [arrSet2], [arrSet2, arrSet3]]]);
alert(strOutput);

How do I reference a cell within excel named range?

There are a couple different ways I would do this:

1) Mimic Excel Tables Using with a Named Range

In your example, you named the range A10:A20 "Age". Depending on how you wanted to reference a cell in that range you could either (as @Alex P wrote) use =INDEX(Age, 5) or if you want to reference a cell in range "Age" that is on the same row as your formula, just use:

=INDEX(Age, ROW()-ROW(Age)+1)

This mimics the relative reference features built into Excel tables but is an alternative if you don't want to use a table.

If the named range is an entire column, the formula simplifies as:

=INDEX(Age, ROW())

2) Use an Excel Table

Alternatively if you set this up as an Excel table and type "Age" as the header title of the Age column, then your formula in columns to the right of the Age column can use a formula like this:

=[@[Age]]

stop all instances of node.js server

Linux

To impress your friends

ps aux | grep -i node | awk '{print $2}' | xargs  kill -9

But this is the one you will remember

killall node

SQL multiple column ordering

You can use multiple ordering on multiple condition,

ORDER BY 
     (CASE 
        WHEN @AlphabetBy = 2  THEN [Drug Name]
      END) ASC,
    CASE 
        WHEN @TopBy = 1  THEN [Rx Count]
        WHEN @TopBy = 2  THEN [Cost]
        WHEN @TopBy = 3  THEN [Revenue]
    END DESC 

IntelliJ IDEA JDK configuration on Mac OS

The JDK path might change when you update JAVA. For Mac you should go to the following path to check the JAVA version installed.

/Library/Java/JavaVirtualMachines/

Next, say JDK version that you find is jdk1.8.0_151.jdk, the path to home directory within it is the JDK home path.

In my case it was :

/Library/Java/JavaVirtualMachines/jdk1.8.0_151.jdk/Contents/Home

You can configure it by going to File -> Project Structure -> SDKs.

enter image description here enter image description here

How to Import .bson file format on mongodb

Run the following from command line and you should be in the Mongo bin directory.

mongorestore -d db_name -c collection_name path/file.bson

What's the best way to check if a String represents an integer in Java?

How about:

return Pattern.matches("-?\\d+", input);

python error: no module named pylab

With the addition of Python 3, here is an updated code that works:

import numpy as n
import scipy as s
import matplotlib.pylab as p #pylab is part of matplotlib

xa=0.252
xb=1.99

C=n.linspace(xa,xb,100)
print(C)
iter=1000
Y = n.ones(len(C))

for x in range(iter):
    Y = Y**2 - C   #get rid of early transients

for x in range(iter): 
    Y = Y**2 - C
    p.plot(C,Y, '.', color = 'k', markersize = 2)

p.show()

"Unorderable types: int() < str()"

Just a side note, in Python 2.0 you could compare anything to anything (int to string). As this wasn't explicit, it was changed in 3.0, which is a good thing as you are not running into the trouble of comparing senseless values with each other or when you forget to convert a type.

SDK Location not found Android Studio + Gradle

You have also to ensure you have the correct SDK platform version installed in your environment by using SDK Manager.

Unable to resolve "unable to get local issuer certificate" using git on Windows with self-signed certificate

I have had this issue before, and solve it using the following config.

[http "https://your.domain"] sslCAInfo=/path/to/your/domain/priviate-certificate

Since git 2.3.1, you can put https://your.domain after http to indicate the following certificate is only for it.

How do I set default value of select box in angularjs

You can just append

track by version.id

to your ng-options.

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

As others have already mentioned your compile sdk version must match your support library's major version. This is however, also relevant for subprojects should you have any.

In case you do, you can set your subprojects compile sdk versions with the following script:

subprojects { subproject ->
afterEvaluate{
    if((subproject.plugins.hasPlugin('android') || subproject.plugins.hasPlugin('android-library'))) {
        android {
            compileSdkVersion rootProject.ext.compileSdkVersion
            buildToolsVersion rootProject.ext.buildToolsVersion
        }
      }
   }
}

Add this script in your root build.gradle file.

Why does foo = filter(...) return a <filter object>, not a list?

filter expects to get a function and something that it can iterate over. The function should return True or False for each element in the iterable. In your particular example, what you're looking to do is something like the following:

In [47]: def greetings(x):
   ....:     return x == "hello"
   ....:

In [48]: filter(greetings, ["hello", "goodbye"])
Out[48]: ['hello']

Note that in Python 3, it may be necessary to use list(filter(greetings, ["hello", "goodbye"])) to get this same result.

Valid characters in a Java class name

Further to previous answers its worth noting that:

  1. Java allows any Unicode currency symbol in symbol names, so the following will all work:

$var1 £var2 €var3

I believe the usage of currency symbols originates in C/C++, where variables added to your code by the compiler conventionally started with '$'. An obvious example in Java is the names of '.class' files for inner classes, which by convention have the format 'Outer$Inner.class'

  1. Many C# and C++ programmers adopt the convention of placing 'I' in front of interfaces (aka pure virtual classes in C++). This is not required, and hence not done, in Java because the implements keyword makes it very clear when something is an interface.

Compare:

class Employee : public IPayable //C++

with

class Employee : IPayable //C#

and

class Employee implements Payable //Java

  1. Many projects use the convention of placing an underscore in front of field names, so that they can readily be distinguished from local variables and parameters e.g.

private double _salary;

A tiny minority place the underscore after the field name e.g.

private double salary_;

Uninstalling Android ADT

I found a solution by myself after doing some research:

  • Go to Eclipse home folder.
  • Search for 'android' => In Windows 7 you can use search bar.
  • Delete all the file related to android, which is shown in the results.
  • Restart Eclipse.
  • Install the ADT plugin again and Restart plugin.

Now everything works fine.

Add (insert) a column between two columns in a data.frame

df <- data.frame(a=c(1,2), b=c(3,4), c=c(5,6))
df %>%
  mutate(d= a/2) %>%
  select(a, b, d, c)

results

  a b   d c
1 1 3 0.5 5
2 2 4 1.0 6

I suggest to use dplyr::select after dplyr::mutate. It has many helpers to select/de-select subset of columns.

In the context of this question the order by which you select will be reflected in the output data.frame.

NSString property: copy or retain?

If the string is very large then copy will affect performance and two copies of the large string will use more memory.

Objective-C - Remove last character from string

The solutions given here actually do not take into account multi-byte Unicode characters ("composed characters"), and could result in invalid Unicode strings.

In fact, the iOS header file which contains the declaration of substringToIndex contains the following comment:

Hint: Use with rangeOfComposedCharacterSequencesForRange: to avoid breaking up composed characters

See how to use rangeOfComposedCharacterSequenceAtIndex: to delete the last character correctly.

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

Setting attribute disabled on a SPAN element does not prevent click events

There is a dirty trick, what I have used:

I am using bootstrap, so I just added .disabled class to the element which I want to disable. Bootstrap handles the rest of the things.

Suggestion are heartily welcome towards this.

Adding class on run time:

$('#element').addClass('disabled');

Git blame -- prior commits?

I use this little bash script to look at a blame history.

First parameter: file to look at

Subsequent parameters: Passed to git blame

#!/bin/bash
f=$1
shift
{ git log --pretty=format:%H -- "$f"; echo; } | {
  while read hash; do
    echo "--- $hash"
    git blame $@ $hash -- "$f" | sed 's/^/  /'
  done
}

You may supply blame-parameters like -L 70,+10 but it is better to use the regex-search of git blame because line-numbers typically "change" over time.

Common xlabel/ylabel for matplotlib subplots

This looks like what you actually want. It applies the same approach of this answer to your specific case:

import matplotlib.pyplot as plt

fig, ax = plt.subplots(nrows=3, ncols=3, sharex=True, sharey=True, figsize=(6, 6))

fig.text(0.5, 0.04, 'common X', ha='center')
fig.text(0.04, 0.5, 'common Y', va='center', rotation='vertical')

Multiple plots with common axes label

How to create a jQuery function (a new jQuery method or plugin)?

Create a "colorize" method:

$.fn.colorize = function custom_colorize(some_color) {
    this.css('color', some_color);
    return this;
}

Use it:

$('#my_div').colorize('green');

This simple-ish example combines the best of How to Create a Basic Plugin in the jQuery docs, and answers from @Candide, @Michael.

How do a LDAP search/authenticate against this LDAP in Java

try {
    LdapContext ctx = new InitialLdapContext(env, null);
    ctx.setRequestControls(null);
    NamingEnumeration<?> namingEnum = ctx.search("ou=people,dc=example,dc=com", "(objectclass=user)", getSimpleSearchControls());
    while (namingEnum.hasMore ()) {
        SearchResult result = (SearchResult) namingEnum.next ();    
        Attributes attrs = result.getAttributes ();
        System.out.println(attrs.get("cn"));

    } 
    namingEnum.close();
} catch (Exception e) {
    e.printStackTrace();
}

private SearchControls getSimpleSearchControls() {
    SearchControls searchControls = new SearchControls();
    searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);
    searchControls.setTimeLimit(30000);
    //String[] attrIDs = {"objectGUID"};
    //searchControls.setReturningAttributes(attrIDs);
    return searchControls;
}

How to get child element by class name?

But be aware that old browsers doesn't support getElementsByClassName.

Then, you can do

function getElementsByClassName(c,el){
    if(typeof el=='string'){el=document.getElementById(el);}
    if(!el){el=document;}
    if(el.getElementsByClassName){return el.getElementsByClassName(c);}
    var arr=[],
        allEls=el.getElementsByTagName('*');
    for(var i=0;i<allEls.length;i++){
        if(allEls[i].className.split(' ').indexOf(c)>-1){arr.push(allEls[i])}
    }
    return arr;
}
getElementsByClassName('4','test')[0];

It seems it works, but be aware that an HTML class

  • Must begin with a letter: A-Z or a-z
  • Can be followed by letters (A-Za-z), digits (0-9), hyphens ("-"), and underscores ("_")

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

I'd do it this way:

@if (Request::path() == '/view')
    // code
@endif

where '/view' is view name in routes.php.

How to list the tables in a SQLite database file that was opened with ATTACH?

As of the latest versions of SQLite 3 you can issue:

.fullschema

to see all of your create statements.

Replace CRLF using powershell

Adding another version based on example above by @ricky89 and @mklement0 with few improvements:

Script to process:

  • *.txt files in the current folder
  • replace LF with CRLF (Unix to Windows line-endings)
  • save resulting files to CR-to-CRLF subfolder
  • tested on 100MB+ files, PS v5;

LF-to-CRLF.ps1:

# get current dir
$currentDirectory = Split-Path $MyInvocation.MyCommand.Path -Parent

# create subdir CR-to-CRLF for new files
$outDir = $(Join-Path $currentDirectory "CR-to-CRLF")
New-Item -ItemType Directory -Force -Path $outDir | Out-Null

# get all .txt files
Get-ChildItem $currentDirectory -Force | Where-Object {$_.extension -eq ".txt"} | ForEach-Object {
  $file = New-Object System.IO.StreamReader -Arg $_.FullName
  # Resulting file will be in CR-to-CRLF subdir
  $outstream = [System.IO.StreamWriter] $(Join-Path  $outDir $($_.BaseName + $_.Extension))
  $count = 0 
  # read line by line, replace CR with CRLF in each by saving it with $outstream.WriteLine
  while ($line = $file.ReadLine()) {
        $count += 1
        $outstream.WriteLine($line)
    }
  $file.close()
  $outstream.close()
  Write-Host ("$_`: " + $count + ' lines processed.')
}

Preventing console window from closing on Visual Studio C/C++ Console application

(/SUBSYSTEM:CONSOLE) did not worked for my vs2013 (I already had it).

"run without debugging" is not an options, since I do not want to switch between debugging and seeing output.

I ended with

int main() {
  ...
#if _DEBUG
  LOG_INFO("end, press key to close");
  getchar();
#endif // _DEBUG
  return 0;
}

Solution used in qtcreator pre 2.6. Now while qt is growing, vs is going other way. As I remember, in vs2008 we did not need such tricks.

How does one capture a Mac's command key via JavaScript?

Basing on Ilya's data, I wrote a Vanilla JS library for supporting modifier keys on Mac: https://github.com/MichaelZelensky/jsLibraries/blob/master/macKeys.js

Just use it like this, e.g.:

document.onclick = function (event) {
  if (event.shiftKey || macKeys.shiftKey) {
    //do something interesting
  }
}

Tested on Chrome, Safari, Firefox, Opera on Mac. Please check if it works for you.

How can I delete a query string parameter in JavaScript?

Glad you scrolled here.

I would suggest you to resolve this task by next possible solutions:

  1. You need to support only modern browsers (Edge >= 17) - use URLSearchParams.delete() API. It is native and obviously is the most convenient way of solving this task.
  2. If this is not an option, you may want to write a function to do this. Such a function does
    • do not change URL if a parameter is not present
    • remove URL parameter without a value, like http://google.com/?myparm
    • remove URL parameter with a value, like http://google.com/?myparm=1
    • remove URL parameter if is it in URL twice, like http://google.com?qp=1&qpqp=2&qp=1
    • Does not use for loop and not modify array during looping over it
    • is more functional
    • is more readable than regexp solutions
    • Before using make sure your URL is not encoded

Works in IE > 9 (ES5 version)

_x000D_
_x000D_
function removeParamFromUrl(url, param) {  // url: string, param: string_x000D_
  var urlParts = url.split('?'),_x000D_
      preservedQueryParams = '';_x000D_
_x000D_
  if (urlParts.length === 2) {_x000D_
    preservedQueryParams = urlParts[1]_x000D_
      .split('&')_x000D_
      .filter(function(queryParam) {_x000D_
        return !(queryParam === param || queryParam.indexOf(param + '=') === 0)_x000D_
      })_x000D_
      .join('&');_x000D_
  }_x000D_
_x000D_
  return urlParts[0] +  (preservedQueryParams && '?' + preservedQueryParams); _x000D_
}
_x000D_
_x000D_
_x000D_

Fancy ES6 version

_x000D_
_x000D_
function removeParamFromUrlEs6(url, param) {_x000D_
  const [path, queryParams] = url.split('?');_x000D_
 let preservedQueryParams = '';_x000D_
_x000D_
  if (queryParams) {_x000D_
    preservedQueryParams = queryParams_x000D_
      .split('&')_x000D_
      .filter(queryParam => !(queryParam === param || queryParam.startsWith(`${param}=`)))_x000D_
      .join('&');_x000D_
  }_x000D_
_x000D_
  return `${path}${preservedQueryParams && `?${preservedQueryParams}`}`;  _x000D_
}
_x000D_
_x000D_
_x000D_

See how it works here

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

SSL certificate is not trusted - on mobile only

Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

C# Create New T()

Since this is tagged C# 4. With the open sourece framework ImpromptuIntereface it will use the dlr to call the constructor it is significantly faster than Activator when your constructor has arguments, and negligibly slower when it doesn't. However the main advantage is that it will handle constructors with C# 4.0 optional parameters correctly, something that Activator won't do.

protected T GetObject(params object[] args)
{
    return (T)Impromptu.InvokeConstructor(typeof(T), args);
}

Java: Check if enum contains a given string?

I would just write,

Arrays.stream(Choice.values()).map(Enum::name).collect(Collectors.toList()).contains("a1");

Enum#equals only works with object compare.

How to fix the height of a <div> element?

You can also use min-height and max-height. It was very useful for me

How do I view cookies in Internet Explorer 11 using Developer Tools

Sorry to break the news to ya, but there is no way to do this in IE11. I have been troubling with this for some time, but I finally had to see it as a lost course, and just navigate to the files manually.

But where are the files? That depends on a lot of things, I have found them these places on different machines:

In the the Internet Explorer cache.

This can be done via "run" (Windows+r) and then typing in shell:cache or by navigating to it through the internet options in IE11 (AskLeo has a fine guide to this, I'm not affiliated in any way).

  • Click on the gear icon, then Internet options.
  • In the General tab, underneath “Browsing history”, click on Settings.
  • In the resulting “Website Data” dialog, click on View files.
  • This will open the folder we’re interested in: your Internet Explorer cache.

Make a search for "cookie" to see the cookies only

In the Cookies folder

The path for cookies can be found here via regedit:

HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\Cookies

Common path (in 7 & 8)

%APPDATA%\Microsoft\Windows\Cookies

%APPDATA%\Microsoft\Windows\Cookies\Low

Common path (Win 10)

shell:cookies

shell:cookies\low

%userprofile%\AppData\Local\Microsoft\Windows\INetCookies

%userprofile%\AppData\Local\Microsoft\Windows\INetCookies\Low

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

Store that objects into Array  and then iterate the Array
export class AppComponent {

 public obj: object =null;
 public myArr=[];

  constructor(){

    this.obj = {
      jon : {username: 'Jon', genrePref: 'rock'},
      lucy : {username: 'Lucy', genrePref: 'pop'},
      mike : {username: 'Mike', genrePref: 'rock'},
      luke : {username: 'Luke', genrePref: 'house'},
      james : {username: 'James', genrePref: 'house'},
      dave : {username: 'Dave', genrePref: 'bass'},
      sarah : {username: 'Sarah', genrePref: 'country'},
      natalie : {username: 'Natalie', genrePref: 'bass'}
  }
  }
  ngOnInit(){
    this.populateCode();
  }

  populateCode(){
    for( let i in this.obj) {   //Pay attention to the 'in'
    console.log(this.obj[i]);
    this.myArr.push(this.obj[i]);
  }
  }
 }



<div *ngFor="let item of myArr ">
    {{item.username}}
    {{item.genrePref}}
  </div>

How to check if an object implements an interface?

If you want a method like public void doSomething([Object implements Serializable]) you can just type it like this public void doSomething(Serializable serializableObject). You can now pass it any object that implements Serializable but using the serializableObject you only have access to the methods implemented in the object from the Serializable interface.

Access denied for root user in MySQL command-line

Server file only change name folder

etc/mysql
rename
mysql-

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

ICommand MVVM implementation

I have written this article about the ICommand interface.

The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param) is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param)).

Requires the method to switching event CanExecuteChanged. It is called from the user interface elements for switching the state CanExecute() command.

public class ModelCommand : ICommand
{
    #region Constructors

    public ModelCommand(Action<object> execute)
        : this(execute, null) { }

    public ModelCommand(Action<object> execute, Predicate<object> canExecute)
    {
        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion

    #region ICommand Members

    public event EventHandler CanExecuteChanged;

    public bool CanExecute(object parameter)
    {
        return _canExecute != null ? _canExecute(parameter) : true;
    }

    public void Execute(object parameter)
    {
        if (_execute != null)
            _execute(parameter);
    }

    public void OnCanExecuteChanged()
    {
        CanExecuteChanged(this, EventArgs.Empty);
    }

    #endregion

    private readonly Action<object> _execute = null;
    private readonly Predicate<object> _canExecute = null;
}

How do I display the value of a Django form field in a template?

The solution proposed by Jens is correct. However, it turns out that if you initialize your ModelForm with an instance (example below) django will not populate the data:

def your_view(request):   
    if request.method == 'POST':
        form = UserDetailsForm(request.POST)
        if form.is_valid():
          # some code here   
        else:
          form = UserDetailsForm(instance=request.user)

So, I made my own ModelForm base class that populates the initial data:

from django import forms 
class BaseModelForm(forms.ModelForm):
    """
    Subclass of `forms.ModelForm` that makes sure the initial values
    are present in the form data, so you don't have to send all old values
    for the form to actually validate.
    """
    def merge_from_initial(self):
        filt = lambda v: v not in self.data.keys()
        for field in filter(filt, getattr(self.Meta, 'fields', ())):
            self.data[field] = self.initial.get(field, None)

Then, the simple view example looks like this:

def your_view(request):   if request.method == 'POST':
    form = UserDetailsForm(request.POST)
    if form.is_valid():
      # some code here   
    else:
      form = UserDetailsForm(instance=request.user)
      form.merge_from_initial()

How can I run code on a background thread on Android?

Today I was looking for this and Mr Brandon Rude gave an excellent answer. Unfortunately, AsyncTask is now depricated, you can still use it, but it gives you a warning which is very annoying. So an alternative is to use Executors like this way (in kotlin):


    val someRunnable = object : Runnable{
      override fun run() {
        // todo: do your background tasks
        requireActivity().runOnUiThread{
          // update views / ui if you are in a fragment
        };
        /*
        runOnUiThread {
          // update ui if you are in an activity
        }
        * */
      }
    };
    Executors.newSingleThreadExecutor().execute(someRunnable);

And in java it looks like this:


        Runnable someRunnable = new Runnable() {
            @Override
            public void run() {
                // todo: background tasks
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // todo: update your ui / view in activity
                    }
                });

                /*
                requireActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // todo: update your ui / view in Fragment
                    }
                });*/
            }
        };

        Executors.newSingleThreadExecutor().execute(someRunnable);

Get list of databases from SQL Server

Since you are using .NET you can use the SQL Server Management Objects

Dim server As New Microsoft.SqlServer.Management.Smo.Server("localhost")
For Each db As Database In server.Databases
    Console.WriteLine(db.Name)
Next

SQL Stored Procedure: If variable is not null, update statement

Another approach when you have many updates would be to use COALESCE:

UPDATE [DATABASE].[dbo].[TABLE_NAME]
SET    
    [ABC]  = COALESCE(@ABC, [ABC]),
    [ABCD] = COALESCE(@ABCD, [ABCD])

Calculate a MD5 hash from a string

// given, a password in a string
string password = @"1234abcd";

// byte array representation of that string
byte[] encodedPassword = new UTF8Encoding().GetBytes(password);

// need MD5 to calculate the hash
byte[] hash = ((HashAlgorithm) CryptoConfig.CreateFromName("MD5")).ComputeHash(encodedPassword);

// string representation (similar to UNIX format)
string encoded = BitConverter.ToString(hash)
   // without dashes
   .Replace("-", string.Empty)
   // make lowercase
   .ToLower();

// encoded contains the hash you want

DateTime's representation in milliseconds?

There are ToUnixTime() and ToUnixTimeMs() methods in DateTimeExtensions class

DateTime.UtcNow.ToUnixTimeMs()

Restart pods when configmap updates in Kubernetes?

The best way I've found to do it is run Reloader

It allows you to define configmaps or secrets to watch, when they get updated, a rolling update of your deployment is performed. Here's an example:

You have a deployment foo and a ConfigMap called foo-configmap. You want to roll the pods of the deployment every time the configmap is changed. You need to run Reloader with:

kubectl apply -f https://raw.githubusercontent.com/stakater/Reloader/master/deployments/kubernetes/reloader.yaml

Then specify this annotation in your deployment:

kind: Deployment
metadata:
  annotations:
    configmap.reloader.stakater.com/reload: "foo-configmap"
  name: foo
...

Propagation Delay vs Transmission delay

The transmission delay is the amount of time required for the router to push out the packet.

The propagation delay, is the time it takes a bit to propagate from one router to the next.

the transmission and propagation delay are completely different! if denote the length of the packet by L bits, and denote the transmission rate of the link from first router to second router by R bits/sec. then transmission delay will be L/R. and this is depended to transmission rate of link and the length of packet.

then if denote the distance between two routers d and denote the propagation speed s, the propagation delay will be d/s. it is a function of the Distance between the two routers, but has no dependence to the packet's length or the transmission rate of the link.

Convert/cast an stdClass object to another class

And yet another approach using the decorator pattern and PHPs magic getter & setters:

// A simple StdClass object    
$stdclass = new StdClass();
$stdclass->foo = 'bar';

// Decorator base class to inherit from
class Decorator {

    protected $object = NULL;

    public function __construct($object)
    {
       $this->object = $object;  
    }

    public function __get($property_name)
    {
        return $this->object->$property_name;   
    }

    public function __set($property_name, $value)
    {
        $this->object->$property_name = $value;   
    }
}

class MyClass extends Decorator {}

$myclass = new MyClass($stdclass)

// Use the decorated object in any type-hinted function/method
function test(MyClass $object) {
    echo $object->foo . '<br>';
    $object->foo = 'baz';
    echo $object->foo;   
}

test($myclass);

How to set-up a favicon?

you could take a look at the w3 how to, i think you will find it helpful

your link tag attribute should be rel="icon"

How can I send JSON response in symfony2 controller

Since Symfony 3.1 you can use JSON Helper http://symfony.com/doc/current/book/controller.html#json-helper

public function indexAction()
{
// returns '{"username":"jane.doe"}' and sets the proper Content-Type header
return $this->json(array('username' => 'jane.doe'));

// the shortcut defines three optional arguments
// return $this->json($data, $status = 200, $headers = array(), $context = array());
}

UITableView with fixed section headers

You can also set the tableview's bounces property to NO. This will keep the section headers non-floating/static, but then you also lose the bounce property of the tableview.

How to tell if node.js is installed or not

Please try this command node --version or node -v, either of which should return something like v4.4.5.

Convert Object to JSON string

You can use the excellent jquery-Json plugin:

http://code.google.com/p/jquery-json/

Makes it easy to convert to and from Json objects.

Error while sending QUERY packet

You cannot have the WHERE clause in an INSERT statement.

insert into table1(data) VALUES(:data) where sno ='45830'

Should be

insert into table1(data) VALUES(:data)


Update: You have removed that from your code (I assume you copied the code in wrong). You want to increase your allowed packet size:

SET GLOBAL max_allowed_packet=32M

Change the 32M (32 megabytes) up/down as required. Here is a link to the MySQL documentation on the subject.

How do I show a "Loading . . . please wait" message in Winforms for a long loading form?

A simple solution:

using (Form2 f2 = new Form2())
{
    f2.Show();
    f2.Update();

    System.Threading.Thread.Sleep(2500);
} // f2 is closed and disposed here

And then substitute your Loading for the Sleep.
This blocks the UI thread, on purpose.

Generate table relationship diagram from existing schema (SQL Server)

SchemaCrawler for SQL Server can generate database diagrams, with the help of GraphViz. Foreign key relationships are displayed (and can even be inferred, using naming conventions), and tables and columns can be excluded using regular expressions.

What is the difference between React Native and React?

ReactJS is a javascript library which is used to build web interfaces. You would need a bundler like webpack and try to install modules you would need to build your website.

React Native is a javascript framework and it comes with everything you need to write multi-platform apps (like iOS or Android). You would need xcode and android studio installed to build and deploy your app.

Unlike ReactJS, React-Native doesn't use HTML but similar components that you can use accross ios and android to build your app. These components use real native components to build the ios and android apps. Due to this React-Native apps feel real unlike other Hybrid development platforms. Components also increases reusability of your code as you don't need to create same user interface again on ios and android.

How to left align a fixed width string?

Use -50% instead of +50% They will be aligned to left..

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Naming threads and thread-pools of ExecutorService

I find it easiest to use a lambda as a thread factory if you just want to change the name for a single thread executor.

Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "Your name"));

How do I set the eclipse.ini -vm option?

The JDK you're pointing to in your eclipse.ini has to match the Eclipse installation.

If you are running a 32- or 64-bit Eclipse, use a 32 or 64-bit Java JDK, respectively.

Passing headers with axios POST request

axios.post can recieve accept 3 arguments that last argument can accept a config object that you can set header

Sample code with your question:

var data = {
'key1': 'val1',
'key2': 'val2'
}
axios.post(Helper.getUserAPI(), data, {
        headers: {Authorization: token && `Bearer ${ token }`}
})       
.then((response) => {
    dispatch({type: FOUND_USER, data: response.data[0]})
})
.catch((error) => {
    dispatch({type: ERROR_FINDING_USER})
})

jQuery click event on radio button doesn't get fired

Seems like you're #inline_content isn't there! Remove the jQuery-Selector or check the parent elements, maybe you have a typo or forgot to add the id.

(made you a jsfiddle, works after adding a parent <div id="inline_content">: http://jsfiddle.net/J5HdN/)