Programs & Examples On #Function coverage

Pods stuck in Terminating status

The original question is "What could be the reason for this issue?" and the answer is discussed at https://github.com/kubernetes/kubernetes/issues/51835 & https://github.com/kubernetes/kubernetes/issues/65569 & see https://www.bountysource.com/issues/33241128-unable-to-remove-a-stopped-container-device-or-resource-busy

Its caused by docker mount leaking into some other namespace.

You can logon to pod host to investigate.

minikube ssh
docker container ps | grep <id>
docker container stop <id> 

Check whether a path is valid in Python without creating a file at the path's target

if os.path.exists(filePath):
    #the file is there
elif os.access(os.path.dirname(filePath), os.W_OK):
    #the file does not exists but write privileges are given
else:
    #can not write there

Note that path.exists can fail for more reasons than just the file is not there so you might have to do finer tests like testing if the containing directory exists and so on.


After my discussion with the OP it turned out, that the main problem seems to be, that the file name might contain characters that are not allowed by the filesystem. Of course they need to be removed but the OP wants to maintain as much human readablitiy as the filesystem allows.

Sadly I do not know of any good solution for this. However Cecil Curry's answer takes a closer look at detecting the problem.

Is there any sizeof-like method in Java?

The Instrumentation class has a getObjectSize() method however, you shouldn't need to use it at runtime. The easiest way to examine memory usage is to use a profiler which is designed to help you track memory usage.

TypeError: object of type 'int' has no len() error assistance needed

Abstract:

The reason why you are getting this error message is because you are trying to call a method on an int type of a variable. This would work if would have called len() function on a list type of a variable. Let's examin the two cases:

Fail:

num = 10

print(len(num))

The above will produce an error similar to yours due to calling len() function on an int type of a variable;

Success:

data = [0, 4, 8, 9, 12]

print(len(data))

The above will work since you are calling a function on a list type of a variable;

Getting an attribute value in xml element

Below is the code to do it in vtd-xml. It basically queries the XML with the XPath of "/xml/item/@name."

import com.ximpleware.*;

public class getAttrs{

   public static void main(String[] s) throws VTDException{
         VTDGen vg = new VTDGen();
         if (!vg.parseFile("input.xml",false)) // turn off namespace
              return;
         VTDNav vn = vg.getNav();
         AutoPilot ap =  new AutoPilot(vn);
         ap.selectXPath("/xml/item/@name");
         int i=0;
         while( (i=ap.evalXPath())!=-1){
              System.out.println(" item name is ===>"+vn.toString(i+1)); 
         }
   }
}

Math functions in AngularJS bindings

While the accepted answer is right that you can inject Math to use it in angular, for this particular problem, the more conventional/angular way is the number filter:

<p>The percentage is {{(100*count/total)| number:0}}%</p>

You can read more about the number filter here: http://docs.angularjs.org/api/ng/filter/number

How to change PHP version used by composer

I found out that composer runs with the php-version /usr/bin/env finds first in $PATH, which is 7.1.33 in my case on MacOs. So shifting mamp's php to the beginning helped me here.

PHPVER=$(/usr/libexec/PlistBuddy -c "print phpVersion" ~/Library/Preferences/de.appsolute.mamppro.plist)

export PATH=/Applications/MAMP/bin/php/php${PHPVER}/bin:$PATH

"static const" vs "#define" vs "enum"

The difference between static const and #define is that the former uses the memory and the later does not use the memory for storage. Secondly, you cannot pass the address of an #define whereas you can pass the address of a static const. Actually it is depending on what circumstance we are under, we need to select one among these two. Both are at their best under different circumstances. Please don't assume that one is better than the other... :-)

If that would have been the case, Dennis Ritchie would have kept the best one alone... hahaha... :-)

How to reset or change the passphrase for a GitHub SSH key?

If you had generate a SSH-key with passphrase and then you forget your passphrase for this SSH-key,there's no way to recover it, You'll need to generate a brand new SSH keypair or switch to HTTPS cloning so you can use your GitHub password instead.

BUT,there are exceptions

If you configured your SSH passphrase with the OS X Keychain, you may be able to recover it.

  1. In Finder, search for the Keychain Access app.
  2. In Keychain Access, search for SSH.
  3. Double click on the entry for your SSH key to open a new dialog box.
  4. Keychain access dialogIn the lower-left corner, select Show password.
  5. You'll be prompted for your administrative password. Type it into the "Keychain Access" dialog box.
  6. Your password will be revealed.

Refer to Github help - How do I recover my SSH key passphrase?

Difference between os.getenv and os.environ.get

See this related thread. Basically, os.environ is found on import, and os.getenv is a wrapper to os.environ.get, at least in CPython.

EDIT: To respond to a comment, in CPython, os.getenv is basically a shortcut to os.environ.get ; since os.environ is loaded at import of os, and only then, the same holds for os.getenv.

Border length smaller than div width?

I have case to have some bottom border between pictures in div container and the best one line code was - border-bottom-style: inset;

How to convert string to Title Case in Python?

def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d

'IF' in 'SELECT' statement - choose output value based on column values

Use a case statement:

select id,
    case report.type
        when 'P' then amount
        when 'N' then -amount
    end as amount
from
    `report`

Convert string to JSON Object

only with js

   JSON.parse(jsonObj);

reference

Radio button checked event handling

$("#expires1").click(function(){
     if (this.checked)
        alert("testing....");
});

How to read values from properties file?

If you need to manually read a properties file without using @Value.

Thanks for the well written page by Lokesh Gupta : Blog

enter image description here

package utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.io.File;


public class Utils {

    private static final Logger LOGGER = LoggerFactory.getLogger(Utils.class.getName());

    public static Properties fetchProperties(){
        Properties properties = new Properties();
        try {
            File file = ResourceUtils.getFile("classpath:application.properties");
            InputStream in = new FileInputStream(file);
            properties.load(in);
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }
        return properties;
    }
}

Detect change to ngModel on a select tag (Angular 2)

I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"

in my .html

<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">

then in my component.ts

reSearch(newValue: string) {
    //this.searchText would equal the new value
    //handle my filtering with the new value
}

How to Customize a Progress Bar In Android

Creating Custom ProgressBar like hotstar.

  1. Add Progress bar on layout file and set the indeterminateDrawable with drawable file.

activity_main.xml

<ProgressBar
    style="?android:attr/progressBarStyleLarge"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_centerHorizontal="true"
    android:id="@+id/player_progressbar"
    android:indeterminateDrawable="@drawable/custom_progress_bar"
    />
  1. Create new xml file in res\drawable

custom_progress_bar.xml

<?xml version="1.0" encoding="utf-8"?>
    <rotate  xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toDegrees="1080" >

    <shape
        android:innerRadius="35dp"
        android:shape="ring"
        android:thickness="3dp"
        android:useLevel="false" >
       <size
           android:height="80dp"
           android:width="80dp" />

       <gradient
            android:centerColor="#80b7b4b2"
            android:centerY="0.5"
            android:endColor="#f4eef0"
            android:startColor="#00938c87"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

'too many values to unpack', iterating over a dict. key=>string, value=>list

you are missing fields.iteritems() in your code.

You could also do it other way, where you get values using keys in the dictionary.

for key in fields:
    value = fields[key]

How to ssh connect through python Paramiko with ppk public key

For me I doing this:

import paramiko
hostname = 'my hostname or IP' 
myuser   = 'the user to ssh connect'
mySSHK   = '/path/to/sshkey.pub'
sshcon   = paramiko.SSHClient()  # will create the object
sshcon.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # no known_hosts error
sshcon.connect(hostname, username=myuser, key_filename=mySSHK) # no passwd needed

works for me pretty ok

How to add number of days to today's date?

You could extend the javascript Date object like this

Date.prototype.addDays = function(days) {
    this.setDate(this.getDate() + parseInt(days));
    return this;
};

and in your javascript code you could call

var currentDate = new Date();
// to add 4 days to current date
currentDate.addDays(4);

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

yii2 redirect in controller action does not work?

here is another way to do this

if(!Yii::$app->request->getIsPost()) {
    return Yii::$app->getResponse()->redirect(array('/user/index',302));
}

Importing a Maven project into Eclipse from Git

I have been testing this out for my project.

  1. Eclispe Indigo
  2. "Help > Install New Software" Enable/Install official Git plug-ins at "Eclipse Git Plugin .." and install the lot.
  3. Enable the Maven/EGit connector with these instructions How do you get git integration working with m2eclipse?
  4. Switch to the Git Repository perspective. Right click paste the project git url. The defaults should all work. You may want to change the install folder it guesses.
  5. Expand the cloned repository and right click on "Working Tree" and pick "Import Maven Projects...".
  6. Switch to the Java perspective. Right click on the project and choose "Team > Share Project". Select "Git" and be sure to tick the box "Use or create repository in parent folder of project".

Serializing/deserializing with memory stream

Use Method to Serialize and Deserialize Collection object from memory. This works on Collection Data Types. This Method will Serialize collection of any type to a byte stream. Create a Seperate Class SerilizeDeserialize and add following two methods:

public class SerilizeDeserialize
{

    // Serialize collection of any type to a byte stream

    public static byte[] Serialize<T>(T obj)
    {
        using (MemoryStream memStream = new MemoryStream())
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            binSerializer.Serialize(memStream, obj);
            return memStream.ToArray();
        }
    }

    // DSerialize collection of any type to a byte stream

    public static T Deserialize<T>(byte[] serializedObj)
    {
        T obj = default(T);
        using (MemoryStream memStream = new MemoryStream(serializedObj))
        {
            BinaryFormatter binSerializer = new BinaryFormatter();
            obj = (T)binSerializer.Deserialize(memStream);
        }
        return obj;
    }

}

How To use these method in your Class:

ArrayList arrayListMem = new ArrayList() { "One", "Two", "Three", "Four", "Five", "Six", "Seven" };
Console.WriteLine("Serializing to Memory : arrayListMem");
byte[] stream = SerilizeDeserialize.Serialize(arrayListMem);

ArrayList arrayListMemDes = new ArrayList();

arrayListMemDes = SerilizeDeserialize.Deserialize<ArrayList>(stream);

Console.WriteLine("DSerializing From Memory : arrayListMemDes");
foreach (var item in arrayListMemDes)
{
    Console.WriteLine(item);
}

Can you break from a Groovy "each" closure?

I agree with other answers not to use an exception to break an each. I also do not prefer to create an extra closure eachWithBreak, instead of this I prefer a modern approach: let's use the each to iterate over the collection, as requested, but refine the collection to contain only those elements to be iterated, for example with findAll:

collection.findAll { !endCondition }.each { doSomething() }

For example, if we what to break when the counter == 3 we can write this code (already suggested):

(0..5)
    .findAll { it < 3  }
    .each { println it }

This will output

0
1
2

So far so good, but you will notice a small discrepancy though. Our end condition, negation of counter == 3 is not quite correct because !(counter==3) is not equivalent with it < 3. This is necessary to make the code work since findAll does not actually break the loop but continues until the end.

To emulate a real situation, let's say we have this code:

for (n in 0..5) {
    if (n == 3)
        break
    println n
}

but we want to use each, so let's rewrite it using a function to simulate a break condition:

def breakWhen(nr) { nr == 3 }
(0..5)
    .findAll { !breakWhen(it) }
    .each { println it }

with the output:

0
1
2
4
5

now you see the problem with findAll. This does not stop, but ignores that element where the condition is not met.

To solve this issues, we need an extra variable to remember when the breaking condition become true. After this moment, findAll must ignore all remaining elements.

This is how it should look like:

def breakWhen(nr) { nr == 3 }
def loop = true
(0..5)
    .findAll {
        if (breakWhen(it))
            loop = false
        !breakWhen(it) && loop
    } .each {
        println it
    }

with the output:

0
1
2

That's what we want!

How can I convert a string to an int in Python?

def addition(a, b): return a + b

def subtraction(a, b): return a - b

def multiplication(a, b): return a * b

def division(a, b): return a / b

keepProgramRunning = True

print "Welcome to the Calculator!"

while keepProgramRunning:
print "Please choose what you'd like to do:"

print "0: Addition"
print "1: Subtraction"
print "2: Multiplication"
print "3: Division"
print "4: Quit Application"



#Capture the menu choice.
choice = raw_input()    

if choice == "0":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(addition(numberA, numberB)) + "\n"
elif choice == "1":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(subtraction(numberA, numberB)) + "\n"
elif choice == "2":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(multiplication(numberA, numberB)) + "\n"
elif choice == "3":
    numberA = input("Enter your first number: ")
    numberB = input("Enter your second number: ")
    print "Your result is: " + str(division(numberA, numberB)) + "\n"
elif choice == "4":
    print "Bye!"
    keepProgramRunning = False
else:
    print "Please choose a valid option."
    print "\n"

Android Studio: Gradle: error: cannot find symbol variable

If you are using a String build config field in your project, this might be the case:

buildConfigField "String", "source", "play"

If you declare your String like above it will cause the error to happen. The fix is to change it to:

buildConfigField "String", "source", "\"play\""

CSS: Center block, but align contents to the left

Normally you should use margin: 0 auto on the div as mentioned in the other answers, but you'll have to specify a width for the div. If you don't want to specify a width you could either (this is depending on what you're trying to do) use margins, something like margin: 0 200px; , this should make your content seems as if it's centered, you could also see the answer of Leyu to my question

Change value of input and submit form in JavaScript

No. When your input type is submit, you should have an onsubmit event declared in the markup and then do the changes you want. Meaning, have an onsubmit defined in your form tag.

Otherwise change the input type to a button and then define an onclick event for that button.

Regex to accept alphanumeric and some special character in Javascript?

I forgot to mention. This should also accept whitespace.

You could use:

/^[-@.\/#&+\w\s]*$/

Note how this makes use of the character classes \w and \s.

EDIT:- Added \ to escape /

How to retrieve the LoaderException property?

try
{
  // load the assembly or type
}
catch (Exception ex)
{
  if (ex is System.Reflection.ReflectionTypeLoadException)
  {
    var typeLoadException = ex as ReflectionTypeLoadException;
    var loaderExceptions  = typeLoadException.LoaderExceptions;
  }
}

Using `window.location.hash.includes` throws “Object doesn't support property or method 'includes'” in IE11

Adding import 'core-js/es7/array'; to my polyfill.ts fixed the issue for me.

Jquery, set value of td in a table?

Try the code below :

$('#detailInfo').html('your value')

XSL xsl:template match="/"

It's worth noting, since it's confusing for people new to XML, that the root (or document node) of an XML document is not the top-level element. It's the parent of the top-level element. This is confusing because it doesn't seem like the top-level element can have a parent. Isn't it the top level?

But look at this, a well-formed XML document:

<?xml-stylesheet href="my_transform.xsl" type="text/xsl"?>
<!-- Comments and processing instructions are XML nodes too, remember. -->
<TopLevelElement/>

The root of this document has three children: a processing instruction, a comment, and an element.

So, for example, if you wanted to write a transform that got rid of that comment, but left in any comments appearing anywhere else in the document, you'd add this to the identity transform:

<xsl:template match="/comment()"/>

Even simpler (and more commonly useful), here's an XPath pattern that matches the document's top-level element irrespective of its name: /*.

How can I use delay() with show() and hide() in Jquery

from jquery api

Added to jQuery in version 1.4, the .delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

http://api.jquery.com/delay/

Issue with background color and Google Chrome

Everybody has said your code is fine, and you know it works on other browsers without problems. So it's time to drop the science and just try stuff :)

Try putting the background color IN the body tag itself instead of/as-well-as in the CSS. Maybe insist again (redudantly) in Javascript. At some point, Chrome will have to place the background as you want it every time. Might be a timing-interpreting issue...

[Should any of this work, of course, you can toggle it on the server-side so the funny code only shows up in Chrome. And in a few months, when Chrome has changed and the problem disappears... well, worry about that later.]

How to generate and manually insert a uniqueidentifier in sql server?

ApplicationId must be of type UniqueIdentifier. Your code works fine if you do:

DECLARE @TTEST TABLE
(
  TEST UNIQUEIDENTIFIER
)

DECLARE @UNIQUEX UNIQUEIDENTIFIER
SET @UNIQUEX = NEWID();

INSERT INTO @TTEST
(TEST)
VALUES
(@UNIQUEX);

SELECT * FROM @TTEST

Therefore I would say it is safe to assume that ApplicationId is not the correct data type.

Add all files to a commit except a single file?

Now git supports exclude certain paths and files by pathspec magic :(exclude) and its short form :!. So you can easily achieve it as the following command.

git add --all -- :!main/dontcheckmein.txt
git add -- . :!main/dontcheckmein.txt

Actually you can specify more:

git add --all -- :!path/to/file1 :!path/to/file2 :!path/to/folder1/*
git add -- . :!path/to/file1 :!path/to/file2 :!path/to/folder1/*

For Mac and Linux, surround each file/folder path with quotes

git add --all -- ':!path/to/file1' ':!path/to/file2' ':!path/to/folder1/*'

Why "net use * /delete" does not work but waits for confirmation in my PowerShell script?

With PowerShell 5.1 in Windows 10 you can use:

Get-SmbMapping | Remove-SmbMapping -Confirm:$false

Simple PHP calculator

Personally I would do a switch instead of all this if, else if, else

$first = $_POST['first'] + 0;//a small "hack" to make sure its an int but allow negs!!
$second= $_POST['second'] + 0;
$operator = $_POST["group1"];
switch($operator)
{
    case "add"
    echo "Answer is: " .$first + $second;
    break; 
    case "subtract"
    echo "Answer is: " .$first - $second;
    break;
    case "times"
    echo "Answer is: " .$first * $second;
    break; 
    case "divide"
    echo "Answer is: " .$first / $second;
    break;
}

How to change int into int64?

i := 23
i64 := int64(i)
fmt.Printf("%T %T", i, i64) // to print the data types of i and i64

JavaScript and Threads

Different way to do multi-threading and Asynchronous in JavaScript

Before HTML5 JavaScript only allowed the execution of one thread per page.

There was some hacky way to simulate an asynchronous execution with Yield, setTimeout(), setInterval(), XMLHttpRequest or event handlers (see the end of this post for an example with yield and setTimeout()).

But with HTML5 we can now use Worker Threads to parallelize the execution of functions. Here is an example of use.


Real multi-threading

Multi-threading: JavaScript Worker Threads

HTML5 introduced Web Worker Threads (see: browsers compatibilities)
Note: IE9 and earlier versions do not support it.

These worker threads are JavaScript threads that run in background without affecting the performance of the page. For more information about Web Worker read the documentation or this tutorial.

Here is a simple example with 3 Web Worker threads that count to MAX_VALUE and show the current computed value in our page:

_x000D_
_x000D_
//As a worker normally take another JavaScript file to execute we convert the function in an URL: http://stackoverflow.com/a/16799132/2576706_x000D_
function getScriptPath(foo){ return window.URL.createObjectURL(new Blob([foo.toString().match(/^\s*function\s*\(\s*\)\s*\{(([\s\S](?!\}$))*[\s\S])/)[1]],{type:'text/javascript'})); }_x000D_
_x000D_
var MAX_VALUE = 10000;_x000D_
_x000D_
/*_x000D_
 * Here are the workers_x000D_
 */_x000D_
//Worker 1_x000D_
var worker1 = new Worker(getScriptPath(function(){_x000D_
    self.addEventListener('message', function(e) {_x000D_
        var value = 0;_x000D_
        while(value <= e.data){_x000D_
            self.postMessage(value);_x000D_
            value++;_x000D_
        }_x000D_
    }, false);_x000D_
}));_x000D_
//We add a listener to the worker to get the response and show it in the page_x000D_
worker1.addEventListener('message', function(e) {_x000D_
  document.getElementById("result1").innerHTML = e.data;_x000D_
}, false);_x000D_
_x000D_
_x000D_
//Worker 2_x000D_
var worker2 = new Worker(getScriptPath(function(){_x000D_
    self.addEventListener('message', function(e) {_x000D_
        var value = 0;_x000D_
        while(value <= e.data){_x000D_
            self.postMessage(value);_x000D_
            value++;_x000D_
        }_x000D_
    }, false);_x000D_
}));_x000D_
worker2.addEventListener('message', function(e) {_x000D_
  document.getElementById("result2").innerHTML = e.data;_x000D_
}, false);_x000D_
_x000D_
_x000D_
//Worker 3_x000D_
var worker3 = new Worker(getScriptPath(function(){_x000D_
    self.addEventListener('message', function(e) {_x000D_
        var value = 0;_x000D_
        while(value <= e.data){_x000D_
            self.postMessage(value);_x000D_
            value++;_x000D_
        }_x000D_
    }, false);_x000D_
}));_x000D_
worker3.addEventListener('message', function(e) {_x000D_
    document.getElementById("result3").innerHTML = e.data;_x000D_
}, false);_x000D_
_x000D_
_x000D_
// Start and send data to our worker._x000D_
worker1.postMessage(MAX_VALUE); _x000D_
worker2.postMessage(MAX_VALUE); _x000D_
worker3.postMessage(MAX_VALUE);
_x000D_
<div id="result1"></div>_x000D_
<div id="result2"></div>_x000D_
<div id="result3"></div>
_x000D_
_x000D_
_x000D_

We can see that the three threads are executed in concurrency and print their current value in the page. They don't freeze the page because they are executed in the background with separated threads.


Multi-threading: with multiple iframes

Another way to achieve this is to use multiple iframes, each one will execute a thread. We can give the iframe some parameters by the URL and the iframe can communicate with his parent in order to get the result and print it back (the iframe must be in the same domain).

This example doesn't work in all browsers! iframes usually run in the same thread/process as the main page (but Firefox and Chromium seem to handle it differently).

Since the code snippet does not support multiple HTML files, I will just provide the different codes here:

index.html:

//The 3 iframes containing the code (take the thread id in param)
<iframe id="threadFrame1" src="thread.html?id=1"></iframe>
<iframe id="threadFrame2" src="thread.html?id=2"></iframe>
<iframe id="threadFrame3" src="thread.html?id=3"></iframe>

//Divs that shows the result
<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div>


<script>
    //This function is called by each iframe
    function threadResult(threadId, result) {
        document.getElementById("result" + threadId).innerHTML = result;
    }
</script>

thread.html:

//Get the parameters in the URL: http://stackoverflow.com/a/1099670/2576706
function getQueryParams(paramName) {
    var qs = document.location.search.split('+').join(' ');
    var params = {}, tokens, re = /[?&]?([^=]+)=([^&]*)/g;
    while (tokens = re.exec(qs)) {
        params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
    }
    return params[paramName];
}

//The thread code (get the id from the URL, we can pass other parameters as needed)
var MAX_VALUE = 100000;
(function thread() {
    var threadId = getQueryParams('id');
    for(var i=0; i<MAX_VALUE; i++){
        parent.threadResult(threadId, i);
    }
})();

Simulate multi-threading

Single-thread: emulate JavaScript concurrency with setTimeout()

The 'naive' way would be to execute the function setTimeout() one after the other like this:

setTimeout(function(){ /* Some tasks */ }, 0);
setTimeout(function(){ /* Some tasks */ }, 0);
[...]

But this method does not work because each task will be executed one after the other.

We can simulate asynchronous execution by calling the function recursively like this:

_x000D_
_x000D_
var MAX_VALUE = 10000;_x000D_
_x000D_
function thread1(value, maxValue){_x000D_
    var me = this;_x000D_
    document.getElementById("result1").innerHTML = value;_x000D_
    value++;_x000D_
  _x000D_
    //Continue execution_x000D_
    if(value<=maxValue)_x000D_
        setTimeout(function () { me.thread1(value, maxValue); }, 0);_x000D_
}_x000D_
_x000D_
function thread2(value, maxValue){_x000D_
    var me = this;_x000D_
    document.getElementById("result2").innerHTML = value;_x000D_
    value++;_x000D_
 _x000D_
    if(value<=maxValue)_x000D_
        setTimeout(function () { me.thread2(value, maxValue); }, 0);_x000D_
}_x000D_
_x000D_
function thread3(value, maxValue){_x000D_
    var me = this;_x000D_
    document.getElementById("result3").innerHTML = value;_x000D_
    value++;_x000D_
 _x000D_
    if(value<=maxValue)_x000D_
        setTimeout(function () { me.thread3(value, maxValue); }, 0);_x000D_
}_x000D_
_x000D_
thread1(0, MAX_VALUE);_x000D_
thread2(0, MAX_VALUE);_x000D_
thread3(0, MAX_VALUE);
_x000D_
<div id="result1"></div>_x000D_
<div id="result2"></div>_x000D_
<div id="result3"></div>
_x000D_
_x000D_
_x000D_

As you can see this second method is very slow and freezes the browser because it uses the main thread to execute the functions.


Single-thread: emulate JavaScript concurrency with yield

Yield is a new feature in ECMAScript 6, it only works on the oldest version of Firefox and Chrome (in Chrome you need to enable Experimental JavaScript appearing in chrome://flags/#enable-javascript-harmony).

The yield keyword causes generator function execution to pause and the value of the expression following the yield keyword is returned to the generator's caller. It can be thought of as a generator-based version of the return keyword.

A generator allows you to suspend execution of a function and resume it later. A generator can be used to schedule your functions with a technique called trampolining.

Here is the example:

_x000D_
_x000D_
var MAX_VALUE = 10000;_x000D_
_x000D_
Scheduler = {_x000D_
 _tasks: [],_x000D_
 add: function(func){_x000D_
  this._tasks.push(func);_x000D_
 }, _x000D_
 start: function(){_x000D_
  var tasks = this._tasks;_x000D_
  var length = tasks.length;_x000D_
  while(length>0){_x000D_
   for(var i=0; i<length; i++){_x000D_
    var res = tasks[i].next();_x000D_
    if(res.done){_x000D_
     tasks.splice(i, 1);_x000D_
     length--;_x000D_
     i--;_x000D_
    }_x000D_
   }_x000D_
  }_x000D_
 } _x000D_
}_x000D_
_x000D_
_x000D_
function* updateUI(threadID, maxValue) {_x000D_
  var value = 0;_x000D_
  while(value<=maxValue){_x000D_
 yield document.getElementById("result" + threadID).innerHTML = value;_x000D_
 value++;_x000D_
  }_x000D_
}_x000D_
_x000D_
Scheduler.add(updateUI(1, MAX_VALUE));_x000D_
Scheduler.add(updateUI(2, MAX_VALUE));_x000D_
Scheduler.add(updateUI(3, MAX_VALUE));_x000D_
_x000D_
Scheduler.start()
_x000D_
<div id="result1"></div>_x000D_
<div id="result2"></div>_x000D_
<div id="result3"></div>
_x000D_
_x000D_
_x000D_

How to copy files across computers using SSH and MAC OS X Terminal

First zip or gzip the folders:
Use the following command:

zip -r NameYouWantForZipFile.zip foldertozip/

or

tar -pvczf BackUpDirectory.tar.gz /path/to/directory

for gzip compression use SCP:

scp [email protected]:~/serverpath/public_html ~/Desktop

Python: CSV write by column rather than row

wr.writerow(item)  #column by column
wr.writerows(item) #row by row

This is quite simple if your goal is just to write the output column by column.

If your item is a list:

yourList = []

with open('yourNewFileName.csv', 'w', ) as myfile:
    wr = csv.writer(myfile, quoting=csv.QUOTE_ALL)
    for word in yourList:
        wr.writerow([word])

Search for exact match of string in excel row using VBA Macro

Never mind, I found the answer.

This will do the trick.

Dim colIndex As Long    
colIndex = Application.Match(colName, Range(Cells(rowIndex, 1), Cells(rowIndex, 100)), 0)

Can you do a For Each Row loop using MySQL?

In the link you provided, thats not a loop in sql...

thats a loop in programming language

they are first getting list of all distinct districts, and then for each district executing query again.

Arithmetic operation resulted in an overflow. (Adding integers)

int.MaxValue = 2147483647
2055786000 + 93552000 = 2149338000 > int.MaxValue

So you cannot store this number into an integer. You could use Int64 type which has a maximum value of 9,223,372,036,854,775,807.

How can I parse JSON with C#?

         string json = @"{
            'Name': 'Wide Web',
            'Url': 'www.wideweb.com.br'}";

        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        dynamic j = jsonSerializer.Deserialize<dynamic>(json);
        string name = j["Name"].ToString();
        string url = j["Url"].ToString();

What is the difference between a database and a data warehouse?

See in simple words : Dataware --> Huge data using for Analytical/storage/ copy and Analysis . Database --> CRUD operation with Frequently used data .

Dataware house is Kind of storage which u are not using on daily basis & Database is something which your dealing frequently .

Eg. If we are asking statement of bank then it gives us for last 3/4/6/more months bcoz it is in database. If you want more than that it stores on Dataware house.

How to create a zip archive with PowerShell?

If someone needs to zip a single file (and not a folder): http://blogs.msdn.com/b/jerrydixon/archive/2014/08/08/zipping-a-single-file-with-powershell.aspx

[CmdletBinding()]
Param(
     [Parameter(Mandatory=$True)]
     [ValidateScript({Test-Path -Path $_ -PathType Leaf})]
     [string]$sourceFile,

     [Parameter(Mandatory=$True)]
     [ValidateScript({-not(Test-Path -Path $_ -PathType Leaf)})]
     [string]$destinationFile
) 

<#
     .SYNOPSIS
     Creates a ZIP file that contains the specified innput file.

     .EXAMPLE
     FileZipper -sourceFile c:\test\inputfile.txt 
                -destinationFile c:\test\outputFile.zip
#> 

function New-Zip
{
     param([string]$zipfilename)
     set-content $zipfilename 
          ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
     (dir $zipfilename).IsReadOnly = $false
}

function Add-Zip
{
     param([string]$zipfilename) 

     if(-not (test-path($zipfilename)))
     {
          set-content $zipfilename 
               ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
          (dir $zipfilename).IsReadOnly = $false    

     }

     $shellApplication = new-object -com shell.application
     $zipPackage = $shellApplication.NameSpace($zipfilename)


     foreach($file in $input) 
     { 
          $zipPackage.CopyHere($file.FullName)
          Start-sleep -milliseconds 500
     }
}

dir $sourceFile | Add-Zip $destinationFile

Visual Studio Code pylint: Unable to import 'protorpc'

Spent hours trying to fix the error for importing local modules. Code execution was fine but pylint showed:

    Unable to import '<module>'

Finally figured:

  1. First of all, select the correct python path. (In the case of a virtual environment, it will be venv/bin/python). You can do this by hitting

  2. Make sure that your pylint path is the same as the python path you chose in step 1. (You can open VS Code from within the activated venv from terminal so it automatically performs these two steps)

  3. The most important step: Add an empty __init__.py file in the folder that contains your module file. Although python3 does not require this file for importing modules, I think pylint still requires it for linting.

Restart VS Code, the errors should be gone!

Best way to script remote SSH commands in Batch (Windows)

As an alternative option you could install OpenSSH http://www.mls-software.com/opensshd.html and then simply ssh user@host -pw password -m command_run

Edit: After a response from user2687375 when installing, select client only. Once this is done you should be able to initiate SSH from command.

Then you can create an ssh batch script such as

ECHO OFF
CLS
:MENU
ECHO.
ECHO ........................
ECHO SSH servers
ECHO ........................
ECHO.
ECHO 1 - Web Server 1
ECHO 2 - Web Server 2
ECHO E - EXIT
ECHO.

SET /P M=Type 1 - 2 then press ENTER:
IF %M%==1 GOTO WEB1
IF %M%==2 GOTO WEB2
IF %M%==E GOTO EOF

REM ------------------------------
REM SSH Server details
REM ------------------------------

:WEB1
CLS
call ssh [email protected]
cmd /k

:WEB2
CLS
call ssh [email protected]
cmd /k

How to strip comma in Python string

This will strip all commas from the text and left justify it.

for row in inputfile:
    place = row['your_row_number_here'].strip(', ')

? ????? ??????

XPath to get all child nodes (elements, comments, and text) without parent

From the documentation of XPath ( http://www.w3.org/TR/xpath/#location-paths ):

child::* selects all element children of the context node

child::text() selects all text node children of the context node

child::node() selects all the children of the context node, whatever their node type

So I guess your answer is:

$doc/PRESENTEDIN/X/child::node()

And if you want a flatten array of all nested nodes:

$doc/PRESENTEDIN/X/descendant::node()

Replace a character at a specific index in a string?

As previously answered here, String instances are immutable. StringBuffer and StringBuilder are mutable and suitable for such a purpose whether you need to be thread safe or not.

There is however a way to modify a String but I would never recommend it because it is unsafe, unreliable and it can can be considered as cheating : you can use reflection to modify the inner char array the String object contains. Reflection allows you to access fields and methods that are normally hidden in the current scope (private methods or fields from another class...).

public static void main(String[] args) {
    String text = "This is a test";
    try {
        //String.value is the array of char (char[])
        //that contains the text of the String
        Field valueField = String.class.getDeclaredField("value");
        //String.value is a private variable so it must be set as accessible 
        //to read and/or to modify its value
        valueField.setAccessible(true);
        //now we get the array the String instance is actually using
        char[] value = (char[])valueField.get(text);
        //The 13rd character is the "s" of the word "Test"
        value[12]='x';
        //We display the string which should be "This is a text"
        System.out.println(text);
    } catch (NoSuchFieldException | SecurityException e) {
        e.printStackTrace();
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

How to change an Eclipse default project into a Java project

Using project Project facets we can configure characteristics and requirements for projects.

To find Project facets on eclipse:

  • Step 1: Right click on the project and choose properties from the menu.
  • Step 2:Select project facets option. Click on Convert to faceted form... enter image description here

  • Step 3: We can find all available facets you can select and change their settings. enter image description here

Set specific precision of a BigDecimal

You can use setScale() e.g.

double d = ...
BigDecimal db = new BigDecimal(d).setScale(12, BigDecimal.ROUND_HALF_UP);

Npm Error - No matching version found for

Probably not the case of everybody but I had the same problem. I was using the last, in my case, the error was because I was using jfrog manage from the company where I am working.

 npm config list

The result was

; cli configs
metrics-registry = "https://COMPANYNAME.jfrog.io/COMPANYNAM/api/npm/npm/"
scope = ""
user-agent = "npm/6.3.0 node/v8.11.2 win32 x64"

; userconfig C:\Users\USER\.npmrc
always-auth = true
email = "XXXXXXXXX"
registry = "https://COMPANYNAME.jfrog.io/COMPANYNAME/api/npm/npm/"

; builtin config undefined
prefix = "C:\\Users\\XXXXX\\AppData\\Roaming\\npm"

; node bin location = C:\Program Files\nodejs\node.exe
; cwd = C:\WINDOWS\system32
; HOME = C:\Users\XXXXXX
; "npm config ls -l" to show all defaults.

I solve the problem by using the global metrics.

What is the difference between SQL Server 2012 Express versions?

This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.

Summary compiled from the above document:

    * = contains the feature
                                           SQLEXPR    SQLEXPRWT   SQLEXPRADV
 ----------------------------------------------------------------------------
    > SQL Server Core                         *           *           *
    > SQL Server Management Studio            -           *           *
    > Distributed Replay – Admin Tool         -           *           *
    > LocalDB                                 -           *           *
    > SQL Server Data Tools (SSDT)            -           -           *
    > Full-text and semantic search           -           -           *
    > Specification of language in query      -           -           *
    > some of Reporting services features     -           -           *

How to scroll to the bottom of a RecyclerView? scrollToPosition doesn't work

Solution for Kotlin:

apply below code after setting "recyclerView.adapter" or after "recyclerView.adapter.notifyDataSetChanged()"

recyclerView.scrollToPosition(recyclerView.adapter.itemCount - 1)

What does auto do in margin:0 auto?

When you have specified a width on the object that you have applied margin: 0 auto to, the object will sit centrally within it's parent container.

Specifying auto as the second parameter basically tells the browser to automatically determine the left and right margins itself, which it does by setting them equally. It guarantees that the left and right margins will be set to the same size. The first parameter 0 indicates that the top and bottom margins will both be set to 0.

margin-top:0;
margin-bottom:0;
margin-left:auto;
margin-right:auto;

Therefore, to give you an example, if the parent is 100px and the child is 50px, then the auto property will determine that there's 50px of free space to share between margin-left and margin-right:

var freeSpace = 100 - 50;
var equalShare = freeSpace / 2;

Which would give:

margin-left:25;
margin-right:25;

Have a look at this jsFiddle. You do not have to specify the parent width, only the width of the child object.

Run a controller function whenever a view is opened/shown

This is probably what you were looking for:

Ionic caches your views and thus your controllers by default (max of 10) http://ionicframework.com/docs/api/directive/ionView/

There are events you can hook onto to let your controller do certain things based on those ionic events. see here for an example: http://ionicframework.com/blog/navigating-the-changes/

Remote Procedure call failed with sql server 2008 R2

I got the samilar issue, while both SQLServer and SQLServerAgent services are running. The error is fixed by a restart of services.

Server Manager > Service > 
    SQL Server > Stop
    SQL Server > Start
    SQL Server Agent > Start

Firebase onMessageReceived not called when app in background

By default the Launcher Activity in you app will be launched when your app is in background and you click the notification, if you have any data part with your notifcation you can handle it in the same activity as follows,

if(getIntent().getExtras()! = null){
  //do your stuff
}else{
  //do that you normally do
}

NSDictionary - Need to check whether dictionary contains key-value pair or not

Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

if ([xyz objectForKey:@"b"]) {
    NSLog(@"There's an object set for key @\"b\"!");
} else {
    NSLog(@"No object set for key @\"b\"");
}

Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).

Eclipse IDE: How to zoom in on text?

go to Eclipse > Prefences > General > Appearance > Color and Fonts > Basic > Text Font

Font problem will resolved I guess.Dont need a any plugin for this.

Change :hover CSS properties with JavaScript

This is not actually adding the CSS to the cell, but gives the same effect. While providing the same result as others above, this version is a little more intuitive to me, but I'm a novice, so take it for what it's worth:

$(".hoverCell").bind('mouseover', function() {
    var old_color = $(this).css("background-color");
    $(this)[0].style.backgroundColor = '#ffff00';

    $(".hoverCell").bind('mouseout', function () {
        $(this)[0].style.backgroundColor = old_color;
    });
});

This requires setting the Class for each of the cells you want to highlight to "hoverCell".

Delete dynamically-generated table row using jQuery

You need to use event delegation because those buttons don't exist on load:

http://jsfiddle.net/isherwood/Z7fG7/1/

 $(document).on('click', 'button.removebutton', function () { // <-- changes
     alert("aa");
     $(this).closest('tr').remove();
     return false;
 });

How to install Visual C++ Build tools?

You can check Announcing the official release of the Visual C++ Build Tools 2015 and from this blog, we can know that the Build Tools are the same C++ tools that you get with Visual Studio 2015 but they come in a scriptable standalone installer that only lays down the tools you need to build C++ projects. The Build Tools give you a way to install the tools you need on your build machines without the IDE you don’t need.

Because these components are the same as the ones installed by the Visual Studio 2015 Update 2 setup, you cannot install the Visual C++ Build Tools on a machine that already has Visual Studio 2015 installed. Therefore, it asks you to uninstall your existing VS 2015 when you tried to install the Visual C++ build tools using the standalone installer. Since you already have the VS 2015, you can go to Control Panel—Programs and Features and right click the VS 2015 item and Change-Modify, then check the option of those components that relates to the Visual C++ Build Tools, like Visual C++, Windows SDK… then install them. After the installation is successful, you can build the C++ projects.

Today's Date in Perl in MM/DD/YYYY format

Formating numbers with leading zero is done easily with "sprintf", a built-in function in perl (documentation with: perldoc perlfunc)

use strict;
use warnings;
use Date::Calc qw();
my ($y, $m, $d) = Date::Calc::Today();
my $ddmmyyyy = sprintf '%02d.%02d.%d', $d, $m, $y;
print $ddmmyyyy . "\n";

This gives you:

14.05.2014

Capture screenshot of active window?

ScreenCapture sc = new ScreenCapture();
// capture entire screen, and save it to a file
Image img = sc.CaptureScreen();
// display image in a Picture control named imageDisplay
this.imageDisplay.Image = img;
// capture this window, and save it
sc.CaptureWindowToFile(this.Handle,"C:\\temp2.gif",ImageFormat.Gif);

http://www.developerfusion.com/code/4630/capture-a-screen-shot/

How to restart Jenkins manually?

Windows

Run services.msc and restart:

Enter image description here

How can I capitalize the first letter of each word in a string using JavaScript?

function titleCase(str) {

    var myString = str.toLowerCase().split(' ');
    for (var i = 0; i < myString.length; i++) {
        var subString = myString[i].split('');
        for (var j = 0; j < subString.length; j++) {
            subString[0] = subString[0].toUpperCase();
        }
        myString[i] = subString.join('');
    }

    return myString.join(' ');
}

How to read file with space separated values in pandas

add delim_whitespace=True argument, it's faster than regex.

Oracle SQL Developer: Unable to find a JVM

Version 1.5 is very, very old.

In the latest builds, we support 32 and 64 bit JDKs. In version 4.0, we find the JDK for you on Windows. If the software can't find it, it prompts for that path.

That path would look something like this C:\Java\jdk1.7.0_45

You can read more about this here.

How do I pipe a subprocess call to a text file?

If you want to write the output to a file you can use the stdout-argument of subprocess.call.

It takes None, subprocess.PIPE, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.

You need to open a file with something like open and pass the object or file descriptor integer to call:

f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml",  "/tmp/video_xml"], stdout=f)

I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.

As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT. Any of the above mentioned values works as well, you can redirect to different places.

XML Schema How to Restrict Attribute by Enumeration

The numerical value seems to be missing from your price definition. Try the following:

<xs:simpleType name="curr">
  <xs:restriction base="xs:string">
    <xs:enumeration value="pounds" />
    <xs:enumeration value="euros" />
    <xs:enumeration value="dollars" />
  </xs:restriction>
</xs:simpleType>



<xs:element name="price">
        <xs:complexType>
            <xs:extension base="xs:decimal">
              <xs:attribute name="currency" type="curr"/>
            </xs:extension>
        </xs:complexType>
</xs:element>

jQuery selector for id starts with specific text

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

Change color of PNG image via CSS?

Think I have a solution for this that's a) exactly what you were looking for 5 years ago, and b) is a bit simpler than the other code options here.

With any white png (eg, white icon on transparent background), you can add an ::after selector to recolor.

.icon {
    background: url(img/icon.png); /* Your icon */
    position: relative; /* Allows an absolute positioned psuedo element */
}

.icon::after{
    position: absolute; /* Positions psuedo element relative to .icon */
    width: 100%; /* Same dimensions as .icon */
    height: 100%;
    content: ""; /* Allows psuedo element to show */
    background: #EC008C; /* The color you want the icon to change to */
    mix-blend-mode: multiply; /* Only apply color on top of white, use screen if icon is black */
}

See this codepen (applying the color swap on hover): http://codepen.io/chrscblls/pen/bwAXZO

Non-resolvable parent POM using Maven 3.0.3 and relativePath notation

Here is answer to your question.

By default maven looks in ../pom.xml for relativePath. Use empty <relativePath/> tag instead.

Adding and removing style attribute from div with jquery

If you are using jQuery, use css to add CSS

$("#voltaic_holder").css({'position': 'absolute',
    'top': '-75px'});

To remove CSS attributes

$("#voltaic_holder").css({'position': '',
    'top': ''});

Interview question: Check if one string is a rotation of other string

Take each character as an amplitude and perform a discrete Fourier transform on them. If they differ only by rotation, the frequency spectra will be the same to within rounding error. Of course this is inefficient unless the length is a power of 2 so you can do an FFT :-)

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

After facing a similar issue, below is what I did :

  • Created a class extending javax.ws.rs.core.Application and added a Cors Filter to it.

To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");.

Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*" instead of any specific URL to allow any URL.

public class RestApplication
    extends Application
{
    private Set<Object> singletons = new HashSet<Object>();

    public MessageApplication()
    {
        singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
        CorsFilter corsFilter = new CorsFilter();
        // To allow all origins for CORS add following, otherwise add only specific urls.
        // corsFilter.getAllowedOrigins().add("*");
        System.out.println("To only allow restrcited urls ");
        corsFilter.getAllowedOrigins().add("http://localhost:4200");
        singletons = new LinkedHashSet<Object>();
        singletons.add(corsFilter);
    }

    @Override
    public Set<Object> getSingletons()
    {
        return singletons;
    }
}
  • And here is my web.xml:
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>

    <!-- Auto scan rest service -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.app.RestApplication</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>

   <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.app.RestApplication</param-value>
    </init-param>

And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.

Using JQuery to check if no radio button in a group has been checked

if (!$("input[name='html_elements']:checked").val()) {
   alert('Nothing is checked!');
}
else {
  alert('One of the radio buttons is checked!');
}

What is the meaning of the word logits in TensorFlow?

Logits is an overloaded term which can mean many different things:


In Math, Logit is a function that maps probabilities ([0, 1]) to R ((-inf, inf))

enter image description here

Probability of 0.5 corresponds to a logit of 0. Negative logit correspond to probabilities less than 0.5, positive to > 0.5.

In ML, it can be

the vector of raw (non-normalized) predictions that a classification model generates, which is ordinarily then passed to a normalization function. If the model is solving a multi-class classification problem, logits typically become an input to the softmax function. The softmax function then generates a vector of (normalized) probabilities with one value for each possible class.

Logits also sometimes refer to the element-wise inverse of the sigmoid function.

Ruby on Rails generates model field:type - what are the options for field:type?

$ rails g model Item name:string description:text product:references

I too found the guides difficult to use. Easy to understand, but hard to find what I am looking for.

Also, I have temp projects that I run the rails generate commands on. Then once I get them working I run it on my real project.

Reference for the above code: http://guides.rubyonrails.org/getting_started.html#associating-models

Pass Arraylist as argument to function

The answer is already posted but note that this will pass the ArrayList by reference. So if you make any changes to the list in the function it will be affected to the original list also.

<access-modfier> <returnType> AnalyseArray(ArrayList<Integer> list)
{
//analyse the list
//return value
}

call it like this:

x=AnalyseArray(list);

or pass a copy of ArrayList:

x=AnalyseArray(list.clone());

An "and" operator for an "if" statement in Bash

Quote:

The "-a" operator also doesn't work:

if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]]

For a more elaborate explanation: [ and ] are not Bash reserved words. The if keyword introduces a conditional to be evaluated by a job (the conditional is true if the job's return value is 0 or false otherwise).

For trivial tests, there is the test program (man test).

As some find lines like if test -f filename; then foo bar; fi, etc. annoying, on most systems you find a program called [ which is in fact only a symlink to the test program. When test is called as [, you have to add ] as the last positional argument.

So if test -f filename is basically the same (in terms of processes spawned) as if [ -f filename ]. In both cases the test program will be started, and both processes should behave identically.

Here's your mistake: if [ $STATUS -ne 200 ] -a [[ "$STRING" != "$VALUE" ]] will parse to if + some job, the job being everything except the if itself. The job is only a simple command (Bash speak for something which results in a single process), which means the first word ([) is the command and the rest its positional arguments. There are remaining arguments after the first ].

Also not, [[ is indeed a Bash keyword, but in this case it's only parsed as a normal command argument, because it's not at the front of the command.

How to access random item in list?

Or simple extension class like this:

public static class CollectionExtension
{
    private static Random rng = new Random();

    public static T RandomElement<T>(this IList<T> list)
    {
        return list[rng.Next(list.Count)];
    }

    public static T RandomElement<T>(this T[] array)
    {
        return array[rng.Next(array.Length)];
    }
}

Then just call:

myList.RandomElement();

Works for arrays as well.

I would avoid calling OrderBy() as it can be expensive for larger collections. Use indexed collections like List<T> or arrays for this purpose.

Function return value in PowerShell

Luke's description of the function results in these scenarios seems to be right on. I only wish to understand the root cause and the PowerShell product team would do something about the behavior. It seems to be quite common and has cost me too much debugging time.

To get around this issue I've been using global variables rather than returning and using the value from the function call.

Here's another question on the use of global variables: Setting a global PowerShell variable from a function where the global variable name is a variable passed to the function

What is context in _.each(list, iterator, [context])?

The context parameter just sets the value of this in the iterator function.

var someOtherArray = ["name","patrick","d","w"];

_.each([1, 2, 3], function(num) { 
    // In here, "this" refers to the same Array as "someOtherArray"

    alert( this[num] ); // num is the value from the array being iterated
                        //    so this[num] gets the item at the "num" index of
                        //    someOtherArray.
}, someOtherArray);

Working Example: http://jsfiddle.net/a6Rx4/

It uses the number from each member of the Array being iterated to get the item at that index of someOtherArray, which is represented by this since we passed it as the context parameter.

If you do not set the context, then this will refer to the window object.

Abort a git cherry-pick?

I found the answer is git reset --merge - it clears the conflicted cherry-pick attempt.

Remove rows with all or some NAs (missing values) in data.frame

I prefer following way to check whether rows contain any NAs:

row.has.na <- apply(final, 1, function(x){any(is.na(x))})

This returns logical vector with values denoting whether there is any NA in a row. You can use it to see how many rows you'll have to drop:

sum(row.has.na)

and eventually drop them

final.filtered <- final[!row.has.na,]

For filtering rows with certain part of NAs it becomes a little trickier (for example, you can feed 'final[,5:6]' to 'apply'). Generally, Joris Meys' solution seems to be more elegant.

How to have stored properties in Swift, the same way I had on Objective-C?

The solution pointed out by jou doesn't support value types, this works fine with them as well

Wrappers

import ObjectiveC

final class Lifted<T> {
    let value: T
    init(_ x: T) {
        value = x
    }
}

private func lift<T>(x: T) -> Lifted<T>  {
    return Lifted(x)
}

func setAssociatedObject<T>(object: AnyObject, value: T, associativeKey: UnsafePointer<Void>, policy: objc_AssociationPolicy) {
    if let v: AnyObject = value as? AnyObject {
        objc_setAssociatedObject(object, associativeKey, v,  policy)
    }
    else {
        objc_setAssociatedObject(object, associativeKey, lift(value),  policy)
    }
}

func getAssociatedObject<T>(object: AnyObject, associativeKey: UnsafePointer<Void>) -> T? {
    if let v = objc_getAssociatedObject(object, associativeKey) as? T {
        return v
    }
    else if let v = objc_getAssociatedObject(object, associativeKey) as? Lifted<T> {
        return v.value
    }
    else {
        return nil
    }
}

A possible Class extension (Example of usage):

extension UIView {

    private struct AssociatedKey {
        static var viewExtension = "viewExtension"
    }

    var referenceTransform: CGAffineTransform? {
        get {
            return getAssociatedObject(self, associativeKey: &AssociatedKey.viewExtension)
        }

        set {
            if let value = newValue {
                setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.viewExtension, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }
}

This is really such a great solution, I wanted to add another usage example that included structs and values that are not optionals. Also, the AssociatedKey values can be simplified.

struct Crate {
    var name: String
}

class Box {
    var name: String

    init(name: String) {
        self.name = name
    }
}

extension UIViewController {

    private struct AssociatedKey {
        static var displayed:   UInt8 = 0
        static var box:         UInt8 = 0
        static var crate:       UInt8 = 0
    }

    var displayed: Bool? {
        get {
            return getAssociatedObject(self, associativeKey: &AssociatedKey.displayed)
        }

        set {
            if let value = newValue {
                setAssociatedObject(self, value: value, associativeKey: &AssociatedKey.displayed, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
            }
        }
    }

    var box: Box {
        get {
            if let result:Box = getAssociatedObject(self, associativeKey: &AssociatedKey.box) {
                return result
            } else {
                let result = Box(name: "")
                self.box = result
                return result
            }
        }

        set {
            setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.box, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }

    var crate: Crate {
        get {
            if let result:Crate = getAssociatedObject(self, associativeKey: &AssociatedKey.crate) {
                return result
            } else {
                let result = Crate(name: "")
                self.crate = result
                return result
            }
        }

        set {
            setAssociatedObject(self, value: newValue, associativeKey: &AssociatedKey.crate, policy: objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
        }
    }
}

Global variables in R

I found a solution for how to set a global variable in a mailinglist posting via assign:

a <- "old"
test <- function () {
   assign("a", "new", envir = .GlobalEnv)
}
test()
a  # display the new value

How to load data from a text file in a PostgreSQL database?

COPY description_f (id, name) FROM 'absolutepath\test.txt' WITH (FORMAT csv, HEADER true, DELIMITER '   ');

Example

COPY description_f (id, name) FROM 'D:\HIVEWORX\COMMON\TermServerAssets\Snomed2021\SnomedCT\Full\Terminology\sct2_Description_Full_INT_20210131.txt' WITH (FORMAT csv, HEADER true, DELIMITER ' ');

Structure padding and packing

I know this question is old and most answers here explains padding really well, but while trying to understand it myself I figured having a "visual" image of what is happening helped.

The processor reads the memory in "chunks" of a definite size (word). Say the processor word is 8 bytes long. It will look at the memory as a big row of 8 bytes building blocks. Every time it needs to get some information from the memory, it will reach one of those blocks and get it.

Variables Alignment

As seem in the image above, doesn't matter where a Char (1 byte long) is, since it will be inside one of those blocks, requiring the CPU to process only 1 word.

When we deal with data larger than one byte, like a 4 byte int or a 8 byte double, the way they are aligned in the memory makes a difference on how many words will have to be processed by the CPU. If 4-byte chunks are aligned in a way they always fit the inside of a block (memory address being a multiple of 4) only one word will have to be processed. Otherwise a chunk of 4-bytes could have part of itself on one block and part on another, requiring the processor to process 2 words to read this data.

The same applies to a 8-byte double, except now it must be in a memory address multiple of 8 to guarantee it will always be inside a block.

This considers a 8-byte word processor, but the concept applies to other sizes of words.

The padding works by filling the gaps between those data to make sure they are aligned with those blocks, thus improving the performance while reading the memory.

However, as stated on others answers, sometimes the space matters more then performance itself. Maybe you are processing lots of data on a computer that doesn't have much RAM (swap space could be used but it is MUCH slower). You could arrange the variables in the program until the least padding is done (as it was greatly exemplified in some other answers) but if that's not enough you could explicitly disable padding, which is what packing is.

JavaScript: how to change form action attribute value based on selection?

Is required that you have a form?
If not, then you could use this:

<div>
    <input type="hidden" value="ServletParameter" />
    <input type="button" id="callJavaScriptServlet" onclick="callJavaScriptServlet()" />
</div>

with the following JavaScript:

function callJavaScriptServlet() {
    this.form.action = "MyServlet";
    this.form.submit();
}

How to convert FormData (HTML5 object) to JSON

You can achieve this by using the FormData() object. This FormData object will be populated with the form's current keys/values using the name property of each element for the keys and their submitted value for the values. It will also encode file input content.

Example:

var myForm = document.getElementById('myForm');
myForm.addEventListener('submit', function(event)
{
    event.preventDefault();
    var formData = new FormData(myForm),
        result = {};

    for (var entry of formData.entries())
    {
        result[entry[0]] = entry[1];
    }
    result = JSON.stringify(result)
    console.log(result);

});

Comment shortcut Android Studio

Mac:

To comment/uncomment one line, use: Ctrl + /.

To comment/uncomment a block, use: Ctrl + Shift + /.

How to fix error Base table or view not found: 1146 Table laravel relationship table?

The simplest thing to do is, change the default table name assigned for the model. Simply put following code, protected $table = 'category_posts'; instead of protected $table = 'posts'; then it'll do the trick.

However, if you refer Laravel documentation you'll find the answer. Here what it says,

By convention, the "snake case", plural name of the class(model) will be used as the table name unless another name is explicitly specified

Better to you use artisan command to make model and the migration file at the same time, use the following command,

php artisan make:model Test --migration

This will create a model class and a migration class in your Laravel project. Let's say it created following files,

Test.php

2018_06_22_142912_create_tests_table.php

If you look at the code in those two files you'll see,

2018_06_22_142912_create_tests_table.php files' up function,

 public function up()
 {
      Schema::create('tests', function (Blueprint $table) {
      $table->increments('id');
      $table->timestamps();
      });
 }

Here it automatically generated code with the table name of 'tests' which is the plural name of that class which is in Test.php file.

Mongoose (mongodb) batch insert?

Here are both way of saving data with insertMany and save

1) Mongoose save array of documents with insertMany in bulk

/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);

/* write this api in routes directory  */
router.post('/addDocuments', function (req, res) {
    const data = [/* array of object which data need to save in db */];

    Potato.insertMany(data)  
    .then((result) => {
            console.log("result ", result);
            res.status(200).json({'success': 'new documents added!', 'data': result});
    })
    .catch(err => {
            console.error("error ", err);
            res.status(400).json({err});
    });
})

2) Mongoose save array of documents with .save()

These documents will save parallel.

/* write mongoose schema model and export this */
var Potato = mongoose.model('Potato', PotatoSchema);

/* write this api in routes directory  */
router.post('/addDocuments', function (req, res) {
    const saveData = []
    const data = [/* array of object which data need to save in db */];
    data.map((i) => {
        console.log(i)
        var potato = new Potato(data[i])
        potato.save()
        .then((result) => {
            console.log(result)
            saveData.push(result)
            if (saveData.length === data.length) {
                res.status(200).json({'success': 'new documents added!', 'data': saveData});
            }
        })
        .catch((err) => {
            console.error(err)
            res.status(500).json({err});
        })
    })
})

Hiding the address bar of a browser (popup)

This is how I do it for popups, though it is only working with IE11, not Chrome- haven't tested in Firefox.

window.open(url, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no');

How can I find non-ASCII characters in MySQL?

One missing character from everyone's examples above is the termination character (\0). This is invisible to the MySQL console output and is not discoverable by any of the queries heretofore mentioned. The query to find it is simply:

select * from TABLE where COLUMN like '%\0%';

How to properly create composite primary keys - MYSQL

Aside from personal design preferences, there are cases where one wants to make use of composite primary keys. Tables may have two or more fields that provide a unique combination, and not necessarily by way of foreign keys.

As an example, each US state has a set of unique Congressional districts. While many states may individually have a CD-5, there will never be more than one CD-5 in any of the 50 states, and vice versa. Therefore, creating an autonumber field for Massachusetts CD-5 would be redundant.

If the database drives a dynamic web page, writing code to query on a two-field combination could be much simpler than extracting/resubmitting an autonumbered key.

So while I'm not answering the original question, I certainly appreciate Adam's direct answer.

jQuery keypress() event not firing?

e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.

See http://unixpapa.com/js/key.html for more information.

How can I start and check my MySQL log?

Enable general query log by the following query in mysql command line

SET GLOBAL general_log = 'ON';

Now open C:/xampp/mysql/data/mysql.log and check query log

If it fails, open your my.cnf file. For windows its my.ini file and enable it there. Just make sure its in the [mysqld] section

[mysqld]
general_log             = 1

Note: In xampp my.ini file can be either found in xampp\mysql or in c:\windows directory

findViewById in Fragment

Note :

From API Level 26, you also don't need to specifically cast the result of findViewById as it uses inference for its return type.

So now you can simply do,

public View onCreateView(LayoutInflater inflater, 
                         ViewGroup container, 
                         Bundle savedInstanceState) {
     View view = inflater.inflate(R.layout.testclassfragment, container, false);
     ImageView imageView =  view.findViewById(R.id.my_image); //without casting the return type
     return view;
}

Does `anaconda` create a separate PYTHONPATH variable for each new environment?

No, the only thing that needs to be modified for an Anaconda environment is the PATH (so that it gets the right Python from the environment bin/ directory, or Scripts\ on Windows).

The way Anaconda environments work is that they hard link everything that is installed into the environment. For all intents and purposes, this means that each environment is a completely separate installation of Python and all the packages. By using hard links, this is done efficiently. Thus, there's no need to mess with PYTHONPATH because the Python binary in the environment already searches the site-packages in the environment, and the lib of the environment, and so on.

How can I change the size of a Bootstrap checkbox?

It is possible to implement custom bootstrap checkbox for the most popular browsers nowadays.

You can check my Bootstrap-Checkbox project in GitHub, which contains simple .less file. There is a good article in MDN describing some techniques, where the two major are:

  1. Label redirects a click event.

    Label can redirect a click event to its target if it has the for attribute like in <label for="target_id">Text</label> <input id="target_id" type="checkbox" />, or if it contains input as in Bootstrap case: <label><input type="checkbox" />Text</label>.

    It means that it is possible to place a label in one corner of the browser, click on it, and then the label will redirect click event to the checkbox located in other corner producing check/uncheck action for the checkbox.

    We can hide original checkbox visually, but make it is still working and taking click event from the label. In the label itself we can emulate checkbox with a tag or pseudo-element :before :after.

  2. General non supported tag for old browsers

    Some old browsers does not support several CSS features like selecting siblings p+p or specific search input[type=checkbox]. According to the MDN article browsers that support these features also support :root CSS selector, while others not. The :root selector just selects the root element of a document, which is html in a HTML page. Thus it is possible to use :root for a fallback to old browsers and original checkboxes.

    Final code snippet:

_x000D_
_x000D_
:root {_x000D_
  /* larger checkbox */_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox] {_x000D_
  /* hide original check box */_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
  /* find the nearest span with checkbox-placeholder class and draw custom checkbox */_x000D_
  /* draw checkmark before the span placeholder when original hidden input is checked */_x000D_
  /* disabled checkbox style */_x000D_
  /* disabled and checked checkbox style */_x000D_
  /* when the checkbox is focused with tab key show dots arround */_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox] + span.checkbox-placeholder {_x000D_
  width: 14px;_x000D_
  height: 14px;_x000D_
  border: 1px solid;_x000D_
  border-radius: 3px;_x000D_
  /*checkbox border color*/_x000D_
  border-color: #737373;_x000D_
  display: inline-block;_x000D_
  cursor: pointer;_x000D_
  margin: 0 7px 0 -20px;_x000D_
  vertical-align: middle;_x000D_
  text-align: center;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked + span.checkbox-placeholder {_x000D_
  background: #0ccce4;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked + span.checkbox-placeholder:before {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  vertical-align: text-top;_x000D_
  width: 5px;_x000D_
  height: 9px;_x000D_
  /*checkmark arrow color*/_x000D_
  border: solid white;_x000D_
  border-width: 0 2px 2px 0;_x000D_
  /*can be done with post css autoprefixer*/_x000D_
  -webkit-transform: rotate(45deg);_x000D_
  -moz-transform: rotate(45deg);_x000D_
  -ms-transform: rotate(45deg);_x000D_
  -o-transform: rotate(45deg);_x000D_
  transform: rotate(45deg);_x000D_
  content: "";_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:disabled + span.checkbox-placeholder {_x000D_
  background: #ececec;_x000D_
  border-color: #c3c2c2;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:checked:disabled + span.checkbox-placeholder {_x000D_
  background: #d6d6d6;_x000D_
  border-color: #bdbdbd;_x000D_
}_x000D_
:root label.checkbox-bootstrap input[type=checkbox]:focus:not(:hover) + span.checkbox-placeholder {_x000D_
  outline: 1px dotted black;_x000D_
}_x000D_
:root label.checkbox-bootstrap.checkbox-lg input[type=checkbox] + span.checkbox-placeholder {_x000D_
  width: 26px;_x000D_
  height: 26px;_x000D_
  border: 2px solid;_x000D_
  border-radius: 5px;_x000D_
  /*checkbox border color*/_x000D_
  border-color: #737373;_x000D_
}_x000D_
:root label.checkbox-bootstrap.checkbox-lg input[type=checkbox]:checked + span.checkbox-placeholder:before {_x000D_
  width: 9px;_x000D_
  height: 15px;_x000D_
  /*checkmark arrow color*/_x000D_
  border: solid white;_x000D_
  border-width: 0 3px 3px 0;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<p>_x000D_
 Original checkboxes:_x000D_
</p>_x000D_
<div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox">             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" disabled>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox disabled_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" checked>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox checked_x000D_
      </label>_x000D_
 </div>_x000D_
  <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap">                                        _x000D_
          <input type="checkbox" checked disabled>             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Original checkbox checked and disabled_x000D_
      </label>_x000D_
 </div>_x000D_
 <div class="checkbox">_x000D_
      <label class="checkbox-bootstrap checkbox-lg">                           _x000D_
          <input type="checkbox">             _x000D_
          <span class="checkbox-placeholder"></span>           _x000D_
          Large checkbox unchecked_x000D_
      </label>_x000D_
 </div>_x000D_
  <br/>_x000D_
<p>_x000D_
 Inline checkboxes:_x000D_
</p>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox">_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline _x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox" disabled>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline disabled_x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap">_x000D_
  <input type="checkbox" checked disabled>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Inline checked and disabled_x000D_
</label>_x000D_
<label class="checkbox-inline checkbox-bootstrap checkbox-lg">_x000D_
  <input type="checkbox" checked>_x000D_
  <span class="checkbox-placeholder"></span>_x000D_
  Large inline checked_x000D_
</label>
_x000D_
_x000D_
_x000D_

How to count the frequency of the elements in an unordered list?

This approach can be tried if you don't want to use any library and keep it simple and short!

a = [1,1,1,1,2,2,2,2,3,3,4,5,5]
marked = []
b = [(a.count(i), marked.append(i))[0] for i in a if i not in marked]
print(b)

o/p

[4, 4, 2, 1, 2]

Trigger an event on `click` and `enter`

Take a look at the keypress function.

I believe the enter key is 13 so you would want something like:

$('#searchButton').keypress(function(e){
    if(e.which == 13){  //Enter is key 13
        //Do something
    }
});

posting hidden value

Maybe a little late to the party but why don't you use sessions to store your data?

bookingfacilities.php

session_start();
$_SESSION['form_date'] = $date;

successfulbooking.php

session_start();
$date = $_SESSION['form_date']; 

Nobody will see this.

How to increase space between dotted border dots

Building 4 edges solution basing on @Eagorajose's answer with shorthand syntax:

background: linear-gradient(to right, #000 33%, #fff 0%) top/10px 1px repeat-x, /* top */
linear-gradient(#000 33%, #fff 0%) right/1px 10px repeat-y, /* right */
linear-gradient(to right, #000 33%, #fff 0%) bottom/10px 1px repeat-x, /* bottom */
linear-gradient(#000 33%, #fff 0%) left/1px 10px repeat-y; /* left */

_x000D_
_x000D_
#page {_x000D_
    background: linear-gradient(to right, #000 33%, #fff 0%) top/10px 1px repeat-x, /* top */_x000D_
    linear-gradient(#000 33%, #fff 0%) right/1px 10px repeat-y, /* right */_x000D_
    linear-gradient(to right, #000 33%, #fff 0%) bottom/10px 1px repeat-x, /* bottom */_x000D_
    linear-gradient(#000 33%, #fff 0%) left/1px 10px repeat-y; /* left */_x000D_
    _x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
}
_x000D_
<div id="page"></div>
_x000D_
_x000D_
_x000D_

Breaking out of a nested loop

Use a suitable guard in the outer loop. Set the guard in the inner loop before you break.

bool exitedInner = false;

for (int i = 0; i < N && !exitedInner; ++i) {

    .... some outer loop stuff

    for (int j = 0; j < M; ++j) {

        if (sometest) {
            exitedInner = true;
            break;
        }
    }
    if (!exitedInner) {
       ... more outer loop stuff
    }
}

Or better yet, abstract the inner loop into a method and exit the outer loop when it returns false.

for (int i = 0; i < N; ++i) {

    .... some outer loop stuff

    if (!doInner(i, N, M)) {
       break;
    }

    ... more outer loop stuff
}

Java creating .jar file

Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.

Windows service on Local Computer started and then stopped error

I have found it very handy to convert your existing windows service to a console by simply changing your program with the following. With this change you can run the program by debugging in visual studio or running the executable normally. But it will also work as a windows service. I also made a blog post about it

program.cs

class Program
{
    static void Main()
    {
        var program = new YOUR_PROGRAM();
        if (Environment.UserInteractive)
        {
            program.Start();
        }
        else
        {
            ServiceBase.Run(new ServiceBase[]
            {
                program
            });
        }
    }
}

YOUR_PROGRAM.cs

[RunInstallerAttribute(true)]
public class YOUR_PROGRAM : ServiceBase
{
    public YOUR_PROGRAM()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
        Start();
    }

    protected override void OnStop()
    {
        //Stop Logic Here
    }

    public void Start()
    {
        //Start Logic here
    }
}

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.

You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.

How to send a PUT/DELETE request in jQuery?

If you need to make a $.post work to a Laravel Route::delete or Route::put just add an argument "_method"="delete" or "_method"="put".

$.post("your/uri/here", {"arg1":"value1",...,"_method":"delete"}, function(data){}); ...

Must works for others Frameworks

Note: Tested with Laravel 5.6 and jQuery 3

Laravel 5: Display HTML with Blade

On controller.

$your_variable = '';
$your_variable .= '<p>Hello world</p>';

return view('viewname')->with('your_variable', $your_variable)

If you do not want your data to be escaped, you may use the following syntax:

{!! $your_variable !!}

Output

Hello world

SQL JOIN and different types of JOINs

Interestingly most other answers suffer from these two problems:

I've recently written an article on the topic: A Probably Incomplete, Comprehensive Guide to the Many Different Ways to JOIN Tables in SQL, which I'll summarise here.

First and foremost: JOINs are cartesian products

This is why Venn diagrams explain them so inaccurately, because a JOIN creates a cartesian product between the two joined tables. Wikipedia illustrates it nicely:

enter image description here

The SQL syntax for cartesian products is CROSS JOIN. For example:

SELECT *

-- This just generates all the days in January 2017
FROM generate_series(
  '2017-01-01'::TIMESTAMP,
  '2017-01-01'::TIMESTAMP + INTERVAL '1 month -1 day',
  INTERVAL '1 day'
) AS days(day)

-- Here, we're combining all days with all departments
CROSS JOIN departments

Which combines all rows from one table with all rows from the other table:

Source:

+--------+   +------------+
| day    |   | department |
+--------+   +------------+
| Jan 01 |   | Dept 1     |
| Jan 02 |   | Dept 2     |
| ...    |   | Dept 3     |
| Jan 30 |   +------------+
| Jan 31 |
+--------+

Result:

+--------+------------+
| day    | department |
+--------+------------+
| Jan 01 | Dept 1     |
| Jan 01 | Dept 2     |
| Jan 01 | Dept 3     |
| Jan 02 | Dept 1     |
| Jan 02 | Dept 2     |
| Jan 02 | Dept 3     |
| ...    | ...        |
| Jan 31 | Dept 1     |
| Jan 31 | Dept 2     |
| Jan 31 | Dept 3     |
+--------+------------+

If we just write a comma separated list of tables, we'll get the same:

-- CROSS JOINing two tables:
SELECT * FROM table1, table2

INNER JOIN (Theta-JOIN)

An INNER JOIN is just a filtered CROSS JOIN where the filter predicate is called Theta in relational algebra.

For instance:

SELECT *

-- Same as before
FROM generate_series(
  '2017-01-01'::TIMESTAMP,
  '2017-01-01'::TIMESTAMP + INTERVAL '1 month -1 day',
  INTERVAL '1 day'
) AS days(day)

-- Now, exclude all days/departments combinations for
-- days before the department was created
JOIN departments AS d ON day >= d.created_at

Note that the keyword INNER is optional (except in MS Access).

(look at the article for result examples)

EQUI JOIN

A special kind of Theta-JOIN is equi JOIN, which we use most. The predicate joins the primary key of one table with the foreign key of another table. If we use the Sakila database for illustration, we can write:

SELECT *
FROM actor AS a
JOIN film_actor AS fa ON a.actor_id = fa.actor_id
JOIN film AS f ON f.film_id = fa.film_id

This combines all actors with their films.

Or also, on some databases:

SELECT *
FROM actor
JOIN film_actor USING (actor_id)
JOIN film USING (film_id)

The USING() syntax allows for specifying a column that must be present on either side of a JOIN operation's tables and creates an equality predicate on those two columns.

NATURAL JOIN

Other answers have listed this "JOIN type" separately, but that doesn't make sense. It's just a syntax sugar form for equi JOIN, which is a special case of Theta-JOIN or INNER JOIN. NATURAL JOIN simply collects all columns that are common to both tables being joined and joins USING() those columns. Which is hardly ever useful, because of accidental matches (like LAST_UPDATE columns in the Sakila database).

Here's the syntax:

SELECT *
FROM actor
NATURAL JOIN film_actor
NATURAL JOIN film

OUTER JOIN

Now, OUTER JOIN is a bit different from INNER JOIN as it creates a UNION of several cartesian products. We can write:

-- Convenient syntax:
SELECT *
FROM a LEFT JOIN b ON <predicate>

-- Cumbersome, equivalent syntax:
SELECT a.*, b.*
FROM a JOIN b ON <predicate>
UNION ALL
SELECT a.*, NULL, NULL, ..., NULL
FROM a
WHERE NOT EXISTS (
  SELECT * FROM b WHERE <predicate>
)

No one wants to write the latter, so we write OUTER JOIN (which is usually better optimised by databases).

Like INNER, the keyword OUTER is optional, here.

OUTER JOIN comes in three flavours:

  • LEFT [ OUTER ] JOIN: The left table of the JOIN expression is added to the union as shown above.
  • RIGHT [ OUTER ] JOIN: The right table of the JOIN expression is added to the union as shown above.
  • FULL [ OUTER ] JOIN: Both tables of the JOIN expression are added to the union as shown above.

All of these can be combined with the keyword USING() or with NATURAL (I've actually had a real world use-case for a NATURAL FULL JOIN recently)

Alternative syntaxes

There are some historic, deprecated syntaxes in Oracle and SQL Server, which supported OUTER JOIN already before the SQL standard had a syntax for this:

-- Oracle
SELECT *
FROM actor a, film_actor fa, film f
WHERE a.actor_id = fa.actor_id(+)
AND fa.film_id = f.film_id(+)

-- SQL Server
SELECT *
FROM actor a, film_actor fa, film f
WHERE a.actor_id *= fa.actor_id
AND fa.film_id *= f.film_id

Having said so, don't use this syntax. I just list this here so you can recognise it from old blog posts / legacy code.

Partitioned OUTER JOIN

Few people know this, but the SQL standard specifies partitioned OUTER JOIN (and Oracle implements it). You can write things like this:

WITH

  -- Using CONNECT BY to generate all dates in January
  days(day) AS (
    SELECT DATE '2017-01-01' + LEVEL - 1
    FROM dual
    CONNECT BY LEVEL <= 31
  ),

  -- Our departments
  departments(department, created_at) AS (
    SELECT 'Dept 1', DATE '2017-01-10' FROM dual UNION ALL
    SELECT 'Dept 2', DATE '2017-01-11' FROM dual UNION ALL
    SELECT 'Dept 3', DATE '2017-01-12' FROM dual UNION ALL
    SELECT 'Dept 4', DATE '2017-04-01' FROM dual UNION ALL
    SELECT 'Dept 5', DATE '2017-04-02' FROM dual
  )
SELECT *
FROM days 
LEFT JOIN departments 
  PARTITION BY (department) -- This is where the magic happens
  ON day >= created_at

Parts of the result:

+--------+------------+------------+
| day    | department | created_at |
+--------+------------+------------+
| Jan 01 | Dept 1     |            | -- Didn't match, but still get row
| Jan 02 | Dept 1     |            | -- Didn't match, but still get row
| ...    | Dept 1     |            | -- Didn't match, but still get row
| Jan 09 | Dept 1     |            | -- Didn't match, but still get row
| Jan 10 | Dept 1     | Jan 10     | -- Matches, so get join result
| Jan 11 | Dept 1     | Jan 10     | -- Matches, so get join result
| Jan 12 | Dept 1     | Jan 10     | -- Matches, so get join result
| ...    | Dept 1     | Jan 10     | -- Matches, so get join result
| Jan 31 | Dept 1     | Jan 10     | -- Matches, so get join result

The point here is that all rows from the partitioned side of the join will wind up in the result regardless if the JOIN matched anything on the "other side of the JOIN". Long story short: This is to fill up sparse data in reports. Very useful!

SEMI JOIN

Seriously? No other answer got this? Of course not, because it doesn't have a native syntax in SQL, unfortunately (just like ANTI JOIN below). But we can use IN() and EXISTS(), e.g. to find all actors who have played in films:

SELECT *
FROM actor a
WHERE EXISTS (
  SELECT * FROM film_actor fa
  WHERE a.actor_id = fa.actor_id
)

The WHERE a.actor_id = fa.actor_id predicate acts as the semi join predicate. If you don't believe it, check out execution plans, e.g. in Oracle. You'll see that the database executes a SEMI JOIN operation, not the EXISTS() predicate.

enter image description here

ANTI JOIN

This is just the opposite of SEMI JOIN (be careful not to use NOT IN though, as it has an important caveat)

Here are all the actors without films:

SELECT *
FROM actor a
WHERE NOT EXISTS (
  SELECT * FROM film_actor fa
  WHERE a.actor_id = fa.actor_id
)

Some folks (especially MySQL people) also write ANTI JOIN like this:

SELECT *
FROM actor a
LEFT JOIN film_actor fa
USING (actor_id)
WHERE film_id IS NULL

I think the historic reason is performance.

LATERAL JOIN

OMG, this one is too cool. I'm the only one to mention it? Here's a cool query:

SELECT a.first_name, a.last_name, f.*
FROM actor AS a
LEFT OUTER JOIN LATERAL (
  SELECT f.title, SUM(amount) AS revenue
  FROM film AS f
  JOIN film_actor AS fa USING (film_id)
  JOIN inventory AS i USING (film_id)
  JOIN rental AS r USING (inventory_id)
  JOIN payment AS p USING (rental_id)
  WHERE fa.actor_id = a.actor_id -- JOIN predicate with the outer query!
  GROUP BY f.film_id
  ORDER BY revenue DESC
  LIMIT 5
) AS f
ON true

It will find the TOP 5 revenue producing films per actor. Every time you need a TOP-N-per-something query, LATERAL JOIN will be your friend. If you're a SQL Server person, then you know this JOIN type under the name APPLY

SELECT a.first_name, a.last_name, f.*
FROM actor AS a
OUTER APPLY (
  SELECT f.title, SUM(amount) AS revenue
  FROM film AS f
  JOIN film_actor AS fa ON f.film_id = fa.film_id
  JOIN inventory AS i ON f.film_id = i.film_id
  JOIN rental AS r ON i.inventory_id = r.inventory_id
  JOIN payment AS p ON r.rental_id = p.rental_id
  WHERE fa.actor_id = a.actor_id -- JOIN predicate with the outer query!
  GROUP BY f.film_id
  ORDER BY revenue DESC
  LIMIT 5
) AS f

OK, perhaps that's cheating, because a LATERAL JOIN or APPLY expression is really a "correlated subquery" that produces several rows. But if we allow for "correlated subqueries", we can also talk about...

MULTISET

This is only really implemented by Oracle and Informix (to my knowledge), but it can be emulated in PostgreSQL using arrays and/or XML and in SQL Server using XML.

MULTISET produces a correlated subquery and nests the resulting set of rows in the outer query. The below query selects all actors and for each actor collects their films in a nested collection:

SELECT a.*, MULTISET (
  SELECT f.*
  FROM film AS f
  JOIN film_actor AS fa USING (film_id)
  WHERE a.actor_id = fa.actor_id
) AS films
FROM actor

As you have seen, there are more types of JOIN than just the "boring" INNER, OUTER, and CROSS JOIN that are usually mentioned. More details in my article. And please, stop using Venn diagrams to illustrate them.

How do I install Keras and Theano in Anaconda Python on Windows?

The trick is that you need to create an environment/workspace for Python. This solution should work for Python 2.7 but at the time of writing keras can run on python 3.5, especially if you have the latest anaconda installed (this took me awhile to figure out so I'll outline the steps I took to install KERAS in python 3.5):

Create environment/workspace for Python 3.5

  1. C:\conda create --name neuralnets python=3.5
  2. C:\activate neuralnets

Install everything (notice the neuralnets workspace in parenthesis on each line). Accept any dependencies each of those steps wants to install:

  1. (neuralnets) C:\conda install theano
  2. (neuralnets) C:\conda install mingw libpython
  3. (neuralnets) C:\pip install tensorflow
  4. (neuralnets) C:\pip install keras

Test it out:

(neuralnets) C:\python -c "from keras import backend; print(backend._BACKEND)"

Just remember, if you want to work in the workspace you always have to do:

C:\activate neuralnets

so you can launch Jupyter for example (assuming you also have Jupyter installed in this environment/workspace) as:

C:\activate neuralnets
(neuralnets) jupyter notebook

You can read more about managing and creating conda environments/workspaces at the follwing URL: https://conda.io/docs/using/envs.html

What is the use of ObservableCollection in .net?

ObservableCollection Caveat

Mentioned above (Said Roohullah Allem)

What makes the ObservableCollection class unique is that this class supports an event named CollectionChanged.

Keep this in mind...If you adding a large number of items to an ObservableCollection the UI will also update that many times. This can really gum up or freeze your UI. A work around would be to create a new list, add all the items then set your property to the new list. This hits the UI once. Again...this is for adding a large number of items.

Can't install any packages in Node.js using "npm install"

npm set registry http://85.10.209.91/

(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).

The other solutions seem to have outdated versions.

Relative div height

add this to you CSS:

html, body
{
    height: 100%;
}

working Fiddle

when you say to wrap to be 100%, 100% of what? of its parent (body), so his parent has to have some height.

and the same goes for body, his parent his html. html parent his the viewport.. so, by setting them both to 100%, wrap can also have a percentage height.

also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use

*
{
    padding: 0;
    margin: 0;
}

to disable that.

Look at That Fiddle

Regular expression to find URLs within a string

(?:vnc|s3|ssh|scp|sftp|ftp|http|https)\:\/\/[\w\.]+(?:\:?\d{0,5})|(?:mailto|)\:[\w\.]+\@[\w\.]+

If you want an explanation of each part, try in regexr[.]com where you will get a great explanation of every character.

This is split by an "|" or "OR" because not all useable URI have "//" so this is where you can create a list of schemes as or conditions that you would be interested in matching.

How to check object is nil or not in swift?

The case of if abc == nil is used when you are declaring a var and want to force unwrap and then check for null. Here you know this can be nil and you can check if != nil use the NSString functions from foundation.

In case of String? you are not aware what is wrapped at runtime and hence you have to use if-let and perform the check.

You were doing following but without "!". Hope this clears it.

From apple docs look at this:

let assumedString: String! = "An implicitly unwrapped optional string."

You can still treat an implicitly unwrapped optional like a normal optional, to check if it contains a value:

if assumedString != nil {
    println(assumedString)
}
// prints "An implicitly unwrapped optional string."

Iframe positioning

It's because you're missing position:relative; on #contentframe

<div id="contentframe" style="position:relative; top: 160px; left: 0px;">

position:absolute; positions itself against the closest ancestor that has a position that is not static. Since the default is static that is what was causing your issue.

When restoring a backup, how do I disconnect all active connections?

To add to advice already given, if you have a web app running through IIS that uses the DB, you may also need to stop (not recycle) the app pool for the app while you restore, then re-start. Stopping the app pool kills off active http connections and doesn't allow any more, which could otherwise end up allowing processes to be triggered that connect to and thereby lock the database. This is a known issue for example with the Umbraco Content Management System when restoring its database

Format number to 2 decimal places

How about CAST(2229.999 AS DECIMAL(6,2)) to get a decimal with 2 decimal places

Is Tomcat running?

tomcat.sh helps you know this easily.

tomcat.sh usage doc says:

no argument: display the process-id of the tomcat, if it's running, otherwise do nothing

So, run command on your command prompt and check for pid:

$ tomcat.sh

Converting between datetime and Pandas Timestamp objects

>>> pd.Timestamp('2014-01-23 00:00:00', tz=None).to_datetime()
datetime.datetime(2014, 1, 23, 0, 0)
>>> pd.Timestamp(datetime.date(2014, 3, 26))
Timestamp('2014-03-26 00:00:00')

ERROR: Cannot open source file " "

  1. Copy the contents of the file,
  2. Create an .h file, give it the name of the original .h file
  3. Copy the contents of the original file to the newly created one
  4. Build it
  5. VOILA!!

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

How to calculate cumulative normal distribution?

Alex's answer shows you a solution for standard normal distribution (mean = 0, standard deviation = 1). If you have normal distribution with mean and std (which is sqr(var)) and you want to calculate:

from scipy.stats import norm

# cdf(x < val)
print norm.cdf(val, m, s)

# cdf(x > val)
print 1 - norm.cdf(val, m, s)

# cdf(v1 < x < v2)
print norm.cdf(v2, m, s) - norm.cdf(v1, m, s)

Read more about cdf here and scipy implementation of normal distribution with many formulas here.

css display table cell requires percentage width

Note also that vertical-align:top; is often necessary for correct table cell appearance.

css table-cell, contents have unnecessary top margin

What to use now Google News API is deprecated?

Depending on your needs, you want to use their section feeds, their search feeds

http://news.google.com/news?q=apple&output=rss

or Bing News Search.

http://www.bing.com/toolbox/bingdeveloper/

Should I return EXIT_SUCCESS or 0 from main()?

It does not matter. Both are the same.

C++ Standard Quotes:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

Limit file format when using <input type="file">?

Use input tag with accept attribute

<input type="file" name="my-image" id="image" accept="image/gif, image/jpeg, image/png" />

Click here for the latest browser compatibility table

Live demo here

To select only image files, you can use this accept="image/*"

<input type="file" name="my-image" id="image" accept="image/*" />

Live demo here

Only gif, jpg and png will be shown, screen grab from Chrome version 44 Only gif, jpg and png will be shown, screen grab from Chrome version 44

Create two threads, one display odd & other even numbers

public class MyThread {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Threado o =new Threado();
        o.start();

        Threade e=new Threade();
        e.start();    
    }    
}


class Threade extends Thread{

    public void run(){

        for(int i=2;i<10;i=i+2)
            System.out.println("evens "+i);         
    }       
}


class Threado extends Thread{

    public void run(){

        for(int i=1;i<10;i=i+2)
            System.out.println("odds "+i);          
    }       
}

OUTPUT :-

odds 1 odds 3 odds 5 odds 7 odds 9 evens 2 evens 4 evens 6 evens 8

How can I merge two MySQL tables?

If you need to do it manually, one time:

First, merge in a temporary table, with something like:

create table MERGED as select * from table 1 UNION select * from table 2

Then, identify the primary key constraints with something like

SELECT COUNT(*), PK from MERGED GROUP BY PK HAVING COUNT(*) > 1

Where PK is the primary key field...

Solve the duplicates.

Rename the table.

[edited - removed brackets in the UNION query, which was causing the error in the comment below]

jQuery Ajax requests are getting cancelled without being sent

I have had the same problem, for me I was creating the iframe for temporary manner and I was removing the iframe before the ajax become completes, so the browser would cancel my ajax request.

python mpl_toolkits installation issue

I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap

How to use putExtra() and getExtra() for string data

You can Simply use static variable to store the string of your edittext and then use that variable in the other class. Hope this will solve your problem

ByRef argument type mismatch in Excel VBA

I don't know why, but it is very important to declare the variables separately if you want to pass variables (as variables) into other procedure or function.

For example there is a procedure which make some manipulation with data: based on ID returns Part Number and Quantity information. ID as constant value, other two arguments are variables.

Public Sub GetPNQty(ByVal ID As String, PartNumber As String, Quantity As Long)

the next main code gives me a "ByRef argument mismatch":

Sub KittingScan()  
Dim BoxPN As String
Dim BoxQty, BoxKitQty As Long

  Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty) 

End sub

and the next one is working as well:

Sub KittingScan()
Dim BoxPN As String
Dim BoxQty As Long
Dim BoxKitQty As Long

  Call GetPNQty(InputBox("Enter ID:"), BoxPN, BoxQty)

End sub

sort dict by value python

no lambda method

# sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
    for k, v in d.items():
        if v == i:
            return (k)

sortvaluelist = sorted(d.values())
sortresult ={}
for i1 in sortvaluelist:   
    key = getkeybyvalue(d,i1)
    sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')

How to convert string to string[]?

You can create a string[] (string array) that contains your string like :

string someString = "something";
string[] stringArray = new string[]{ someString };

The variable stringArray will now have a length of 1 and contain someString.

What's the difference between identifying and non-identifying relationships?

  • An identifying relationship is when the existence of a row in a child table depends on a row in a parent table. This may be confusing because it's common practice these days to create a pseudokey for a child table, but not make the foreign key to the parent part of the child's primary key. Formally, the "right" way to do this is to make the foreign key part of the child's primary key. But the logical relationship is that the child cannot exist without the parent.

    Example: A Person has one or more phone numbers. If they had just one phone number, we could simply store it in a column of Person. Since we want to support multiple phone numbers, we make a second table PhoneNumbers, whose primary key includes the person_id referencing the Person table.

    We may think of the phone number(s) as belonging to a person, even though they are modeled as attributes of a separate table. This is a strong clue that this is an identifying relationship (even if we don't literally include person_id in the primary key of PhoneNumbers).

  • A non-identifying relationship is when the primary key attributes of the parent must not become primary key attributes of the child. A good example of this is a lookup table, such as a foreign key on Person.state referencing the primary key of States.state. Person is a child table with respect to States. But a row in Person is not identified by its state attribute. I.e. state is not part of the primary key of Person.

    A non-identifying relationship can be optional or mandatory, which means the foreign key column allows NULL or disallows NULL, respectively.


See also my answer to Still Confused About Identifying vs. Non-Identifying Relationships

how to get request path with express req object

req.route.path is working for me

var pool = require('../db');

module.exports.get_plants = function(req, res) {
    // to run a query we can acquire a client from the pool,
    // run a query on the client, and then return the client to the pool
    pool.connect(function(err, client, done) {
        if (err) {
            return console.error('error fetching client from pool', err);
        }
        client.query('SELECT * FROM plants', function(err, result) {
            //call `done()` to release the client back to the pool
            done();
            if (err) {
                return console.error('error running query', err);
            }
            console.log('A call to route: %s', req.route.path + '\nRequest type: ' + req.method.toLowerCase());
            res.json(result);
        });
    });
};

after executing I see the following in the console and I get perfect result in my browser.

Express server listening on port 3000 in development mode
A call to route: /plants
Request type: get

Oracle SQL Where clause to find date records older than 30 days

Use:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= TRUNC(SYSDATE) - 30

SYSDATE returns the date & time; TRUNC resets the date to being as of midnight so you can omit it if you want the creation_date that is 30 days previous including the current time.

Depending on your needs, you could also look at using ADD_MONTHS:

SELECT *
  FROM YOUR_TABLE
 WHERE creation_date <= ADD_MONTHS(TRUNC(SYSDATE), -1)

make html text input field grow as I type?

A couple of things come to mind:

Use an onkeydown handler in your text field, measure the text*, and increase the text box size accordingly.

Attach a :focus css class to your text box with a larger width. Then your box will be larger when focused. That's not exactly what you're asking for, but similar.

* It's not straightforward to measure text in javascript. Check out this question for some ideas.

Does swift have a trim method on String?

Another similar way:

extension String {
    var trimmed:String {
        return self.trimmingCharacters(in: CharacterSet.whitespaces)
    }
}

Use:

let trimmedString = "myString ".trimmed

Adding items to a JComboBox

Wrap the values in a class and override the toString() method.

class ComboItem
{
    private String key;
    private String value;

    public ComboItem(String key, String value)
    {
        this.key = key;
        this.value = value;
    }

    @Override
    public String toString()
    {
        return key;
    }

    public String getKey()
    {
        return key;
    }

    public String getValue()
    {
        return value;
    }
}

Add the ComboItem to your comboBox.

comboBox.addItem(new ComboItem("Visible String 1", "Value 1"));
comboBox.addItem(new ComboItem("Visible String 2", "Value 2"));
comboBox.addItem(new ComboItem("Visible String 3", "Value 3"));

Whenever you get the selected item.

Object item = comboBox.getSelectedItem();
String value = ((ComboItem)item).getValue();

Android : Fill Spinner From Java Code Programmatically

// you need to have a list of data that you want the spinner to display
List<String> spinnerArray =  new ArrayList<String>();
spinnerArray.add("item1");
spinnerArray.add("item2");

ArrayAdapter<String> adapter = new ArrayAdapter<String>(
    this, android.R.layout.simple_spinner_item, spinnerArray);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner sItems = (Spinner) findViewById(R.id.spinner1);
sItems.setAdapter(adapter);

also to find out what is selected you could do something like this

String selected = sItems.getSelectedItem().toString();
if (selected.equals("what ever the option was")) {
}

difference between new String[]{} and new String[] in java

1.THE USE OF {}:

It initialize the array with the values { }

2.The difference between String array=new String[]; and String array=new String[]{};

String array=new String[]; and String array=new String[]{}; both are invalid statement in java.

It will gives you an error that you are trying to assign String array to String datatype. More specifically error is like this Type mismatch: cannot convert from String[] to String

3.String array=new String[10]{}; got error why?

Wrong because you are defining an array of length 10 ([10]), then defining an array of length String[10]{} 0

How to filter rows in pandas by regex

Thanks for the great answer @user3136169, here is an example of how that might be done also removing NoneType values.

def regex_filter(val):
    if val:
        mo = re.search(regex,val)
        if mo:
            return True
        else:
            return False
    else:
        return False

df_filtered = df[df['col'].apply(regex_filter)]

Also you can also add regex as an arg:

def regex_filter(val,myregex):
    ...

df_filtered = df[df['col'].apply(res_regex_filter,regex=myregex)]

XML Schema minOccurs / maxOccurs default values

The default values for minOccurs and maxOccurs are 1. Thus:

<xsd:element minOccurs="1" name="asdf"/>

cardinality is [1-1] Note: if you specify only minOccurs attribute, it can't be greater than 1, because the default value for maxOccurs is 1.

<xsd:element minOccurs="5" maxOccurs="2" name="asdf"/>

invalid

<xsd:element maxOccurs="2" name="asdf"/>

cardinality is [1-2] Note: if you specify only maxOccurs attribute, it can't be smaller than 1, because the default value for minOccurs is 1.

<xsd:element minOccurs="0" maxOccurs="0"/>

is a valid combination which makes the element prohibited.

For more info see http://www.w3.org/TR/xmlschema-0/#OccurrenceConstraints

Better way to check if a Path is a File or a Directory?

I came across this when facing a similar problem, except I needed to check if a path is for a file or folder when that file or folder may not actually exist. There were a few comments on answers above that mentioned they would not work for this scenario. I found a solution (I use VB.NET, but you can convert if you need) that seems to work well for me:

Dim path As String = "myFakeFolder\ThisDoesNotExist\"
Dim bIsFolder As Boolean = (IO.Path.GetExtension(path) = "")
'returns True

Dim path As String = "myFakeFolder\ThisDoesNotExist\File.jpg"
Dim bIsFolder As Boolean = (IO.Path.GetExtension(path) = "")
'returns False

Hopefully this can be helpful to someone!

Cannot perform runtime binding on a null reference, But it is NOT a null reference

This error happens when you have a ViewBag Non-Existent in your razor code calling a method.

Controller

public ActionResult Accept(int id)
{
    return View();
}

razor:

<div class="form-group">
      @Html.LabelFor(model => model.ToId, "To", htmlAttributes: new { @class = "control-label col-md-2" })
     <div class="col-md-10">
           @Html.Flag(Model.from)
     </div>
</div>
<div class="form-group">
     <div class="col-md-10">
          <input value="@ViewBag.MaximounAmount.ToString()" />@* HERE is the error *@ 
     </div>
</div>

For some reason, the .net aren't able to show the error in the correct line.

Normally this causes a lot of wasted time.

Use of "this" keyword in C++

It's programmer preference. Personally, I love using this since it explicitly marks the object members. Of course the _ does the same thing (only when you follow the convention)

PHP: if !empty & empty

if(!empty($youtube) && empty($link)) {

}
else if(empty($youtube) && !empty($link)) {

}
else if(empty($youtube) && empty($link)) {
}

Sublime Text 2 - Show file navigation in sidebar

  1. open ST ( Sublime Text )

  2. add your project root folder into ST : link : https://stackoverflow.com/a/18798528/1241980

  3. show sidebar : Menu bar View > Side Bar > Show Side Bar

  4. Try Ctrl + P to open a file someFileName.py

Does a navigation panel for openned files and project folders appear in the left of ST ?

Extra : Want view the other files that are in the same directory with someFileName.py ?
While I found ST side bar seems doesn't support this, but you can try Ctrl + O (Open) keyshort in ST to open your system file browser, in which the ST will help you to locate into the folder that contains someFileName.py and it's sibling files.

Triangle Draw Method

You should try using the Shapes API.

Take a look at JPanel repaint from another class which is all about drawing triangles, look to the getPath method for some ideas

You should also read up on GeneralPath & Drawing Arbitrary Shapes.

This method is much easy to apply AffineTransformations to

Jupyter Notebook not saving: '_xsrf' argument missing from post

When I click 'save' button, it has this error. Based on the answers in this post and other websites, I just found the solution. My jupyter notebook is installed from pip. So I access it by typing 'jupyter notebook' in the windows command line.

(1) open a new command window, then open a new jupyter notebook. try to save again in the old notebook, this time ,the error is 'fail: forbidden'

(2) Then in the old notebook, click 'download as', it will pop out a new windows ask you the token.

enter image description here

(3) open another command window, then open another jupyter notebook, type 'jupyter notebook list' copy the code after 'token=' and before :: to the box you just saw. You can save this time. If it fails, you can try another token in the list

JSON to PHP Array using file_get_contents

Check some typo ','

<?php
 //file_get_content(url);
$jsonD = '{
    "bpath":"http://www.sampledomain.com/",
    "clist":[{
            "cid":"11",
            "display_type":"grid",
            "ctitle":"abc",
            "acount":"71",
            "alist":[{
                    "aid":"6865",
                    "adate":"2 Hours ago",
                    "atitle":"test",
                    "adesc":"test desc",
                    "aimg":"",
                    "aurl":"?nid=6865",
                    "weburl":"news.php?nid=6865",
                    "cmtcount":"0"
                },
                {
                    "aid":"6857",
                    "adate":"20 Hours ago",
                    "atitle":"test1",
                    "adesc":"test desc1",
                    "aimg":"",
                    "aurl":"?nid=6857",
                    "weburl":"news.php?nid=6857",
                    "cmtcount":"0"
                }
            ]
        },
        {
            "cid":"1",
            "display_type":"grid",
            "ctitle":"test1",
            "acount":"2354",
            "alist":[{
                    "aid":"6851",
                    "adate":"1 Days ago",
                    "atitle":"test123",
                    "adesc":"test123 desc",
                    "aimg":"",
                    "aurl":"?nid=6851",
                    "weburl":"news.php?nid=6851",
                    "cmtcount":"7"
                },
                {
                    "aid":"6847",
                    "adate":"2 Days ago",
                    "atitle":"test12345",
                    "adesc":"test12345 desc",
                    "aimg":"",
                    "aurl":"?nid=6847",
                    "weburl":"news.php?nid=6847",
                    "cmtcount":"7"
                }
            ]
        }
    ]
}
';

$parseJ = json_decode($jsonD,true);

print_r($parseJ);
?>

how to get docker-compose to use the latest image from repository

If the docker compose configuration is in a file, simply run:

docker-compose -f appName.yml down && docker-compose -f appName.yml pull && docker-compose -f appName.yml up -d

How can I print variable and string on same line in Python?

On a current python version you have to use parenthesis, like so :

print ("If there was a birth every 7 seconds", X)

Trying to mock datetime.date.today(), but not working

Maybe you could use your own "today()" method that you will patch where needed. Example with mocking utcnow() can be found here: https://bitbucket.org/k_bx/blog/src/tip/source/en_posts/2012-07-13-double-call-hack.rst?at=default

How to convert CharSequence to String?

There is a subtle issue here that is a bit of a gotcha.

The toString() method has a base implementation in Object. CharSequence is an interface; and although the toString() method appears as part of that interface, there is nothing at compile-time that will force you to override it and honor the additional constraints that the CharSequence toString() method's javadoc puts on the toString() method; ie that it should return a string containing the characters in the order returned by charAt().

Your IDE won't even help you out by reminding that you that you probably should override toString(). For example, in intellij, this is what you'll see if you create a new CharSequence implementation: http://puu.sh/2w1RJ. Note the absence of toString().

If you rely on toString() on an arbitrary CharSequence, it should work provided the CharSequence implementer did their job properly. But if you want to avoid any uncertainty altogether, you should use a StringBuilder and append(), like so:

final StringBuilder sb = new StringBuilder(charSequence.length());
sb.append(charSequence);
return sb.toString();

How do you detect/avoid Memory leaks in your (Unmanaged) code?

If your C/C++ code is portable to *nix, few things are better than Valgrind.

How to get the text of the selected value of a dropdown list?

Hi if you are having dropdownlist like this

<select id="testID">
<option value="1">Value1</option>
<option value="2">Value2</option>
<option value="3">Value3</option>
<option value="4">Value4</option>
<option value="5">Value5</option>
<option value="6">Value6</option>
</select>
<input type="button" value="Get dropdown selected Value" onclick="getHTML();">

after giving id to dropdownlist you just need to add jquery code like this

function getHTML()
{
      var display=$('#testID option:selected').html();
      alert(display);
}

Auto Increment after delete in MySQL

Its definitely not recommendable. If you have a large database with multiple tables, you may probably have saved a userid as id in table 2. if you rearrange table 1 then probably the intended userid will not end up being the intended table 2 id.

Phonegap Cordova installation Windows

I faced the same problem and struggled for an hour to get pass through by reading the documents and the other issues reported in Stack Overflow but I didn't find any answer to it. So, here is the guide to successfully run the phonegap/cordova in Windows Machine.

Follow these steps

  1. Download and Install node.js from http://nodejs.org/
  2. Run the command npm install -g phonegap (in case of phonegap installation) or run the command npm install -g cordova (in case of Cordova installation).
  3. As the installation gets completed you can notice this:

    C:\Users\binaryuser\AppData\Roaming\npm\cordova -> C:\Users\binaryuser\AppData\Roaming\npm\node_modules\cordova\bin\cordova
    [email protected] C:\Users\binaryuser\AppData\Roaming\npm\node_modules\cordova
    +-- [email protected]
    +-- [email protected]
    +-- [email protected]
    +-- [email protected]
    +-- [email protected]
    +-- [email protected] ([email protected])
    +-- [email protected] ([email protected])
    +-- [email protected] ([email protected], [email protected])
    +-- [email protected] ([email protected], [email protected])
    +-- [email protected] ([email protected], [email protected])
    +-- [email protected] ([email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
    +-- [email protected]
    +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
    
  4. Notice the above line you can see the path were the file is mentioned. Copy that path. In my case it is C:\Users\binaryuser\AppData\Roaming\npm\cordova so use cd C:\Users\binaryuser\AppData\Roaming\npm\ and type cordova. There it is, it finally works.

  5. Since the -g key value isn't working you have set the Environment Variables path:
    1. Press Win + Pause|Break or right click on Computer and choose Properties.
    2. Click Advanced system settings on the left.
    3. Click Environment Variables under the Advanced tab.
    4. Select the PATH variable and click Edit.
    5. Copy the path mentioned above to the value field and press OK.

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

try:

Activity parentActivity = this.getParent();
if (parentActivity != null)
{
    View landmarkEditNameView = (EditText) parentActivity.findViewById(R.id. landmark_name_dialog_edit);
}

Create list of object from another using Java 8 Streams

What you are possibly looking for is map(). You can "convert" the objects in a stream to another by mapping this way:

...
 .map(userMeal -> new UserMealExceed(...))
...

Accessing JSON elements

Just for more one option...You can do it this way too:

MYJSON = {
    'username': 'gula_gut',
    'pics': '/0/myfavourite.jpeg',
    'id': '1'
}

#changing username
MYJSON['username'] = 'calixto'
print(MYJSON['username'])

I hope this can help.

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

jQuery datepicker years shown

Adding to what @Shog9 posted, you can also restrict dates individually in the beforeShowDay: callback function.

You supply a function that takes a date and returns a boolean array:

"$(".selector").datepicker({ beforeShowDay: nationalDays}) 
natDays = [[1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'], [4, 27, 'za'], 
[5, 25, 'ar'], [6, 6, 'se'], [7, 4, 'us'], [8, 17, 'id'], [9, 7, 
'br'], [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']]; 
function nationalDays(date) { 
    for (i = 0; i < natDays.length; i++) { 
      if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == 
natDays[i][1]) { 
        return [false, natDays[i][2] + '_day']; 
      } 
    } 
  return [true, '']; 
} 

How do you set, clear, and toggle a single bit?

It is sometimes worth using an enum to name the bits:

enum ThingFlags = {
  ThingMask  = 0x0000,
  ThingFlag0 = 1 << 0,
  ThingFlag1 = 1 << 1,
  ThingError = 1 << 8,
}

Then use the names later on. I.e. write

thingstate |= ThingFlag1;
thingstate &= ~ThingFlag0;
if (thing & ThingError) {...}

to set, clear and test. This way you hide the magic numbers from the rest of your code.

Other than that I endorse Jeremy's solution.

Check whether IIS is installed or not?

In the menu, go to RUN > services.msc and hit enter to get the services window and check for the IIS ADMIN service. If it is not present, then reinstall IIS using your windows CD.

Xcode error "Could not find Developer Disk Image"

This happens when your Xcode version doesn't have a necessary component to build the application to your target OS. You should update your Xcode.

If you are building a new application for a beta OS version that no stable Xcode version is able to build, you should download the newest Xcode beta version.

I also had this problem. I was using Xcode 7.3 for my iOS 10 beta iPhone, so I went to install Xcode 8-beta, and I did the following step to continue using the stable version of Xcode with new build tool:

Just like @onmyway133 answer, but more user-friendly is after finish installing the Xcode 8-beta version, go to Xcode 7.3 preferences (Cmd + ,), go to the tab locations, change the Command Line Tools to Xcode 8 in the dropdown list.

I successfully built to both iOS simulator 9.3 and my device iOS 10 beta using Xcode 7.3.

How to do a simple file search in cmd

dir /b/s *.txt  

searches for all txt file in the directory tree. Before using it just change the directory to root using

cd/

you can also export the list to a text file using

dir /b/s *.exe >> filelist.txt

and search within using

type filelist.txt | find /n "filename"

EDIT 1: Although this dir command works since the old dos days but Win7 added something new called Where

where /r c:\Windows *.exe *.dll

will search for exe & dll in the drive c:\Windows as suggested by @SPottuit you can also copy the output to the clipboard with

where /r c:\Windows *.exe |clip

just wait for the prompt to return and don't copy anything until then.

EDIT 2: If you are searching recursively and the output is big you can always use more to enable paging, it will show -- More -- at the bottom and will scroll to the next page once you press SPACE or moves line by line on pressing ENTER

where /r c:\Windows *.exe |more

For more help try

where/?

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

My problem was missing package declaration in the beginning of the activity source file:

package com.my.package

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)

Once the user have choose a image you can read the file-path of the chosen image and place it into your html.

Example:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

Javascript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

What is the difference between properties and attributes in HTML?

After reading Sime Vidas's answer, I searched more and found a very straight-forward and easy-to-understand explanation in the angular docs.

HTML attribute vs. DOM property

-------------------------------

Attributes are defined by HTML. Properties are defined by the DOM (Document Object Model).

  • A few HTML attributes have 1:1 mapping to properties. id is one example.

  • Some HTML attributes don't have corresponding properties. colspan is one example.

  • Some DOM properties don't have corresponding attributes. textContent is one example.

  • Many HTML attributes appear to map to properties ... but not in the way you might think!

That last category is confusing until you grasp this general rule:

Attributes initialize DOM properties and then they are done. Property values can change; attribute values can't.

For example, when the browser renders <input type="text" value="Bob">, it creates a corresponding DOM node with a value property initialized to "Bob".

When the user enters "Sally" into the input box, the DOM element value property becomes "Sally". But the HTML value attribute remains unchanged as you discover if you ask the input element about that attribute: input.getAttribute('value') returns "Bob".

The HTML attribute value specifies the initial value; the DOM value property is the current value.


The disabled attribute is another peculiar example. A button's disabled property is false by default so the button is enabled. When you add the disabled attribute, its presence alone initializes the button's disabled property to true so the button is disabled.

Adding and removing the disabled attribute disables and enables the button. The value of the attribute is irrelevant, which is why you cannot enable a button by writing <button disabled="false">Still Disabled</button>.

Setting the button's disabled property disables or enables the button. The value of the property matters.

The HTML attribute and the DOM property are not the same thing, even when they have the same name.

Change the location of an object programmatically

Use either:

balancePanel.Left = optionsPanel.Location.X;

or

balancePanel.Location = new Point(optionsPanel.Location.X, balancePanel.Location.Y);

See the documentation of Location:

Because the Point class is a value type (Structure in Visual Basic, struct in Visual C#), it is returned by value, meaning accessing the property returns a copy of the upper-left point of the control. So, adjusting the X or Y properties of the Point returned from this property will not affect the Left, Right, Top, or Bottom property values of the control. To adjust these properties set each property value individually, or set the Location property with a new Point.

Pull new updates from original GitHub repository into forked GitHub repository

This video shows how to update a fork directly from GitHub

Steps:

  1. Open your fork on GitHub.
  2. Click on Pull Requests.
  3. Click on New Pull Request. By default, GitHub will compare the original with your fork, and there shouldn’t be anything to compare if you didn’t make any changes.
  4. Click on switching the base. Now GitHub will compare your fork with the original, and you should see all the latest changes.
  5. Click on Create a pull request for this comparison and assign a predictable name to your pull request (e.g., Update from original).
  6. Click on Create pull request.
  7. Scroll down and click Merge pull request and finally Confirm merge. If your fork didn’t have any changes, you will be able to merge it automatically.

Placeholder in UITextView

In swift 5. Works fine.

class BaseTextView: UITextView {

    // MARK: - Views
    private var placeholderLabel: UIlabel!

    // MARK: - Init
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
        startupSetup()
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        setupUI()
        startupSetup()
    }

    deinit {
        NotificationCenter.default.removeObserver(self)
    }    
}

// MARK: - Setup UI
private extension BaseTextView {
    func setupUI() {
        addPlaceholderLabel()

        textColor = .textColor
    }

    func addPlaceholderLabel() {
        placeholderLabel = BaseLabel(frame: .zero)
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        insertSubview(placeholderLabel, at: 0)

        placeholderLabel.alpha = 0
        placeholderLabel.numberOfLines = 0
        placeholderLabel.backgroundColor = .clear
        placeholderLabel.textColor = .lightTextColor
        placeholderLabel.lineBreakMode = .byWordWrapping
        placeholderLabel.isUserInteractionEnabled = false
        placeholderLabel.font = UIFont.openSansSemibold.withSize(12)

        placeholderLabel.topAnchor.constraint(equalTo: topAnchor, constant: 8).isActive = true
        placeholderLabel.leftAnchor.constraint(equalTo: leftAnchor, constant: 5).isActive = true
        placeholderLabel.rightAnchor.constraint(lessThanOrEqualTo: rightAnchor, constant: -8).isActive = true
        placeholderLabel.bottomAnchor.constraint(lessThanOrEqualTo: bottomAnchor, constant: -8).isActive = true
    }
}

// MARK: - Startup
private extension BaseTextView {
    func startupSetup() {
        addObservers()
        textChanged(nil)
        font = UIFont.openSansSemibold.withSize(12)
    }    

    func addObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged(_:)), name: UITextView.textDidChangeNotification, object: nil)
    }
}

// MARK: - Actions
private extension BaseTextView {
    @objc func textChanged(_ sender: Notification?) {
        UIView.animate(withDuration: 0.2) {
            self.placeholderLabel.alpha = self.text.count == 0 ? 1 : 0
        }    
    }
}

// MARK: - Public methods
extension BaseTextView {
    public func setPlaceholder(_ placeholder: String) {
        placeholderLabel.text = placeholder
    }
}

Bootstrap 3 - Set Container Width to 940px Maximum for Desktops?

There is a far easier solution (IMO) in Bootstrap 3 that does not require you to compile any custom LESS. You just have to leverage the cascade in "Cascading Style Sheets."

Set up your CSS loading like so...

<link type="text/css" rel="stylesheet" href="/css/bootstrap.css" />
<link type="text/css" rel="stylesheet" href="/css/custom.css" />

Where /css/custom.css is your unique style definitions. Inside that file, add the following definition...

@media (min-width: 1200px) {
  .container {
    width: 970px;
  }
}

This will override Bootstrap's default width: 1170px setting when the viewport is 1200px or bigger.

Tested in Bootstrap 3.0.2

WCF timeout exception detailed investigation

from: http://www.codeproject.com/KB/WCF/WCF_Operation_Timeout_.aspx

To avoid this timeout error, we need to configure the OperationTimeout property for Proxy in the WCF client code. This configuration is something new unlike other configurations such as Send Timeout, Receive Timeout etc., which I discussed early in the article. To set this operation timeout property configuration, we have to cast our proxy to IContextChannel in WCF client application before calling the operation contract methods.

html5 input for money/currency

Try using step="0.01", then it will step by a penny each time.

eg:

_x000D_
_x000D_
<input type="number" min="0.00" max="10000.00" step="0.01" />
_x000D_
_x000D_
_x000D_

How to put wildcard entry into /etc/hosts?

It happens that /etc/hosts file doesn't support wild card entries.

You'll have to use other services like dnsmasq. To enable it in dnsmasq, just edit dnsmasq.conf and add the following line:

address=/example.com/127.0.0.1

Is it possible to have a default parameter for a mysql stored procedure?

SET myParam = IFNULL(myParam, 0);

Explanation: IFNULL(expression_1, expression_2)

The IFNULL function returns expression_1 if expression_1 is not NULL; otherwise it returns expression_2. The IFNULL function returns a string or a numeric based on the context where it is used.