Programs & Examples On #Branching and merging

In version control, branches represent parallel lines of development. Merging is the action that integrates changes made in different branches.

How do I create a branch?

  • Create a new folder outside of your current project. You can give it any name. (Example: You have a checkout for a project named "Customization". And it has many projects, like "Project1", "Project2"....And you want to create a branch of "Project1". So first open the "Customization", right click and create a new folder and give it a name, "Project1Branch").
  • Right click on "Myproject1"....TortoiseSVN -> Branch/Tag.
  • Choose working copy.
  • Open browser....Just right of parallel on "To URL".
  • Select customization.....right click then Add Folder. and go through the folder which you have created. Here it is "Project1Branch". Now clik the OK button to add.
  • Take checkout of this new banch.
  • Again go to your project which branch you want to create. Right click TorotoiseSVN -> branch/tag. Then select working copy. And you can give the URL as your branch name. like {your IP address/svn/AAAA/Customization/Project1Branch}. And you can set the name in the URL so it will create the folder with this name only. Like {Your IP address/svn/AAAA/Customization/Project1Branch/MyProject1Branch}.
  • Press the OK button. Now you can see the logs in ...your working copy will be stored in your branch.
  • Now you can take a check out...and let you enjoy your work. :)

How to resolve git's "not something we can merge" error

This may sounds weird, but remember to setup your git email and name:

git config --global user.email "[email protected]"
git config --global user.name "FIRST_NAME LAST_NAME"

Remove large .pack file created by git

As loganfsmyth already stated in his answer, you need to purge git history because the files continue to exist there even after deleting them from the repo. Official GitHub docs recommend BFG which I find easier to use than filter-branch:

Deleting files from history

Download BFG from their website. Make sure you have java installed, then create a mirror clone and purge history. Make sure to replace YOUR_FILE_NAME with the name of the file you'd like to delete:

git clone --mirror git://example.com/some-big-repo.git
java -jar bfg.jar --delete-files YOUR_FILE_NAME some-big-repo.git
cd some-big-repo.git
git reflog expire --expire=now --all && git gc --prune=now --aggressive
git push

Delete a folder

Same as above but use --delete-folders

java -jar bfg.jar --delete-folders YOUR_FOLDER_NAME some-big-repo.git

Other options

BFG also allows for even fancier options (see docs) like these:

Remove all files bigger than 100M from history:

java -jar bfg.jar --strip-blobs-bigger-than 100M some-big-repo.git

Important!

When running BFG, be careful that both YOUR_FILE_NAME and YOUR_FOLDER_NAME are indeed just file/folder names. They're not paths, so something like foo/bar.jpg will not work! Instead all files/folders with the specified name will be removed from repo history, no matter which path or branch they existed.

How to copy commits from one branch to another?

For the simple case of just copying the last commit from branch wss to v2.1, you can simply grab the commit id (git log --oneline | head -n 1) and do:

git checkout v2.1
git merge <commit>

What I can do to resolve "1 commit behind master"?

Suppose currently in your branch myBranch
Do the following :-

git status

If all changes are committed

git pull origin master

If changes are not committed than

git add .

git commit -m"commit changes"

git pull origin master

Check if there are any conflicts than resolve and commit changes

git add .

git commit -m"resolved conflicts message"

And than push

git push origin myBranch

How do I copy a version of a single file from one git branch to another?

What about using checkout command :

  git diff --stat "$branch"
  git checkout --merge "$branch" "$file"
  git diff --stat "$branch"

Move the most recent commit(s) to a new branch with Git

For those wondering why it works (as I was at first):

You want to go back to C, and move D and E to the new branch. Here's what it looks like at first:

A-B-C-D-E (HEAD)
        ?
      master

After git branch newBranch:

    newBranch
        ?
A-B-C-D-E (HEAD)
        ?
      master

After git reset --hard HEAD~2:

    newBranch
        ?
A-B-C-D-E (HEAD)
    ?
  master

Since a branch is just a pointer, master pointed to the last commit. When you made newBranch, you simply made a new pointer to the last commit. Then using git reset you moved the master pointer back two commits. But since you didn't move newBranch, it still points to the commit it originally did.

Deleting an SVN branch

For those using TortoiseSVN, you can accomplish this by using the Repository Browser (it's labeled "Repo-browser" in the context menu.)

context menu

Find the branch folder you want to delete, right-click it, and select "Delete."

deleting the folder

Enter your commit message, and you're done.

committing

What is the best (and safest) way to merge a Git branch into master?

As the title says "Best way", I think it's a good idea to consider the patience merge strategy.

From: https://git-scm.com/docs/merge-strategies

With this option, 'merge-recursive' spends a little extra time to avoid mismerges that sometimes occur due to unimportant matching lines (e.g., braces from distinct functions). Use this when the branches to be merged have diverged wildly. See also git-diff[1] --patience.

Usage:

git fetch
git merge -s recursive -X patience origin/master

Git Alias

I use always an alias for this, e.g. run once:

 git config --global alias.pmerge 'merge -s recursive -X patience'

Now you could do:

git fetch
git pmerge origin/master

JavaFX Panel inside Panel auto resizing

I was designing a GUI in SceneBuilder, trying to make the main container adapt to whatever the window size is. It should always be 100% wide.

This is where you can set these values in SceneBuilder:

AnchorPane Constraints in SceneBuilder

Toggling the dotted/red lines will actually just add/remove the attributes that Korki posted in his solution (AnchorPane.topAnchor etc.).

Error: org.testng.TestNGException: Cannot find class in classpath: EmpClass

For me it was that I added Skip Tests checkbox/flag in the Maven Build of the Project

Therefore the test classes weren't compiled and then weren't found by TestNG

How can I determine if a date is between two dates in Java?

Here's a couple ways to do this using the Joda-Time 2.3 library.

One way is to use the simple isBefore and isAfter methods on DateTime instances. By the way, DateTime in Joda-Time is similar in concept to a java.util.Date (a moment in time on the timeline of the Universe) but includes a time zone.

Another way is to build an Interval in Joda-Time. The contains method tests if a given DateTime occurs within the span of time covered by the Interval. The beginning of the Interval is inclusive, but the endpoint is exclusive. This approach is known as "Half-Open", symbolically [).

See both ways in the following code example.

Convert the java.util.Date instances to Joda-Time DateTime instances. Simply pass the Date instance to constructor of DateTime. In practice you should also pass a specific DateTimeZone object rather than rely on JVM’s default time zone.

DateTime dateTime1 = new DateTime( new java.util.Date() ).minusWeeks( 1 );
DateTime dateTime2 = new DateTime( new java.util.Date() );
DateTime dateTime3 = new DateTime( new java.util.Date() ).plusWeeks( 1 );

Compare by testing for before/after…

boolean is1After2 = dateTime1.isAfter( dateTime2 );
boolean is2Before3 = dateTime2.isBefore( dateTime3 );

boolean is2Between1And3 = ( ( dateTime2.isAfter( dateTime1 ) ) && ( dateTime2.isBefore( dateTime3 ) ) );

Using the Interval approach instead of isAfter/isBefore…

Interval interval = new Interval( dateTime1, dateTime3 );
boolean intervalContainsDateTime2 = interval.contains( dateTime2 );

Dump to console…

System.out.println( "DateTimes: " + dateTime1 + " " + dateTime1 + " " + dateTime1 );
System.out.println( "is1After2 " + is1After2 );
System.out.println( "is2Before3 " + is2Before3 );
System.out.println( "is2Between1And3 " + is2Between1And3 );
System.out.println( "intervalContainsDateTime2 " + intervalContainsDateTime2 );

When run…

DateTimes: 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00 2014-01-22T20:26:14.955-08:00
is1After2 false
is2Before3 true
is2Between1And3 true
intervalContainsDateTime2 true

Read text from response

Your "application/xrds+xml" was giving me issues, I was receiving a Content-Length of 0 (no response).

After removing that, you can access the response using response.GetResponseStream().

HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;

//request.Accept = "application/xrds+xml";  
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

WebHeaderCollection header = response.Headers;

var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
    string responseText = reader.ReadToEnd();
}

How to add new line in Markdown presentation?

I was using Markwon for markdown parsing in Android. The following worked great:

"My first line  \nMy second line  \nMy third line  \nMy last line"

...two spaces followed by \n at the end of each line.

How to make readonly all inputs in some div in Angular2?

If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable().

Getting error while sending email through Gmail SMTP - "Please log in via your web browser and then try again. 534-5.7.14"

There are two ways to resolve this, and only one may work, depending on how you're accessing Google.

The first method is to authorize access for your IP or client machine using the https://accounts.google.com/DisplayUnlockCaptcha link. That can resolve authentication issues on client devices, like mobile or desktop apps. I would test this first, because it results in a lower overall decrease in account security.

If the above link doesn't work, it's because the session is being initiated by an app or device that is not associated with your particular location. Examples include:

  • An app that uses a remote server to retrieve data, like a web site or, in my case, other Google servers
  • A company mail server fetching mail on your behalf

In all such cases you have to use the https://www.google.com/settings/security/lesssecureapps link referenced above.

TLDR; check the captcha link first, and if it doesn't work, try the other one and enable less secure apps.

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

PHP: Show yes/no confirmation dialog

<a onclick="javascript:return confirm('Are You Confirm Deletion');" href="delete_customer.php?a=<?php echo $row['id']; ?>"  class="btn btn-danger a-btn-slide-text" style="color: white; width:86px; height:37px;" > <span class="glyphicon glyphicon-remove" aria-hidden="true"></span><span><strong></a></strong></span> 

How to get the file extension in PHP?

How about

$ext = array_pop($userfile_extn);

Swift: print() vs println() vs NSLog()

Moreover, Swift 2 has debugPrint() (and CustomDebugStringConvertible protocol)!

Don't forget about debugPrint() which works like print() but most suitable for debugging.

Examples:

  • Strings
    • print("Hello World!") becomes Hello World
    • debugPrint("Hello World!") becomes "Hello World" (Quotes!)
  • Ranges
    • print(1..<6) becomes 1..<6
    • debugPrint(1..<6) becomes Range(1..<6)

Any class can customize their debug string representation via CustomDebugStringConvertible protocol.

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

Get a random boolean in python?

Adam's answer is quite fast, but I found that random.getrandbits(1) to be quite a lot faster. If you really want a boolean instead of a long then

bool(random.getrandbits(1))

is still about twice as fast as random.choice([True, False])

Both solutions need to import random

If utmost speed isn't to priority then random.choice definitely reads better

$ python -m timeit -s "import random" "random.choice([True, False])"
1000000 loops, best of 3: 0.904 usec per loop
$ python -m timeit -s "import random" "random.choice((True, False))" 
1000000 loops, best of 3: 0.846 usec per loop
$ python -m timeit -s "import random" "random.getrandbits(1)"
1000000 loops, best of 3: 0.286 usec per loop
$ python -m timeit -s "import random" "bool(random.getrandbits(1))"
1000000 loops, best of 3: 0.441 usec per loop
$ python -m timeit -s "import random" "not random.getrandbits(1)"
1000000 loops, best of 3: 0.308 usec per loop
$ python -m timeit -s "from random import getrandbits" "not getrandbits(1)"
1000000 loops, best of 3: 0.262 usec per loop  # not takes about 20us of this

Added this one after seeing @Pavel's answer

$ python -m timeit -s "from random import random" "random() < 0.5"
10000000 loops, best of 3: 0.115 usec per loop

Exception of type 'System.OutOfMemoryException' was thrown.

If you're using IIS Express, select Show All Application from IIS Express in the task bar notification area, then select Stop All.

Now re-run your application.

How to communicate between Docker containers via "hostname"

Edit: After Docker 1.9, the docker network command (see below https://stackoverflow.com/a/35184695/977939) is the recommended way to achieve this.


My solution is to set up a dnsmasq on the host to have DNS record automatically updated: "A" records have the names of containers and point to the IP addresses of the containers automatically (every 10 sec). The automatic updating script is pasted here:

#!/bin/bash

# 10 seconds interval time by default
INTERVAL=${INTERVAL:-10}

# dnsmasq config directory
DNSMASQ_CONFIG=${DNSMASQ_CONFIG:-.}

# commands used in this script
DOCKER=${DOCKER:-docker}
SLEEP=${SLEEP:-sleep}
TAIL=${TAIL:-tail}

declare -A service_map

while true
do
    changed=false
    while read line
    do
        name=${line##* }
        ip=$(${DOCKER} inspect --format '{{.NetworkSettings.IPAddress}}' $name)
        if [ -z ${service_map[$name]} ] || [ ${service_map[$name]} != $ip ] # IP addr changed
        then
            service_map[$name]=$ip
            # write to file
            echo $name has a new IP Address $ip >&2
            echo "host-record=$name,$ip"  > "${DNSMASQ_CONFIG}/docker-$name"
            changed=true
        fi
    done < <(${DOCKER} ps | ${TAIL} -n +2)

    # a change of IP address occured, restart dnsmasq
    if [ $changed = true ]
    then
        systemctl restart dnsmasq
    fi

    ${SLEEP} $INTERVAL
done

Make sure your dnsmasq service is available on docker0. Then, start your container with --dns HOST_ADDRESS to use this mini dns service.

Reference: http://docs.blowb.org/setup-host/dnsmasq.html

Node.js for() loop returning the same values at each loop

I would suggest doing this in a more functional style :P

function CreateMessageboard(BoardMessages) {
  var htmlMessageboardString = BoardMessages
   .map(function(BoardMessage) {
     return MessageToHTMLString(BoardMessage);
   })
   .join('');
}

Try this

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

How do I fix the multiple-step OLE DB operation errors in SSIS?

This error is common when the source table contains a TEXT column and the target is anything other than a TEXT column. It can be a real time-eater if you have not encountered (or forgot!) this before.

Convert the text column to string and set the error condition on truncation to ignore. this will usually serve as a solution for this error.

Text size of android design TabLayout tabs

Do as following.

1. Add the Style to the XML

    <style name="MyTabLayoutTextAppearance" parent="TextAppearance.Design.Tab">
        <item name="android:textSize">14sp</item>
    </style>

2. Apply Style

Find the Layout containing the TabLayout and add the style. The added line is bold.

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        app:tabTextAppearance="@style/MyTabLayoutTextAppearance" 
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

Silent installation of a MSI package

You should be able to use the /quiet or /qn options with msiexec to perform a silent install.

MSI packages export public properties, which you can set with the PROPERTY=value syntax on the end of the msiexec parameters.

For example, this command installs a package with no UI and no reboot, with a log and two properties:

msiexec /i c:\path\to\package.msi /quiet /qn /norestart /log c:\path\to\install.log PROPERTY1=value1 PROPERTY2=value2

You can read the options for msiexec by just running it with no options from Start -> Run.

Include jQuery in the JavaScript Console

Per this answer:

fetch('https://code.jquery.com/jquery-latest.min.js').then(r => r.text()).then(r => eval(r))

For some reason I have to execute it twice to get the new '$' (which I have to do with the other methods as well), but it works.

This is the equivalent if your browser isn't so modern:

fetch('http://code.jquery.com/jquery-latest.min.js').then(function(r){return r.text()}).then(function(r){eval(r)})

file_get_contents() how to fix error "Failed to open stream", "No such file"

Why don't you use cURL ?

$yourkey="your api key";
$url="https://prod.api.pvp.net/api/lol/euw/v1.1/game/by-summoner/20986461/recent?api_key=$yourkey";
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$auth = curl_exec($curl);
if($auth)
{
$json = json_decode($auth); 
print_r($json);
}
}

Breaking out of nested loops

If you're going to raise an exception, you might raise a StopIteration exception. That will at least make the intent obvious.

What is the Auto-Alignment Shortcut Key in Eclipse?

Auto-alignment? Lawful good?

If you mean formatting, then Ctrl+Shift+F.

How to create a .gitignore file

If you don't want to have your .gitignore interfere with anyone else's repository, you can also use .git/info/exclude. (See http://help.github.com/ignore-files/)

wget/curl large file from google drive

The default behavior of google drive is to scan files for viruses if the file is to big it will prompte the user and notifies him that the file could not be scanned.

At the moment the only workaround I found is to share the file with the web and create a web resource.

Quote from the google drive help page:

With Drive, you can make web resources — like HTML, CSS, and Javascript files — viewable as a website.

To host a webpage with Drive:

  1. Open Drive at drive.google.com and select a file.
  2. Click the Share button at the top of the page.
  3. Click Advanced in the bottom right corner of the sharing box.
  4. Click Change....
  5. Choose On - Public on the web and click Save.
  6. Before closing the sharing box, copy the document ID from the URL in the field below "Link to share". The document ID is a string of uppercase and lowercase letters and numbers between slashes in the URL.
  7. Share the URL that looks like "www.googledrive.com/host/[doc id] where [doc id] is replaced by the document ID you copied in step 6.
    Anyone can now view your webpage.

Found here: https://support.google.com/drive/answer/2881970?hl=en

So for example when you share a file on google drive publicly the sharelink looks like this:

https://drive.google.com/file/d/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U/view?usp=sharing

Then you copy the file id and create a googledrive.com linke that look like this:

https://www.googledrive.com/host/0B5IRsLTwEO6CVXFURmpQZ1Jxc0U

How to close the current fragment by using Button like the back button?

Try this:

ft.addToBackStack(null);   // ft is FragmentTransaction

So, when you press back-key, the current activity (which holds multiple fragments) will load previous fragment rather than finishing itself.

Bootstrap 4, How do I center-align a button?

you can also just wrap with an H class or P class with a text-center attribute

jQuery Mobile how to check if button is disabled?

To see which options have been set on a jQuery UI button use:

$("#deliveryNext").button('option')

To check if it's disabled you can use:

$("#deliveryNext").button('option', 'disabled')

Unfortunately, if the button hasn't been explicitly enabled or disabled before, the above call will just return the button object itself so you'll need to first check to see if the options object contains the 'disabled' property.

So to determine if a button is disabled you can do it like this:

$("#deliveryNext").button('option').disabled != undefined && $("#deliveryNext").button('option', 'disabled')

Need to make a clickable <div> button

Just use an <a> by itself, set it to display: block; and set width and height. Get rid of the <span> and <div>. This is the semantic way to do it. There is no need to wrap things in <divs> (or any element) for layout. That is what CSS is for.

Demo: http://jsfiddle.net/ThinkingStiff/89Enq/

HTML:

<a id="music" href="Music.html">Music I Like</a>

CSS:

#music {
    background-color: black;
    color: white;
    display: block;
    height: 40px;
    line-height: 40px;
    text-decoration: none;
    width: 100px;
    text-align: center;
}

Output:

enter image description here

How to find index position of an element in a list when contains returns true

Use List.indexOf(). This will give you the first match when there are multiple duplicates.

How to use foreach with a hash reference?

foreach my $key (keys %$ad_grp_ref) {
    ...
}

Perl::Critic and daxim recommend the style

foreach my $key (keys %{ $ad_grp_ref }) {
    ...
}

out of concerns for readability and maintenance (so that you don't need to think hard about what to change when you need to use %{ $ad_grp_obj[3]->get_ref() } instead of %{ $ad_grp_ref })

Passing multiple parameters with $.ajax url

why not just pass an data an object with your key/value pairs then you don't have to worry about encoding

$.ajax({
    type: "Post",
    url: "getdata.php",
    data:{
       timestamp: timestamp,
       uid: id,
       uname: name
    },
    async: true,
    cache: false,
    success: function(data) {


    };
}?);?

How do I properly escape quotes inside HTML attributes?

Per HTML syntax, and even HTML5, the following are all valid options:

<option value="&quot;asd">test</option>
<option value="&#34;asd">test</option>
<option value='"asd'>test</option>
<option value='&quot;asd'>test</option>
<option value='&#34;asd'>test</option>
<option value=&quot;asd>test</option>
<option value=&#34;asd>test</option>

Note that if you are using XML syntax the quotes (single or double) are required.

Here's a jsfiddle showing all of the above working.

What permission do I need to access Internet from an Android application?

just put above line like below

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.avocats.activeavocats"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="9"
    android:targetSdkVersion="16" />

 <uses-permission android:name="android.permission.INTERNET" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >


    <activity
        android:name="com.example.exp.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

response.sendRedirect() from Servlet to JSP does not seem to work

Since you already have sent some data,

System.out.println("going to demo.jsp");

you won't be able to send a redirect.

Table-level backup

BMC Recovery Manager (formerly known as SQLBacktrack) allows point-in-time recovery of individual objects in a database (aka tables). It is not cheap but does a fantastic job: http://www.bmc.com/products/proddocview/0,2832,19052_19429_70025639_147752,00.html

http://www.bmc.com/products/proddocview/0,2832,19052_19429_67883151_147636,00.html

Search for string and get count in vi editor

You need the n flag. To count words use:

:%s/\i\+/&/gn   

and a particular word:

:%s/the/&/gn        

See count-items documentation section.

If you simply type in:

%s/pattern/pattern/g

then the status line will give you the number of matches in vi as well.

Can you install and run apps built on the .NET framework on a Mac?

Yes you can!

As of November 2016, Microsoft now has integrated .NET Core in it's official .NET Site

They even have a new Visual Studio app that runs on MacOS

How to print_r $_POST array?

Why are you wrapping the $_POST array in an array?

You can access your "id" and "value" arrays using the following

// assuming the appropriate isset() checks for $_POST['id'] and $_POST['value']

$ids = $_POST['id'];
$values = $_POST['value'];

foreach ($ids as $idx => $id) {
    // ...
}

foreach ($values as $idx => $value) {
    // ...
}

Is it possible to define more than one function per file in MATLAB, and access them from outside that file?

I really like SCFrench's answer - I would like to point out that it can easily be modified to import the functions directly to the workspace using the assignin function. (Doing it like this reminds me a lot of Python's "import x from y" way of doing things)

function message = makefuns
  assignin('base','fun1',@fun1);
  assignin('base','fun2',@fun2);
  message='Done importing functions to workspace';
end

function y=fun1(x)
  y=x;
end

function z=fun2
  z=1;
end

And then used thusly:

>> makefuns
ans =
Done importing functions to workspace

>> fun1(123)
ans =
   123

>> fun2()
ans =
     1

How can I update a row in a DataTable in VB.NET?

The problem you're running into is that you're trying to replace an entire row object. That is not allowed by the DataTable API. Instead you have to update the values in the columns of a row object. Or add a new row to the collection.

To update the column of a particular row you can access it by name or index. For instance you could write the following code to update the column "Foo" to be the value strVerse

dtResult.Rows(i)("Foo") = strVerse

Raise to power in R

1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math

2: Yes: But you already know it:

`^`(x,y)
#[1] 1024

In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math.

Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply and sapply:

> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4

How to loop through all but the last item of a list?

This answers what the OP should have asked, i.e. traverse a list comparing consecutive elements (excellent SilentGhost answer), yet generalized for any group (n-gram): 2, 3, ... n:

zip(*(l[start:] for start in range(0, n)))

Examples:

l = range(0, 4)  # [0, 1, 2, 3]

list(zip(*(l[start:] for start in range(0, 2)))) # == [(0, 1), (1, 2), (2, 3)]
list(zip(*(l[start:] for start in range(0, 3)))) # == [(0, 1, 2), (1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 4)))) # == [(0, 1, 2, 3)]
list(zip(*(l[start:] for start in range(0, 5)))) # == []

Explanations:

  • l[start:] generates a a list/generator starting from index start
  • *list or *generator: passes all elements to the enclosing function zip as if it was written zip(elem1, elem2, ...)

Note:

AFAIK, this code is as lazy as it can be. Not tested.

FPDF utf-8 encoding (HOW-TO)

None of the above solutions are going to work.

Try this:

function filter_html($value){
    $value = mb_convert_encoding($value, 'ISO-8859-1', 'UTF-8');
    return $value;
}

Where is the Query Analyzer in SQL Server Management Studio 2008 R2?

You can use Database Engine Tuning Advisor.

This tool is for improving the query performances by examining the way queries are processed and recommended enhancements by specific indexes.

How to use the Database Engine Tuning Advisor?

1- Copy the select statement that you need to speed up into the new query.

2- Parse (Ctrl+F5).

3- Press The Icon of the (Database Engine Tuning Advisor).

Importing Excel spreadsheet data into another Excel spreadsheet containing VBA

Data can be pulled into an excel from another excel through Workbook method or External reference or through Data Import facility.

If you want to read or even if you want to update another excel workbook, these methods can be used. We may not depend only on VBA for this.

For more info on these techniques, please click here to refer the article

Map.Entry: How to use it?

_x000D_
_x000D_
public HashMap<Integer,Obj> ListeObj= new HashMap<>();

public void addObj(String param1, String param2, String param3){
  Obj newObj = new Obj(param1, param2, param3);
  this.ListObj.put(newObj.getId(), newObj);
}

public ArrayList<Integer> searchdObj (int idObj){
  ArrayList<Integer> returnList = new ArrayList<>();
  for (java.util.Map.Entry<Integer, Obj> e : this.ListObj.entrySet()){
    if(e.getValue().getName().equals(idObj)) {
      returnList.add(e.getKey());
    }
  }
return returnList;
}
_x000D_
_x000D_
_x000D_

"Uncaught Error: [$injector:unpr]" with angular after deployment

Ran into the same problem myself, but my controller definitions looked a little different than above. For controllers defined like this:

function MyController($scope, $http) {
    // ...
}

Just add a line after the declaration indicating which objects to inject when the controller is instantiated:

function MyController($scope, $http) {
    // ...
}
MyController.$inject = ['$scope', '$http'];

This makes it minification-safe.

LDAP: error code 49 - 80090308: LdapErr: DSID-0C0903A9, comment: AcceptSecurityContext error, data 52e, v1db1

if you debug and loook at ctx=null,maybe your username hava proble ,you shoud write like "ac\administrator"(double "\") or "administrator@ac"

Make WPF Application Fullscreen (Cover startmenu)

If you want user to change between WindowStyle.SingleBorderWindow and WindowStyle.None at runtime you can bring this at code behind:

Make application fullscreen:

RootWindow.Visibility = Visibility.Collapsed;
RootWindow.WindowStyle = WindowStyle.None;
RootWindow.ResizeMode = ResizeMode.NoResize;
RootWindow.WindowState = WindowState.Maximized;
RootWindow.Topmost = true;
RootWindow.Visibility = Visibility.Visible;

Return to single border style:

RootWindow.WindowStyle = WindowStyle.SingleBorderWindow;
RootWindow.ResizeMode = ResizeMode.CanResize;
RootWindow.Topmost = false;

Note that without RootWindow.Visibility property your window will not cover start menu, however you can skip this step if you making application fullscreen once at startup.

Github permission denied: ssh add agent has no identities

Full details in this answer.

In summary, when ssh-add -l returns “The agent has no identities”, it means that keys used by ssh (stored in files such as ~/.ssh/id_rsa, ~/.ssh/id_dsa, etc.) are either missing, they are not known to ssh-agent, which is the authentication agent, or that their permissions are set incorrectly (for example, world writable).

If your keys are missing or if you have not generated any, use ssh-keygen -t rsa, then ssh-add to add them.

If keys exist but are not known to ssh-agent (like if they are in a non-standard folder), use ssh-add /path/to/my-non-standard-ssh-folder/id_rsa to add them.

See this answer if you are having trouble with ssh-add or ssh-agent.

Python Infinity - Any caveats?

Python's implementation follows the IEEE-754 standard pretty well, which you can use as a guidance, but it relies on the underlying system it was compiled on, so platform differences may occur. Recently¹, a fix has been applied that allows "infinity" as well as "inf", but that's of minor importance here.

The following sections equally well apply to any language that implements IEEE floating point arithmetic correctly, it is not specific to just Python.

Comparison for inequality

When dealing with infinity and greater-than > or less-than < operators, the following counts:

  • any number including +inf is higher than -inf
  • any number including -inf is lower than +inf
  • +inf is neither higher nor lower than +inf
  • -inf is neither higher nor lower than -inf
  • any comparison involving NaN is false (inf is neither higher, nor lower than NaN)

Comparison for equality

When compared for equality, +inf and +inf are equal, as are -inf and -inf. This is a much debated issue and may sound controversial to you, but it's in the IEEE standard and Python behaves just like that.

Of course, +inf is unequal to -inf and everything, including NaN itself, is unequal to NaN.

Calculations with infinity

Most calculations with infinity will yield infinity, unless both operands are infinity, when the operation division or modulo, or with multiplication with zero, there are some special rules to keep in mind:

  • when multiplied by zero, for which the result is undefined, it yields NaN
  • when dividing any number (except infinity itself) by infinity, which yields 0.0 or -0.0².
  • when dividing (including modulo) positive or negative infinity by positive or negative infinity, the result is undefined, so NaN.
  • when subtracting, the results may be surprising, but follow common math sense:
    • when doing inf - inf, the result is undefined: NaN;
    • when doing inf - -inf, the result is inf;
    • when doing -inf - inf, the result is -inf;
    • when doing -inf - -inf, the result is undefined: NaN.
  • when adding, it can be similarly surprising too:
    • when doing inf + inf, the result is inf;
    • when doing inf + -inf, the result is undefined: NaN;
    • when doing -inf + inf, the result is undefined: NaN;
    • when doing -inf + -inf, the result is -inf.
  • using math.pow, pow or ** is tricky, as it doesn't behave as it should. It throws an overflow exception when the result with two real numbers is too high to fit a double precision float (it should return infinity), but when the input is inf or -inf, it behaves correctly and returns either inf or 0.0. When the second argument is NaN, it returns NaN, unless the first argument is 1.0. There are more issues, not all covered in the docs.
  • math.exp suffers the same issues as math.pow. A solution to fix this for overflow is to use code similar to this:

    try:
        res = math.exp(420000)
    except OverflowError:
        res = float('inf')
    

Notes

Note 1: as an additional caveat, that as defined by the IEEE standard, if your calculation result under-or overflows, the result will not be an under- or overflow error, but positive or negative infinity: 1e308 * 10.0 yields inf.

Note 2: because any calculation with NaN returns NaN and any comparison to NaN, including NaN itself is false, you should use the math.isnan function to determine if a number is indeed NaN.

Note 3: though Python supports writing float('-NaN'), the sign is ignored, because there exists no sign on NaN internally. If you divide -inf / +inf, the result is NaN, not -NaN (there is no such thing).

Note 4: be careful to rely on any of the above, as Python relies on the C or Java library it was compiled for and not all underlying systems implement all this behavior correctly. If you want to be sure, test for infinity prior to doing your calculations.

¹) Recently means since version 3.2.
²) Floating points support positive and negative zero, so: x / float('inf') keeps its sign and -1 / float('inf') yields -0.0, 1 / float(-inf) yields -0.0, 1 / float('inf') yields 0.0 and -1/ float(-inf) yields 0.0. In addition, 0.0 == -0.0 is true, you have to manually check the sign if you don't want it to be true.

Is Django for the frontend or backend?

Neither.

Django is a framework, not a language. Python is the language in which Django is written.

Django is a collection of Python libs allowing you to quickly and efficiently create a quality Web application, and is suitable for both frontend and backend.

However, Django is pretty famous for its "Django admin", an auto generated backend that allows you to manage your website in a blink for a lot of simple use cases without having to code much.

More precisely, for the front end, Django helps you with data selection, formatting, and display. It features URL management, a templating language, authentication mechanisms, cache hooks, and various navigation tools such as paginators.

For the backend, Django comes with an ORM that lets you manipulate your data source with ease, forms (an HTML independent implementation) to process user input and validate data and signals, and an implementation of the observer pattern. Plus a tons of use-case specific nifty little tools.

For the rest of the backend work Django doesn't help with, you just use regular Python. Business logic is a pretty broad term.

You probably want to know as well that Django comes with the concept of apps, a self contained pluggable Django library that solves a problem. The Django community is huge, and so there are numerous apps that do specific business logic that vanilla Django doesn't.

Why Local Users and Groups is missing in Computer Management on Windows 10 Home?

Windows 10 Home Edition does not have Local Users and Groups option so that is the reason you aren't able to see that in Computer Management.

You can use User Accounts by pressing Window+R, typing netplwiz and pressing OK as described here.

What's the best CRLF (carriage return, line feed) handling strategy with Git?

Try setting the core.autocrlf configuration option to true. Also have a look at the core.safecrlf option.

Actually it sounds like core.safecrlf might already be set in your repository, because (emphasis mine):

If this is not the case for the current setting of core.autocrlf, git will reject the file.

If this is the case, then you might want to check that your text editor is configured to use line endings consistently. You will likely run into problems if a text file contains a mixture of LF and CRLF line endings.

Finally, I feel that the recommendation to simply "use what you're given" and use LF terminated lines on Windows will cause more problems than it solves. Git has the above options to try to handle line endings in a sensible way, so it makes sense to use them.

Display progress bar while doing some work in C#?

Reading your requirements the simplest way would be to display a mode-less form and use a standard System.Windows.Forms timer to update the progress on the mode-less form. No threads, no possible memory leaks.

As this only uses the one UI thread, you would also need to call Application.DoEvents() at certain points during your main processing to guarantee the progress bar is updated visually.

%matplotlib line magic causes SyntaxError in Python script

Line magics are only supported by the IPython command line. They cannot simply be used inside a script, because %something is not correct Python syntax.

If you want to do this from a script you have to get access to the IPython API and then call the run_line_magic function.

Instead of %matplotlib inline, you will have to do something like this in your script:

from IPython import get_ipython
get_ipython().run_line_magic('matplotlib', 'inline')

A similar approach is described in this answer, but it uses the deprecated magic function.

Note that the script still needs to run in IPython. Under vanilla Python the get_ipython function returns None and get_ipython().run_line_magic will raise an AttributeError.

What is the difference between call and apply?

Both call and apply the same way. It calls immediately when we use call and apply.

Both call and apply takes "this" parameter as the first argument and the second argument only differs.

the call takes the arguments of the functions as a list (comma ) Apply takes the arguments of the functions as an array.

You can find the complete difference between bind, call, and apply in the bellow youtube video.

https://www.youtube.com/watch?v=G-EfxnG0DtY&t=180s

How to update a single library with Composer?

Difference between install, update and require

Assume the following scenario:

composer.json

"parsecsv/php-parsecsv": "0.*"

composer.lock file

  "name": "parsecsv/php-parsecsv",
            "version": "0.1.4",

Latest release is 1.1.0. The latest 0.* release is 0.3.2

install: composer install parsecsv/php-parsecsv

This will install version 0.1.4 as specified in the lock file

update: composer update parsecsv/php-parsecsv

This will update the package to 0.3.2. The highest version with respect to your composer.json. The entry in composer.lock will be updated.

require: composer require parsecsv/php-parsecsv

This will update or install the newest version 1.1.0. Your composer.lock file and composer.json file will be updated as well.

Java multiline string

Use Properties.loadFromXML(InputStream). There's no need for external libs.

Better than a messy code (since maintainability and design are your concern), it is preferable not to use long strings.

Start by reading xml properties:

 InputStream fileIS = YourClass.class.getResourceAsStream("MultiLine.xml");
 Properties prop = new Properies();
 prop.loadFromXML(fileIS);


then you can use your multiline string in a more maintainable way...

static final String UNIQUE_MEANINGFUL_KEY = "Super Duper UNIQUE Key";
prop.getProperty(UNIQUE_MEANINGFUL_KEY) // "\n    MEGA\n   LONG\n..."


MultiLine.xml` gets located in the same folder YourClass:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">

<properties>
    <entry key="Super Duper UNIQUE Key">
       MEGA
       LONG
       MULTILINE
    </entry>
</properties>

PS.: You can use <![CDATA[" ... "]]> for xml-like string.

Sort a Custom Class List<T>

You are correct that your cTag class must implement IComparable<T> interface. Then you can just call Sort() on your list.

To implement IComparable<T> interface, you must implement CompareTo(T other) method. The easiest way to do this is to call CompareTo method of the field you want to compare, which in your case is date.

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public string date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

However, this wouldn't sort well, because this would use classic sorting on strings (since you declared date as string). So I think the best think to do would be to redefine the class and to declare date not as string, but as DateTime. The code would stay almost the same:

public class cTag:IComparable<cTag> {
    public int id { get; set; }
    public int regnumber { get; set; }
    public DateTime date { get; set; }
    public int CompareTo(cTag other) {
        return date.CompareTo(other.date);
    }
}

Only thing you'd have to do when creating the instance of the class to convert your string containing the date into DateTime type, but it can be done easily e.g. by DateTime.Parse(String) method.

Converting HTML string into DOM elements?

Why not use insertAdjacentHTML

for example:

// <div id="one">one</div> 
var d1 = document.getElementById('one'); 
d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');

// At this point, the new structure is:
// <div id="one">one</div><div id="two">two</div>here

Using floats with sprintf() in embedded C

Since you're on an embedded platform, it's quite possible that you don't have the full range of capabilities from the printf()-style functions.

Assuming you have floats at all (still not necessarily a given for embedded stuff), you can emulate it with something like:

char str[100];
float adc_read = 678.0123;

char *tmpSign = (adc_read < 0) ? "-" : "";
float tmpVal = (adc_read < 0) ? -adc_read : adc_read;

int tmpInt1 = tmpVal;                  // Get the integer (678).
float tmpFrac = tmpVal - tmpInt1;      // Get fraction (0.0123).
int tmpInt2 = trunc(tmpFrac * 10000);  // Turn into integer (123).

// Print as parts, note that you need 0-padding for fractional bit.

sprintf (str, "adc_read = %s%d.%04d\n", tmpSign, tmpInt1, tmpInt2);

You'll need to restrict how many characters come after the decimal based on the sizes of your integers. For example, with a 16-bit signed integer, you're limited to four digits (9,999 is the largest power-of-ten-minus-one that can be represented).

However, there are ways to handle this by further processing the fractional part, shifting it by four decimal digits each time (and using/subtracting the integer part) until you have the precision you desire.


Update:

One final point you mentioned that you were using avr-gcc in a response to one of the other answers. I found the following web page that seems to describe what you need to do to use %f in your printf() statements here.

As I originally suspected, you need to do some extra legwork to get floating point support. This is because embedded stuff rarely needs floating point (at least none of the stuff I've ever done). It involves setting extra parameters in your makefile and linking with extra libraries.

However, that's likely to increase your code size quite a bit due to the need to handle general output formats. If you can restrict your float outputs to 4 decimal places or less, I'd suggest turning my code into a function and just using that - it's likely to take up far less room.

In case that link ever disappears, what you have to do is ensure that your gcc command has "-Wl,-u,vfprintf -lprintf_flt -lm". This translates to:

  • force vfprintf to be initially undefined (so that the linker has to resolve it).
  • specify the floating point printf() library for searching.
  • specify the math library for searching.

Using jQuery's ajax method to retrieve images as a blob

If you need to handle error messages using jQuery.AJAX you will need to modify the xhr function so the responseType is not being modified when an error happens.

So you will have to modify the responseType to "blob" only if it is a successful call:

$.ajax({
    ...
    xhr: function() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function() {
            if (xhr.readyState == 2) {
                if (xhr.status == 200) {
                    xhr.responseType = "blob";
                } else {
                    xhr.responseType = "text";
                }
            }
        };
        return xhr;
    },
    ...
    error: function(xhr, textStatus, errorThrown) {
        // Here you are able now to access to the property "responseText"
        // as you have the type set to "text" instead of "blob".
        console.error(xhr.responseText);
    },
    success: function(data) {
        console.log(data); // Here is "blob" type
    }
});

Note

If you debug and place a breakpoint at the point right after setting the xhr.responseType to "blob" you can note that if you try to get the value for responseText you will get the following message:

The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

How do I create directory if it doesn't exist to create a file?

As @hitec said, you have to be sure that you have the right permissions, if you do, you can use this line to ensure the existence of the directory:

Directory.CreateDirectory(Path.GetDirectoryName(filePath))

Divide a number by 3 without using *, /, +, -, % operators

Using a Linux shell script:

#include <stdio.h>
int main()
{
    int number = 30;
    char command[25];
    snprintf(command, 25, "echo $((%d %c 3)) ", number, 47);
    system( command );
    return 0;
}

See my another answer.

How to convert an XML file to nice pandas dataframe?

You can easily use xml (from the Python standard library) to convert to a pandas.DataFrame. Here's what I would do (when reading from a file replace xml_data with the name of your file or file object):

import pandas as pd
import xml.etree.ElementTree as ET
import io

def iter_docs(author):
    author_attr = author.attrib
    for doc in author.iter('document'):
        doc_dict = author_attr.copy()
        doc_dict.update(doc.attrib)
        doc_dict['data'] = doc.text
        yield doc_dict

xml_data = io.StringIO(u'''\
<author type="XXX" language="EN" gender="xx" feature="xx" web="foobar.com">
    <documents count="N">
        <document KEY="e95a9a6c790ecb95e46cf15bee517651" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="bc360cfbafc39970587547215162f0db" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="19e71144c50a8b9160b3f0955e906fce" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="21d4af9021a174f61b884606c74d9e42" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="28a45eb2460899763d709ca00ddbb665" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="a0c0712a6a351f85d9f5757e9fff8946" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="626726ba8d34d15d02b6d043c55fe691" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...]
]]>
        </document>
        <document KEY="2cb473e0f102e2e4a40aa3006e412ae4" web="www.foo_bar_exmaple.com"><![CDATA[A large text with lots of strings and punctuations symbols [...] [...]
]]>
        </document>
    </documents>
</author>
''')

etree = ET.parse(xml_data) #create an ElementTree object 
doc_df = pd.DataFrame(list(iter_docs(etree.getroot())))

If there are multiple authors in your original document or the root of your XML is not an author, then I would add the following generator:

def iter_author(etree):
    for author in etree.iter('author'):
        for row in iter_docs(author):
            yield row

and change doc_df = pd.DataFrame(list(iter_docs(etree.getroot()))) to doc_df = pd.DataFrame(list(iter_author(etree)))

Have a look at the ElementTree tutorial provided in the xml library documentation.

Writing a list to a file with Python

Because i'm lazy....

import json
a = [1,2,3]
with open('test.txt', 'w') as f:
    f.write(json.dumps(a))

#Now read the file back into a Python list object
with open('test.txt', 'r') as f:
    a = json.loads(f.read())

Create an array of integers property in Objective-C

This should work:

@interface MyClass
{
    int _doubleDigits[10]; 
}

@property(readonly) int *doubleDigits;

@end

@implementation MyClass

- (int *)doubleDigits
{
    return _doubleDigits;
}

@end

Is there any way to delete local commits in Mercurial?

Modern answer (only relevant after Mercurial 2.1):

Use Phases and mark the revision(s) that you don't want to share as secret (private). That way when you push they won't get sent.

In TortoiseHG you can right click on a commit to change its phase.

Also: You can also use the extension "rebase" to move your local commits to the head of the shared repository after you pull.

How can I hide or encrypt JavaScript code?

The only safe way to protect your code is not giving it away. With client deployment, there is no avoiding the client having access to the code.

So the short answer is: You can't do it

The longer answer is considering flash or Silverlight. Although I believe silverlight will gladly give away it's secrets with reflector running on the client.

I'm not sure if something simular exists with the flash platform.

MongoDB distinct aggregation

SQL Query: (group by & count of distinct)

select city,count(distinct(emailId)) from TransactionDetails group by city;

Equivalent mongo query would look like this:

db.TransactionDetails.aggregate([ 
{$group:{_id:{"CITY" : "$cityName"},uniqueCount: {$addToSet: "$emailId"}}},
{$project:{"CITY":1,uniqueCustomerCount:{$size:"$uniqueCount"}} } 
]);

How to change TIMEZONE for a java.util.Calendar/Date

In Java, Dates are internally represented in UTC milliseconds since the epoch (so timezones are not taken into account, that's why you get the same results, as getTime() gives you the mentioned milliseconds).
In your solution:

Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
long gmtTime = cSchedStartCal.getTime().getTime();

long timezoneAlteredTime = gmtTime + TimeZone.getTimeZone("Asia/Calcutta").getRawOffset();
Calendar cSchedStartCal1 = Calendar.getInstance(TimeZone.getTimeZone("Asia/Calcutta"));
cSchedStartCal1.setTimeInMillis(timezoneAlteredTime);

you just add the offset from GMT to the specified timezone ("Asia/Calcutta" in your example) in milliseconds, so this should work fine.

Another possible solution would be to utilise the static fields of the Calendar class:

//instantiates a calendar using the current time in the specified timezone
Calendar cSchedStartCal = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
//change the timezone
cSchedStartCal.setTimeZone(TimeZone.getTimeZone("Asia/Calcutta"));
//get the current hour of the day in the new timezone
cSchedStartCal.get(Calendar.HOUR_OF_DAY);

Refer to stackoverflow.com/questions/7695859/ for a more in-depth explanation.

How to configure Docker port mapping to use Nginx as an upstream proxy?

I tried using the popular Jason Wilder reverse proxy that code-magically works for everyone, and learned that it doesn't work for everyone (ie: me). And I'm brand new to NGINX, and didn't like that I didn't understand the technologies I was trying to use.

Wanted to add my 2 cents, because the discussion above around linking containers together is now dated since it is a deprecated feature. So here's an explanation on how to do it using networks. This answer is a full example of setting up nginx as a reverse proxy to a statically paged website using Docker Compose and nginx configuration.

TL;DR;

Add the services that need to talk to each other onto a predefined network. For a step-by-step discussion on Docker networks, I learned some things here: https://technologyconversations.com/2016/04/25/docker-networking-and-dns-the-good-the-bad-and-the-ugly/

Define the Network

First of all, we need a network upon which all your backend services can talk on. I called mine web but it can be whatever you want.

docker network create web

Build the App

We'll just do a simple website app. The website is a simple index.html page being served by an nginx container. The content is a mounted volume to the host under a folder content

DockerFile:

FROM nginx
COPY default.conf /etc/nginx/conf.d/default.conf

default.conf

server {
    listen       80;
    server_name  localhost;

    location / {
        root   /var/www/html;
        index  index.html index.htm;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/share/nginx/html;
    }
}

docker-compose.yml

version: "2"

networks:
  mynetwork:
    external:
      name: web

services:
  nginx:
    container_name: sample-site
    build: .
    expose:
      - "80"
    volumes:
      - "./content/:/var/www/html/"
    networks:
      default: {}
      mynetwork:
        aliases:
          - sample-site

Note that we no longer need port mapping here. We simple expose port 80. This is handy for avoiding port collisions.

Run the App

Fire this website up with

docker-compose up -d

Some fun checks regarding the dns mappings for your container:

docker exec -it sample-site bash
ping sample-site

This ping should work, inside your container.

Build the Proxy

Nginx Reverse Proxy:

Dockerfile

FROM nginx

RUN rm /etc/nginx/conf.d/*

We reset all the virtual host config, since we're going to customize it.

docker-compose.yml

version: "2"

networks:
  mynetwork:
    external:
      name: web


services:
  nginx:
    container_name: nginx-proxy
    build: .
    ports:
      - "80:80"
      - "443:443"
    volumes:
      - ./conf.d/:/etc/nginx/conf.d/:ro
      - ./sites/:/var/www/
    networks:
      default: {}
      mynetwork:
        aliases:
          - nginx-proxy

Run the Proxy

Fire up the proxy using our trusty

docker-compose up -d

Assuming no issues, then you have two containers running that can talk to each other using their names. Let's test it.

docker exec -it nginx-proxy bash
ping sample-site
ping nginx-proxy

Set up Virtual Host

Last detail is to set up the virtual hosting file so the proxy can direct traffic based on however you want to set up your matching:

sample-site.conf for our virtual hosting config:

  server {
    listen 80;
    listen [::]:80;

    server_name my.domain.com;

    location / {
      proxy_pass http://sample-site;
    }

  }

Based on how the proxy was set up, you'll need this file stored under your local conf.d folder which we mounted via the volumes declaration in the docker-compose file.

Last but not least, tell nginx to reload it's config.

docker exec nginx-proxy service nginx reload

These sequence of steps is the culmination of hours of pounding head-aches as I struggled with the ever painful 502 Bad Gateway error, and learning nginx for the first time, since most of my experience was with Apache.

This answer is to demonstrate how to kill the 502 Bad Gateway error that results from containers not being able to talk to one another.

I hope this answer saves someone out there hours of pain, since getting containers to talk to each other was really hard to figure out for some reason, despite it being what I expected to be an obvious use-case. But then again, me dumb. And please let me know how I can improve this approach.

How to extract the first two characters of a string in shell scripting?

Probably the most efficient method, if you're using the bash shell (and you appear to be, based on your comments), is to use the sub-string variant of parameter expansion:

pax> long="USCAGol.blah.blah.blah"
pax> short="${long:0:2}" ; echo "${short}"
US

This will set short to be the first two characters of long. If long is shorter than two characters, short will be identical to it.

This in-shell method is usually better if you're going to be doing it a lot (like 50,000 times per report as you mention) since there's no process creation overhead. All solutions which use external programs will suffer from that overhead.

If you also wanted to ensure a minimum length, you could pad it out before hand with something like:

pax> long="A"
pax> tmpstr="${long}.."
pax> short="${tmpstr:0:2}" ; echo "${short}"
A.

This would ensure that anything less than two characters in length was padded on the right with periods (or something else, just by changing the character used when creating tmpstr). It's not clear that you need this but I thought I'd put it in for completeness.


Having said that, there are any number of ways to do this with external programs (such as if you don't have bash available to you), some of which are:

short=$(echo "${long}" | cut -c1-2)
short=$(echo "${long}" | head -c2)
short=$(echo "${long}" | awk '{print substr ($0, 0, 2)}'
short=$(echo "${long}" | sed 's/^\(..\).*/\1/')

The first two (cut and head) are identical for a single-line string - they basically both just give you back the first two characters. They differ in that cut will give you the first two characters of each line and head will give you the first two characters of the entire input

The third one uses the awk sub-string function to extract the first two characters and the fourth uses sed capture groups (using () and \1) to capture the first two characters and replace the entire line with them. They're both similar to cut - they deliver the first two characters of each line in the input.

None of that matters if you are sure your input is a single line, they all have an identical effect.

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" from php function

Here maybe?

I believe that the code should be:


$connect = new mysqli("host", "root", "", "dbname");

because root does not have a password. the (using password: YES) is saying "you're using a password with this user"

Model summary in pytorch

AFAK there is no model.summary() like equivalent in pytorch

Meanwhile you can refer script by szagoruyko, which gives a nice visualizaton like in resnet18-example

Cheers

VBA - Select columns using numbers?

you can use range with cells to get the effect you want (but it would be better not to use select if you don't have to)

For n = 1 to 5
range(cells(1,n).entirecolumn,cells(1,n+4).entirecolumn).Select
do sth
next n

Xpath for href element

have you tried:

//a[@id='oldcontent']/u[text()='Re-Call']

How to Test Facebook Connect Locally

Create 2 apps and

In /initializers/env_variables.rb

if Rails.env == 'development'
    ENV['FB_APP_ID'] = "HERE"
    ENV["FB_SECRET"] = "HERE"
else
    ENV['FB_APP_ID'] = "HERE"
    ENV["FB_SECRET"] = "HERE"
end

How can I kill whatever process is using port 8080 so that I can vagrant up?

This might help

lsof -n -i4TCP:8080 

The PID is the second field in the output.

Or try:

lsof -i -P

Best way to determine user's locale within browser

I used all the answers and created a single line solution:

const getLanguage = () => navigator.userLanguage || (navigator.languages && navigator.languages.length && navigator.languages[0]) || navigator.language || navigator.browserLanguage || navigator.systemLanguage || 'en';

console.log(getLanguage());

Sorting arrays in NumPy by column

Here is another solution considering all columns (more compact way of J.J's answer);

ar=np.array([[0, 0, 0, 1],
             [1, 0, 1, 0],
             [0, 1, 0, 0],
             [1, 0, 0, 1],
             [0, 0, 1, 0],
             [1, 1, 0, 0]])

Sort with lexsort,

ar[np.lexsort(([ar[:, i] for i in range(ar.shape[1]-1, -1, -1)]))]

Output:

array([[0, 0, 0, 1],
       [0, 0, 1, 0],
       [0, 1, 0, 0],
       [1, 0, 0, 1],
       [1, 0, 1, 0],
       [1, 1, 0, 0]])

How to create PDF files in Python

fpdf works well for me. Much simpler than ReportLab and really free. Works with UTF-8.

Column calculated from another column?

MySQL 5.7 supports computed columns. They call it "Generated Columns" and the syntax is a little weird, but it supports the same options I see in other databases.

https://dev.mysql.com/doc/refman/5.7/en/create-table.html#create-table-generated-columns

How do I update a model value in JavaScript in a Razor view?

You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.

It would look something like this:

function updatePostID(val, comment)
{

    var args = {};
    args.PostID = val;
    args.Comment = comment;

    $.ajax({
     type: "POST",
     url: controllerActionMethodUrlHere,
     contentType: "application/json; charset=utf-8",
     data: args,
     dataType: "json",
     success: function(msg) 
     {
        // Something afterwards here

     }
    });

}

Changing the sign of a number in PHP?

re the edit: "Also i need a way to do the reverse If the float is a negative, make it a positive"

$number = -$number;

changes the number to its opposite.

Connection timeout for SQL server

Yes, you could append ;Connection Timeout=30 to your connection string and specify the value you wish.

The timeout value set in the Connection Timeout property is a time expressed in seconds. If this property isn't set, the timeout value for the connection is the default value (15 seconds).

Moreover, setting the timeout value to 0, you are specifying that your attempt to connect waits an infinite time. As described in the documentation, this is something that you shouldn't set in your connection string:

A value of 0 indicates no limit, and should be avoided in a ConnectionString because an attempt to connect waits indefinitely.

How large is a DWORD with 32- and 64-bit code?

It is defined as:

typedef unsigned long       DWORD;

However, according to the MSDN:

On 32-bit platforms, long is synonymous with int.

Therefore, DWORD is 32bit on a 32bit operating system. There is a separate define for a 64bit DWORD:

typdef unsigned _int64 DWORD64;

Hope that helps.

What does FETCH_HEAD in Git mean?

As mentioned in Jonathan's answer, FETCH_HEAD corresponds to the file .git/FETCH_HEAD. Typically, the file will look like this:

71f026561ddb57063681109aadd0de5bac26ada9                        branch 'some-branch' of <remote URL>
669980e32769626587c5f3c45334fb81e5f44c34        not-for-merge   branch 'some-other-branch' of <remote URL>
b858c89278ab1469c71340eef8cf38cc4ef03fed        not-for-merge   branch 'yet-some-other-branch' of <remote URL>

Note how all branches but one are marked not-for-merge. The odd one out is the branch that was checked out before the fetch. In summary: FETCH_HEAD essentially corresponds to the remote version of the branch that's currently checked out.

Tensorflow image reading & display

I used CIFAR10 format instead of STL10 and code came out like

filename_queue = tf.train.string_input_producer(filenames)
read_input = read_cifar10(filename_queue)
with tf.Session() as sess:       
    tf.train.start_queue_runners(sess=sess)
    result = sess.run(read_input.uint8image)        
img = Image.fromarray(result, "RGB")    
img.save('my.jpg')

The snippet is identical with mttk and Rosa Gronchi, but Somehow I wasn't able to show the image during run-time, so I saved as the JPG file.

How to add the JDBC mysql driver to an Eclipse project?

You can paste the .jar file of the driver in the Java setup instead of adding it to each project that you create. Paste it in C:\Program Files\Java\jre7\lib\ext or wherever you have installed java.

After this you will find that the .jar driver is enlisted in the library folder of your created project(JRE system library) in the IDE. No need to add it repetitively.

Efficient thresholding filter of an array with numpy

b = a[a>threshold] this should do

I tested as follows:

import numpy as np, datetime
# array of zeros and ones interleaved
lrg = np.arange(2).reshape((2,-1)).repeat(1000000,-1).flatten()

t0 = datetime.datetime.now()
flt = lrg[lrg==0]
print datetime.datetime.now() - t0

t0 = datetime.datetime.now()
flt = np.array(filter(lambda x:x==0, lrg))
print datetime.datetime.now() - t0

I got

$ python test.py
0:00:00.028000
0:00:02.461000

http://docs.scipy.org/doc/numpy/user/basics.indexing.html#boolean-or-mask-index-arrays

Is there any difference between a GUID and a UUID?

GUID is Microsoft's implementation of the UUID standard.

Per Wikipedia:

The term GUID usually refers to Microsoft's implementation of the Universally Unique Identifier (UUID) standard.

An updated quote from that same Wikipedia article:

RFC 4122 itself states that UUIDs "are also known as GUIDs". All this suggests that "GUID", while originally referring to a variant of UUID used by Microsoft, has become simply an alternative name for UUID…

How can I get javascript to read from a .json file?

NOTICE: AS OF JULY 12TH, 2018, THE OTHER ANSWERS ARE ALL OUTDATED. JSONP IS NOW CONSIDERED A TERRIBLE IDEA

If you have your JSON as a string, JSON.parse() will work fine. Since you are loading the json from a file, you will need to do a XMLHttpRequest to it. For example (This is w3schools.com example):

_x000D_
_x000D_
var xmlhttp = new XMLHttpRequest();_x000D_
xmlhttp.onreadystatechange = function() {_x000D_
    if (this.readyState == 4 && this.status == 200) {_x000D_
        var myObj = JSON.parse(this.responseText);_x000D_
        document.getElementById("demo").innerHTML = myObj.name;_x000D_
    }_x000D_
};_x000D_
xmlhttp.open("GET", "json_demo.txt", true);_x000D_
xmlhttp.send();
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<body>_x000D_
_x000D_
<h2>Use the XMLHttpRequest to get the content of a file.</h2>_x000D_
<p>The content is written in JSON format, and can easily be converted into a JavaScript object.</p>_x000D_
_x000D_
<p id="demo"></p>_x000D_
_x000D_
_x000D_
<p>Take a look at <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

It will not work here as that file isn't located here. Go to this w3schools example though: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax

Here is the documentation for JSON.parse(): https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Here's a summary:

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

Here's the example used:

_x000D_
_x000D_
var json = '{"result":true, "count":42}';_x000D_
obj = JSON.parse(json);_x000D_
_x000D_
console.log(obj.count);_x000D_
// expected output: 42_x000D_
_x000D_
console.log(obj.result);_x000D_
// expected output: true
_x000D_
_x000D_
_x000D_

Here is a summary on XMLHttpRequests from https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest:

Use XMLHttpRequest (XHR) objects to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing. XMLHttpRequest is used heavily in Ajax programming.

If you don't want to use XMLHttpRequests, then a JQUERY way (which I'm not sure why it isn't working for you) is http://api.jquery.com/jQuery.getJSON/

Since it isn't working, I'd try using XMLHttpRequests

You could also try AJAX requests:

$.ajax({
    'async': false,
    'global': false,
    'url': "/jsonfile.json",
    'dataType': "json",
    'success': function (data) {
        // do stuff with data
    }
});

Documentation: http://api.jquery.com/jquery.ajax/

How can you speed up Eclipse?

Disable virus scanners, or at least configure any virus scanner to not scan JAR files on read access.

What’s the best way to get an HTTP response code from a URL?

Here's a solution that uses httplib instead.

import httplib

def get_status_code(host, path="/"):
    """ This function retreives the status code of a website by requesting
        HEAD data from the host. This means that it only requests the headers.
        If the host cannot be reached or something else goes wrong, it returns
        None instead.
    """
    try:
        conn = httplib.HTTPConnection(host)
        conn.request("HEAD", path)
        return conn.getresponse().status
    except StandardError:
        return None


print get_status_code("stackoverflow.com") # prints 200
print get_status_code("stackoverflow.com", "/nonexistant") # prints 404

NodeJS: How to get the server's port?

const express = require('express');                                                                                                                           
const morgan = require('morgan')
const PORT = 3000;

morgan.token('port', (req) => { 
    return req.app.locals.port; 
});

const app = express();
app.locals.port = PORT;
app.use(morgan(':method :url :port'))
app.get('/app', function(req, res) {
    res.send("Hello world from server");
});

app1.listen(PORT);

Creating a new dictionary in Python

d = dict()

or

d = {}

or

import types
d = types.DictType.__new__(types.DictType, (), {})

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

If you're on Linux, or have cygwin available on Windows, you can run the input XML through a simple sed script that will replace <Active>True</Active> with <Active>true</Active>, like so:

cat <your XML file> | sed 'sX<Active>True</Active>X<Active>true</Active>X' | xmllint --schema -

If you're not, you can still use a non-validating xslt pocessor (xalan, saxon etc.) to run a simple xslt transformation on the input, and only then pipe it to xmllint.

What the xsl should contain something like below, for the example you listed above (the xslt processor should be 2.0 capable):

<?xml version="1.0"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="2.0">
    <xsl:output method="xml" indent="yes"/>
    <xsl:template match="/">
    <xsl:for-each select="XML">
        <xsl:for-each select="Active">
            <xsl:value-of select=" replace(current(), 'True','true')"/>
        </xsl:for-each>
    </xsl:for-each>
    </xsl:template>
</xsl:stylesheet>

Full width layout with twitter bootstrap

Here is an example of a 100% width, 100% height layout with Bootstrap 3.

http://bootply.com/tofficer/77686

JPA CriteriaBuilder - How to use "IN" comparison operator

If I understand well, you want to Join ScheduleRequest with User and apply the in clause to the userName property of the entity User.

I'd need to work a bit on this schema. But you can try with this trick, that is much more readable than the code you posted, and avoids the Join part (because it handles the Join logic outside the Criteria Query).

List<String> myList = new ArrayList<String> ();
for (User u : usersList) {
    myList.add(u.getUsername());
}
Expression<String> exp = scheduleRequest.get("createdBy");
Predicate predicate = exp.in(myList);
criteria.where(predicate);

In order to write more type-safe code you could also use Metamodel by replacing this line:

Expression<String> exp = scheduleRequest.get("createdBy");

with this:

Expression<String> exp = scheduleRequest.get(ScheduleRequest_.createdBy);

If it works, then you may try to add the Join logic into the Criteria Query. But right now I can't test it, so I prefer to see if somebody else wants to try.


Not a perfect answer though may be code snippets might help.

public <T> List<T> findListWhereInCondition(Class<T> clazz,
            String conditionColumnName, Serializable... conditionColumnValues) {
        QueryBuilder<T> queryBuilder = new QueryBuilder<T>(clazz);
        addWhereInClause(queryBuilder, conditionColumnName,
                conditionColumnValues);
        queryBuilder.select();
        return queryBuilder.getResultList();

    }


private <T> void addWhereInClause(QueryBuilder<T> queryBuilder,
            String conditionColumnName, Serializable... conditionColumnValues) {

        Path<Object> path = queryBuilder.root.get(conditionColumnName);
        In<Object> in = queryBuilder.criteriaBuilder.in(path);
        for (Serializable conditionColumnValue : conditionColumnValues) {
            in.value(conditionColumnValue);
        }
        queryBuilder.criteriaQuery.where(in);

    }

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

I have problems with set password too. And find answer at official site

SET PASSWORD FOR 'root'@'localhost' = 'your_password';

Conditionally formatting cells if their value equals any value of another column

All you need to do for that is a simple loop.
This doesn't handle testing for lower case, upper-case mismatch. If this isn't exactly what you are looking for, comment, and I can revise.

If you are planning to learn VBA. This is a great start.

TESTED:

Sub MatchAndColor()

Dim lastRow As Long
Dim sheetName As String

    sheetName = "Sheet1"            'Insert your sheet name here
    lastRow = Sheets(sheetName).Range("A" & Rows.Count).End(xlUp).Row

    For lRow = 2 To lastRow         'Loop through all rows

        If Sheets(sheetName).Cells(lRow, "A") = Sheets(sheetName).Cells(lRow, "B") Then
            Sheets(sheetName).Cells(lRow, "A").Interior.ColorIndex = 3  'Set Color to RED
        End If

    Next lRow

End Sub

EXAMPLE

Oracle SQL Developer and PostgreSQL

Oracle SQL Developer 2020-02 support PostgreSQL, but it is just the basics by adding postgreSQL driver under jdbc dir and configure by adding as a 3rd party driver.

The supported functionality:

  • multiple databases which can be selected at connection definition
  • CRUD operations like query tables
  • scheme operations
  • basic modelling support: show tables without pk, fk, connections

Not supported functionalities:

  • no table or field completion
  • no indexes are shown in a tab
  • no constraints are shown in a tab like: fk, pk-s, unique, or others
  • no table or field completions in the editor
  • no functions, packages,triggers, views are shown

The sad thing is Oracle should only change the queries behind this view in case of PostgreSql connections. For example for indexes they need to use this query: select * from pg_catalog.pg_indexes;

Transaction marked as rollback only: How do I find the cause

There is always a reason why the nested method roll back. If you don't see the reason, you need to change your logger level to debug, where you will see the more details where transaction failed. I changed my logback.xml by adding

<logger name="org.springframework.transaction" level="debug"/>
<logger name="org.springframework.orm.jpa" level="debug"/>

then I got this line in the log:

Participating transaction failed - marking existing transaction as rollback-only

So I just stepped through my code to see where this line is generated and found that there is a catch block which did not throw anything.

private Student add(Student s) {
        try {
            Student retval = studentRepository.save(s);
            return retval;
        } catch (Exception e) {
            
        }
        return null;
    }

Can I change the viewport meta tag in mobile safari on the fly?

in your <head>

<meta id="viewport"
      name="viewport"
      content="width=1024, height=768, initial-scale=0, minimum-scale=0.25" />

somewhere in your javascript

document.getElementById("viewport").setAttribute("content",
      "initial-scale=0.5; maximum-scale=1.0; user-scalable=0;");

... but good luck with tweaking it for your device, fiddling for hours... and i'm still not there!

source

How to add many functions in ONE ng-click?

You have 2 options :

  1. Create a third method that wrap both methods. Advantage here is that you put less logic in your template.

  2. Otherwise if you want to add 2 calls in ng-click you can add ';' after edit($index) like this

    ng-click="edit($index); open()"

See here : http://jsfiddle.net/laguiz/ehTy6/

json_encode function: special characters

you should use this code:

$json = json_encode(array_map('utf8_encode', $arr))

array_map function converts special characters in UTF8 standard

What's the syntax for mod in java

In Java, the mod operation can be performed as such:

Math.floorMod(a, b)

Note: The mod operation is different from the remainder operation. In Java, the remainder operation can be performed as such:

a % b

Convert to/from DateTime and Time in Ruby

You'll need two slightly different conversions.

To convert from Time to DateTime you can amend the Time class as follows:

require 'date'
class Time
  def to_datetime
    # Convert seconds + microseconds into a fractional number of seconds
    seconds = sec + Rational(usec, 10**6)

    # Convert a UTC offset measured in minutes to one measured in a
    # fraction of a day.
    offset = Rational(utc_offset, 60 * 60 * 24)
    DateTime.new(year, month, day, hour, min, seconds, offset)
  end
end

Similar adjustments to Date will let you convert DateTime to Time .

class Date
  def to_gm_time
    to_time(new_offset, :gm)
  end

  def to_local_time
    to_time(new_offset(DateTime.now.offset-offset), :local)
  end

  private
  def to_time(dest, method)
    #Convert a fraction of a day to a number of microseconds
    usec = (dest.sec_fraction * 60 * 60 * 24 * (10**6)).to_i
    Time.send(method, dest.year, dest.month, dest.day, dest.hour, dest.min,
              dest.sec, usec)
  end
end

Note that you have to choose between local time and GM/UTC time.

Both the above code snippets are taken from O'Reilly's Ruby Cookbook. Their code reuse policy permits this.

What's the environment variable for the path to the desktop?

Quite old topic. But I want to give my 2 cents...

I've slightly modified tomasz86 solution, to look in the old style "Shell Folders" instead of "User Shell Folders", so i don't need to expand the envvar %userprofile%

Also there is no dependency from powershell/vbscript/etc....

for /f "usebackq tokens=2,3*" %%A in (`REG QUERY "HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" /v "Desktop"`) do if %%A==REG_SZ  set desktopdir=%%B
echo %desktopdir%

Hope it helps.

@Autowired - No qualifying bean of type found for dependency at least 1 bean

I believe for @Service you have to add qualifier name like below :

@Service("employeeService") should solve your issue

or after @Service you should add @Qualifier annontion like below :

@Service
@Qualifier("employeeService")

Print Combining Strings and Numbers

Using print function without parentheses works with older versions of Python but is no longer supported on Python3, so you have to put the arguments inside parentheses. However, there are workarounds, as mentioned in the answers to this question. Since the support for Python2 has ended in Jan 1st 2020, the answer has been modified to be compatible with Python3.

You could do any of these (and there may be other ways):

(1)  print("First number is {} and second number is {}".format(first, second))
(1b) print("First number is {first} and number is {second}".format(first=first, second=second)) 

or

(2) print('First number is', first, 'second number is', second) 

(Note: A space will be automatically added afterwards when separated from a comma)

or

(3) print('First number %d and second number is %d' % (first, second))

or

(4) print('First number is ' + str(first) + ' second number is' + str(second))
  

Using format() (1/1b) is preferred where available.

What is the difference between Select and Project Operations

The difference come in relational algebra where project affects columns and select affect rows. However in query syntax, select is the word. There is no such query as project. Assuming there is a table named users with hundreds of thousands of records (rows) and the table has 6 fields (userID, Fname,Lname,age,pword,salary). Lets say we want to restrict access to sensitive data (userID,pword and salary) and also restrict amount of data to be accessed. In mysql maria DB we create a view as follows ( Create view user1 as select Fname,Lname, age from users limit 100;) from our view we issue (select Fname from users1;) . This query is both a select and a project

Two statements next to curly brace in an equation

That can be achieve in plain LaTeX without any specific package.

\documentclass{article}
\begin{document}
This is your only binary choices
\begin{math}
  \left\{
    \begin{array}{l}
      0\\
      1
    \end{array}
  \right.
\end{math}
\end{document}

This code produces something which looks what you seems to need.

curly braces in front of two lines

The same example as in the @Tombart can be obtained with similar code.

\documentclass{article}

\begin{document}

\begin{math}
  f(x)=\left\{
    \begin{array}{ll}
      1, & \mbox{if $x<0$}.\\
      0, & \mbox{otherwise}.
    \end{array}
  \right.
\end{math}

\end{document}

This code produces very similar results.

enter image description here

What is tempuri.org?

Note that namespaces that are in the format of a valid Web URL don't necessarily need to be dereferenced i.e. you don't need to serve actual content at that URL. All that matters is that the namespace is globally unique.

Bootstrap 3 grid with no gap

Simple you can use bellow class.

_x000D_
_x000D_
.nopadmar {_x000D_
   padding: 0 !important;_x000D_
   margin: 0 !important;_x000D_
}
_x000D_
<div class="container-fluid">_x000D_
  <div class="row">_x000D_
    <div class="col-md-6 nopadmar">Your Content<div>_x000D_
       <div class="col-md-6 nopadmar">Your Content<div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can the Euclidean distance be calculated with NumPy?

import numpy as np
# any two python array as two points
a = [0, 0]
b = [3, 4]

You first change list to numpy array and do like this: print(np.linalg.norm(np.array(a) - np.array(b))). Second method directly from python list as: print(np.linalg.norm(np.subtract(a,b)))

DateTime.MinValue and SqlDateTime overflow

From MSDN:

Date and time data from January 1, 1753, to December 31, 9999, with an accuracy of one three-hundredth second, or 3.33 milliseconds. Values are rounded to increments of .000, .003, or .007 milliseconds. Stored as two 4-byte integers. The first 4 bytes store the number of days before or after the base date, January 1, 1900. The base date is the system's reference date. Values for datetime earlier than January 1, 1753, are not permitted. The other 4 bytes store the time of day represented as the number of milliseconds after midnight. Seconds have a valid range of 0–59.

SQL uses a different system than C# for DateTime values.

You can use your MinValue as a sentinel value - and if it is MinValue - pass null into your object (and store the date as nullable in the DB).

if(date == dateTime.Minvalue)
    objinfo.BirthDate = null;

How to auto generate migrations with Sequelize CLI from Sequelize models?

While it doesn't auto generate, one way to generate new migrations on a change to a model is: (assuming that you're using the stock sequelize-cli file structure where migrations, and models are on the same level)

  1. (Same as Manuel Bieh's suggestion, but using a require instead of an import) In your migration file (if you don't have one, you can generate one by doing "sequelize migration:create") have the following code:

    'use strict';
    var models = require("../models/index.js")
    module.exports = {
      up: function(queryInterface, Sequelize) {
        return queryInterface.createTable(models.User.tableName, 
          models.User.attributes);
      },
      down: function(queryInterface, Sequelize) {
        return queryInterface.dropTable('Users');
      }
    };
    
  2. Make a change to the User model.

  3. Delete table from database.
  4. Undo all migrations: sequelize db:migrate:undo:all
  5. Re-migrate to have changes saved in db. sequelize db:migrate

Is the MIME type 'image/jpg' the same as 'image/jpeg'?

For those it might help, I use this list as a reference to define my content-type when I have to deal with images on my app.

It says that jpg extension can be declared with Content-type : image/jpeg

There isn't any image/jpg attribute for content-type.

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

Get all table names of a particular database by SQL query?

USE dbName;

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_SCHEMA = 'dbName' OR TABLE_SCHEMA = 'schemaName')
ORDER BY TABLE_NAME

If you are working with multiple schemata on an MS SQL server, then SELECT-ing TABLE_NAME without also simultaneously selecting TABLE_SCHEMA might be of limited benefit, so I have assumed we are interested in the tables belonging to a known schema when using MS SQL Server.

I have tested the query above with SQL Server Management Studio using an SQL Server database of mine and with MySQL Workbench using a MySQL database, and in both cases it gives the table names.

The query bodges Michael Baylon's two different queries into one that can then run on either database type. The first part of the WHERE clause works on MySQL databases and the second part (after the OR) works on MS SQL Server databases. It is ugly and logically a little incorrect as it supposes that there is no undesired schema with the same name as the database. This might help someone who is looking for one single query that can run on either database server.

How to copy a java.util.List into another java.util.List

I tried to do something like this, but I still got an IndexOutOfBoundsException.

I got a ConcurrentAccessException

This means you are modifying the list while you are trying to copy it, most likely in another thread. To fix this you have to either

  • use a collection which is designed for concurrent access.

  • lock the collection appropriately so you can iterate over it (or allow you to call a method which does this for you)

  • find a away to avoid needing to copy the original list.

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

Rounding BigDecimal to *always* have two decimal places

value = value.setScale(2, RoundingMode.CEILING)

PHPExcel auto size column width

Come late, but after searching everywhere, I've created a solution that seems to be "the one".

Being known that there is a column iterator on last API versions, but not knowing how to atuoadjust the column object it self, basically I've created a loop to go from real first used column to real last used one.

Here it goes:

//Just before saving de Excel document, you do this:

PHPExcel_Shared_Font::setAutoSizeMethod(PHPExcel_Shared_Font::AUTOSIZE_METHOD_EXACT);

//We get the util used space on worksheet. Change getActiveSheet to setActiveSheetIndex(0) to choose the sheet you want to autosize. Iterate thorugh'em if needed.
//We remove all digits from this string, which cames in a form of "A1:G24".
//Exploding via ":" to get a 2 position array being 0 fisrt used column and 1, the last used column.
$cols = explode(":", trim(preg_replace('/\d+/u', '', $objPHPExcel->getActiveSheet()->calculateWorksheetDimension())));

$col = $cols[0]; //first util column with data
$end = ++$cols[1]; //last util column with data +1, to use it inside the WHILE loop. Else, is not going to use last util range column.
while($col != $end){
    $objPHPExcel->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);

    $col++;
}

//Saving.
$objWriter->save('php://output');

Which JRE am I using?

The following command will tell you a lot of information about your java version, including the vendor:

java -XshowSettings:properties -version

It works on Windows, Mac, and Linux.

Javascript swap array elements

According to some random person on Metafilter, "Recent versions of Javascript allow you to do swaps (among other things) much more neatly:"

[ list[x], list[y] ] = [ list[y], list[x] ];

My quick tests showed that this Pythonic code works great in the version of JavaScript currently used in "Google Apps Script" (".gs"). Alas, further tests show this code gives a "Uncaught ReferenceError: Invalid left-hand side in assignment." in whatever version of JavaScript (".js") is used by Google Chrome Version 24.0.1312.57 m.

Letter Count on a string

count_letters=""

number=count_letters.count("")

print number

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

System.Net.WebException HTTP status code

I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.

Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.

Remove all constraints affecting a UIView

Swift

Following UIView Extension will remove all Edge constraints of a view:

extension UIView {
    func removeAllConstraints() {
        if let _superview = self.superview {
            self.removeFromSuperview()
            _superview.addSubview(self)
        }
    }
}

How do I iterate over a range of numbers defined by variables in Bash?

for i in $(seq 1 $END); do echo $i; done

edit: I prefer seq over the other methods because I can actually remember it ;)

How do I apply a diff patch on Windows?

I made pure Python tool just for that. It has predictable cross-platform behavior. Although it doesn't create new files (at the time of writing this) and lacks a GUI, it can be used as a library to create graphic tool.

UPDATE: It should be more convenient to use it if you have Python installed.

pip install patch
python -m patch

Fatal error: Call to undefined function sqlsrv_connect()

This helped me get to my answer. There are two php.ini files located, in my case, for wamp. One is under the php folder and the other one is in the C:\wamp\bin\apache\Apachex.x.x\bin folder. When connecting to SQL through sqlsrv_connect function, we are referring to the php.ini file in the apache folder. Add the following (as per your version) to this file:

extension=c:/wamp/bin/php/php5.4.16/ext/php_sqlsrv_53_ts.dll

Get the name of a pandas DataFrame

From here what I understand DataFrames are:

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

And Series are:

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).

Series have a name attribute which can be accessed like so:

 In [27]: s = pd.Series(np.random.randn(5), name='something')

 In [28]: s
 Out[28]: 
 0    0.541
 1   -1.175
 2    0.129
 3    0.043
 4   -0.429
 Name: something, dtype: float64

 In [29]: s.name
 Out[29]: 'something'

EDIT: Based on OP's comments, I think OP was looking for something like:

 >>> df = pd.DataFrame(...)
 >>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
 >>> print(df.name)
 'df'

C# event with custom arguments

public enum MyEvents
{
    Event1
}

public class CustomEventArgs : EventArgs
{
    public MyEvents MyEvents { get; set; }
}


private EventHandler<CustomEventArgs> onTrigger;

public event EventHandler<CustomEventArgs> Trigger
{
    add
    {
        onTrigger += value;
    }
    remove
    {
        onTrigger -= value;
    }
}

protected void OnTrigger(CustomEventArgs e)
{
    if (onTrigger != null)
    {
        onTrigger(this, e);
    }
}

Empty an array in Java / processing

array = new String[array.length];

Open Bootstrap Modal from code-behind

FYI,

I've seen this strange behavior before in jQuery widgets. Part of the key is to put the updatepanel inside the modal. This allows the DOM of the updatepanel to "stay with" the modal (however it works with bootstrap).

Ruby on Rails form_for select field with class

Try this way:

<%= f.select(:object_field, ['Item 1', ...], {}, { :class => 'my_style_class' }) %>

select helper takes two options hashes, one for select, and the second for html options. So all you need is to give default empty options as first param after list of items and then add your class to html_options.

http://api.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-select

Comment shortcut Android Studio

In spanish keyboard without changing anything I can make a comment with the keys:

cmd + -

OR

cmd + alt + -

This works because in english keyboard / is located at the same place than - on a spanish keyboard

How to parse a JSON object to a TypeScript Object

you can make a new object of your class and then assign it's parameters dynamically from the JSON object's parameters.

const employeeData = JSON.parse(employeeString);
let emp:Employee=new Employee();
const keys=Object.keys(employeeData);
keys.forEach(key=>{
    emp[key]=employeeData[key];
});
console.log(emp);

now the emp is an object of Employee containing all fields of employeeString's Json object(employeeData);

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

How do I bind onchange event of a TextBox using JQuery?

What Chad says, except its better to use .keyup in this case because with .keydown and .keypress the value of the input is still the older value i.e. the newest key pressed would not be reflected if .val() is called.

This should probably be a comment on Chad's answer but I dont have privileges to comment yet.

How can I initialize C++ object member variables in the constructor?

You can specify how to initialize members in the member initializer list:

BigMommaClass {
    BigMommaClass(int, int);

private:
    ThingOne thingOne;
    ThingTwo thingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
    : thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}

How could I convert data from string to long in c#

This answer no longer works, and I cannot come up with anything better then the other answers (see below) listed here. Please review and up-vote them.

Convert.ToInt64("1100.25")

Method signature from MSDN:

public static long ToInt64(
    string value
)

On duplicate key ignore?

Mysql has this handy UPDATE INTO command ;)

edit Looks like they renamed it to REPLACE

REPLACE works exactly like INSERT, except that if an old row in the table has the same value as a new row for a PRIMARY KEY or a UNIQUE index, the old row is deleted before the new row is inserted

Passing vector by reference

void do_something(int el, std::vector<int> **arr)

should be

void do_something(int el, std::vector<int>& arr)
{
    arr.push_back(el);
}

Pass by reference has been simplified to use the & in C++.

How to establish a connection pool in JDBC?

HikariCP

It's modern, it's fast, it's simple. I use it for every new project. I prefer it a lot over C3P0, don't know the other pools too well.

How do I deal with corrupted Git object files?

Recovering from Repository Corruption is the official answer.

The really short answer is: find uncorrupted objects and copy them.

Using Colormaps to set color of line in matplotlib

U may do as I have written from my deleted account (ban for new posts :( there was). Its rather simple and nice looking.

Im using 3-rd one of these 3 ones usually, also I wasny checking 1 and 2 version.

from matplotlib.pyplot import cm
import numpy as np

#variable n should be number of curves to plot (I skipped this earlier thinking that it is obvious when looking at picture - sorry my bad mistake xD): n=len(array_of_curves_to_plot)
#version 1:

color=cm.rainbow(np.linspace(0,1,n))
for i,c in zip(range(n),color):
   ax1.plot(x, y,c=c)

#or version 2: - faster and better:

color=iter(cm.rainbow(np.linspace(0,1,n)))
c=next(color)
plt.plot(x,y,c=c)

#or version 3:

color=iter(cm.rainbow(np.linspace(0,1,n)))
for i in range(n):
   c=next(color)
   ax1.plot(x, y,c=c)

example of 3:

Ship RAO of Roll vs Ikeda damping in function of Roll amplitude A44

Populating a razor dropdownlist from a List<object> in MVC

Something close to:

@Html.DropDownListFor(m => m.UserRole, 
   new SelectList(Model.Roles, "UserRoleId", "UserRole", Model.Roles.First().UserRoleId), 
   new { /* any html  attributes here */ }) 

You need a SelectList to populate the DropDownListFor. For any HTML attributes you need, you can add:

new { @class = "DropDown", @id = "dropdownUserRole" }

How can I debug a Perl script?

perl -d your_script.pl args

is how you debug Perl. It launches you into an interactive gdb-style command line debugger.

Where do I find old versions of Android NDK?

Simply replacing .bin with .tar.bz2 is not enough, for NDK releases older than 10b. For example, https://dl.google.com/android/ndk/android-ndk-r10b-linux-x86_64.tar.bz2 is not a valid link.

Turned out that the correct link for 10b was: https://dl.google.com/android/ndk/android-ndk32-r10b-linux-x86_64.tar.bz2 (note the additional '32'). However, this doesn't seem to apply to e.g. 10a, as this link doesn't work: https://dl.google.com/android/ndk/android-ndk32-r10a-linux-x86_64.tar.bz2 .

Bottom line: use http://web.archive.org until Google fixes this, if ever...

Convert number of minutes into hours & minutes using PHP

Just in case you want to something like:

echo date('G \h\o\u\r\s i \m\i\n\u\t\e\s', mktime(0, 90)); //will return 1 hours 30 minutes
echo date('G \j\a\m i \m\e\n\i\t', mktime(0, 90)); //will return 1 jam 30 menit

How to add values in a variable in Unix shell scripting?

Here's a simple example to add two variables:

var1=4
var2=3
let var3=$var1+$var2
echo $var3

html 5 audio tag width

For those looking for an inline example, here is one:

<audio controls style="width: 200px;">
   <source src="http://somewhere.mp3" type="audio/mpeg">
</audio>

It doesn't seem to respect a "height" setting, at least not awesomely. But you can always "customize" the controls but creating your own controls (instead of using the built-in ones) or using somebody's widget that similarly creates its own :)

How do I remove quotes from a string?

str_replace('"', "", $string);
str_replace("'", "", $string);

I assume you mean quotation marks?

Otherwise, go for some regex, this will work for html quotes for example:

preg_replace("/<!--.*?-->/", "", $string);

C-style quotes:

preg_replace("/\/\/.*?\n/", "\n", $string);

CSS-style quotes:

preg_replace("/\/*.*?\*\//", "", $string);

bash-style quotes:

preg-replace("/#.*?\n/", "\n", $string);

Etc etc...

For loop in Objective-C

You mean fast enumeration? You question is very unclear.

A normal for loop would look a bit like this:

unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{ 
   // do loop stuff
   id someObject = [someArray objectAtIndex:i];
}

And a loop with fast enumeration, which is optimized by the compiler, would look like this:

for(id someObject in someArray)
{
   // do stuff with object
}

Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration

Make docker use IPv4 for port binding

As @daniel-t points out in the comment: github.com/docker/docker/issues/2174 is about showing binding only to IPv6 in netstat, but that is not an issue. As that github issues states:

When setting up the proxy, Docker requests the loopback address '127.0.0.1', Linux realises this is an address that exists in IPv6 (as ::0) and opens on both (but it is formally an IPv6 socket). When you run netstat it sees this and tells you it is an IPv6 - but it is still listening on IPv4. If you have played with your settings a little, you may have disabled this trick Linux does - by setting net.ipv6.bindv6only = 1.

In other words, just because you see it as IPv6 only, it is still able to communicate on IPv4 unless you have IPv6 set to only bind on IPv6 with the net.ipv6.bindv6only setting. To be clear, net.ipv6.bindv6only should be 0 - you can run sysctl net.ipv6.bindv6only to verify.

What is path of JDK on Mac ?

On my Mac:

/System/Library/Frameworks/JavaVM.framework/Home/

btw, did you tried which java?

How to repair a serialized string which has been corrupted by an incorrect byte count length?

There's another reason unserialize() failed because you improperly put serialized data into the database see Official Explanation here. Since serialize() returns binary data and php variables don't care encoding methods, so that putting it into TEXT, VARCHAR() will cause this error.

Solution: store serialized data into BLOB in your table.

Can I convert long to int?

The safe and fastest way is to use Bit Masking before cast...

int MyInt = (int) ( MyLong & 0xFFFFFFFF )

The Bit Mask ( 0xFFFFFFFF ) value will depend on the size of Int because Int size is dependent on machine.

How to generate an entity-relationship (ER) diagram using Oracle SQL Developer

Since SQL Developer 3, it's pretty straightforward (they could've made it easier).

  1. Go to «View → Data Modeler → Browser». The browser will show up as one of the tabs along the left-hand side.
  2. Click on the «Browser» tab, expand the design (probably called Untitled_1), right-click «Relational Models» and select «New Relational Model».
  3. Right click on the newly created relational model (probably Relational_1) and select «Show».
  4. Then just drag the tables you want (from e.g. the «Connections» tab) onto the model.  Note when you click on the first table in the Connections tab, SQLDeveloper opens that table in the right: select all the tables from the left, then ensure the Relational_1 tab (or whatever name) is the active one in the rhs before you drag them over, because it has probably switched to one of the tables you clicked in the lhs.

JavaScript for handling Tab Key press

Given this piece of HTML code:

<a href='https://facebook.com/'>Facebook</a>
<a href='https://google.ca/'>Google</a>
<input type='text' placeholder='an input box'>

We can use this JavaScript:

function checkTabPress(e) {
    'use strict';
    var ele = document.activeElement;

    if (e.keyCode === 9 && ele.nodeName.toLowerCase() === 'a') {
        console.log(ele.href);
    }
}

document.addEventListener('keyup', function (e) {
    checkTabPress(e);
}, false);

I have bound an event listener to the document element for the keyUp event, which triggers a function to check if the Tab key was pressed (or technically, released).

The function checks the currently focused element and whether the NodeName is a. If so, it enters the if block and, in my case, writes the value of the href property to the JavaScript console.

Here's a jsFiddle

How do I properly compare strings in C?

    #include<stdio.h>
    #include<string.h>
    int main()
    {
        char s1[50],s2[50];
        printf("Enter the character of strings: ");
        gets(s1);
        printf("\nEnter different character of string to repeat: \n");
        while(strcmp(s1,s2))
        {
            printf("%s\n",s1);
            gets(s2);
        }
        return 0;
    }

This is very simple solution in which you will get your output as you want.

What is the most appropriate way to store user settings in Android application

Okay; it's been a while since the answer is kind-of mixed, but here's a few common answers. I researched this like crazy and it was hard to build a good answer

  1. The MODE_PRIVATE method is considered generally safe, if you assume that the user didn't root the device. Your data is stored in plain text in a part of the file system that can only be accessed by the original program. This makings grabbing the password with another app on a rooted device easy. Then again, do you want to support rooted devices?

  2. AES is still the best encryption you can do. Remember to look this up if you are starting a new implementation if it's been a while since I posted this. The largest issue with this is "What to do with the encryption key?"

So, now we are at the "What to do with the key?" portion. This is the hard part. Getting the key turns out to be not that bad. You can use a key derivation function to take some password and make it a pretty secure key. You do get into issues like "how many passes do you do with PKFDF2?", but that's another topic

  1. Ideally, you store the AES key off the device. You have to figure out a good way to retrieve the key from the server safely, reliably, and securely though

  2. You have a login sequence of some sort (even the original login sequence you do for remote access). You can do two runs of your key generator on the same password. How this works is that you derive the key twice with a new salt and a new secure initialization vector. You store one of those generated passwords on the device, and you use the second password as the AES key.

When you log in, you re-derive the key on the local login and compare it to the stored key. Once that is done, you use derive key #2 for AES.

  1. Using the "generally safe" approach, you encrypt the data using AES and store the key in MODE_PRIVATE. This is recommended by a recent-ish Android blog post. Not incredibly secure, but way better for some people over plain text

You can do a lot of variations of these. For example, instead of a full login sequence, you can do a quick PIN (derived). The quick PIN might not be as secure as a full login sequence, but it's many times more secure than plain text

Error: Node Sass version 5.0.0 is incompatible with ^4.0.0

Uninstall node-sass

npm uninstall node-sass

use sass by:

npm install -g sass
npm install --save-dev sass

What is the best free memory leak detector for a C/C++ program and its plug-in DLLs?

If you don't want to recompile (as Visual Leak Detector requires) I would recommend WinDbg, which is both powerful and fast (though it's not as easy to use as one could desire).

On the other hand, if you don't want to mess with WinDbg, you can take a look at UMDH, which is also developed by Microsoft and it's easier to learn.

Take a look at these links in order to learn more about WinDbg, memory leaks and memory management in general:

UTF-8: General? Bin? Unicode?

Accepted answer is outdated.

If you use MySQL 5.5.3+, use utf8mb4_unicode_ci instead of utf8_unicode_ci to ensure the characters typed by your users won't give you errors.

utf8mb4 supports emojis for example, whereas utf8 might give you hundreds of encoding-related bugs like:

Incorrect string value: ‘\xF0\x9F\x98\x81…’ for column ‘data’ at row 1

Initializing an Array of Structs in C#

I'd use a static constructor on the class that sets the value of a static readonly array.

public class SomeClass
{
   public readonly MyStruct[] myArray;

   public static SomeClass()
   {
      myArray = { {"foo", "bar"},
                  {"boo", "far"}};
   }
}

How to "git clone" including submodules?

I had the same problem for a GitHub repository. My account was missing SSH Key. The process is

  1. Generate SSH Key
  2. Adding a new SSH key to your GitHub account

Then, you can clone the repository with submodules (git clone --recursive YOUR-GIT-REPO-URL)

or

Run git submodule init and git submodule update to fetch submodules in already cloned repository.

Check if an object belongs to a class in Java

I agree with the use of instanceof already mentioned.

An additional benefit of using instanceof is that when used with a null reference instanceof of will return false, while a.getClass() would throw a NullPointerException.

T-SQL datetime rounded to nearest minute and nearest hours with using functions

I realize this question is ancient and there is an accepted and an alternate answer. I also realize that my answer will only answer half of the question, but for anyone wanting to round to the nearest minute and still have a datetime compatible value using only a single function:

CAST(YourValueHere as smalldatetime);

For hours or seconds, use Jeff Ogata's answer (the accepted answer) above.

How to check if image exists with given url?

jQuery 3.0 removed .error. Correct syntax is now

$(this).on('error', function(){
    console.log('Image does not exist: ' + this.id); 
});

How to solve npm error "npm ERR! code ELIFECYCLE"

This solved me on ubuntu 16

1) Update npm and node to latest version . 2) Restart System 3) Remove node_modules and again npm i & npm start

Cannot deserialize the current JSON array (e.g. [1,2,3])

You can use this to solve your problem:

private async void btn_Go_Click(object sender, RoutedEventArgs e)
{
    HttpClient webClient = new HttpClient();
    Uri uri = new Uri("http://www.school-link.net/webservice/get_student/?id=" + txtVCode.Text);
    HttpResponseMessage response = await webClient.GetAsync(uri);
    var jsonString = await response.Content.ReadAsStringAsync();
    var _Data = JsonConvert.DeserializeObject <List<Student>>(jsonString);
    foreach (Student Student in _Data)
    {
        tb1.Text = Student.student_name;
    }
}

How to send a POST request in Go?

I know this is old but this answer came up in search results. For the next guy - the proposed and accepted answer works, however the code initially submitted in the question is lower-level than it needs to be. Nobody got time for that.

//one-line post request/response...
response, err := http.PostForm(APIURL, url.Values{
    "ln": {c.ln},
    "ip": {c.ip},
    "ua": {c.ua}})

//okay, moving on...
if err != nil {
  //handle postform error
}

defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)

if err != nil {
  //handle read response error
}

fmt.Printf("%s\n", string(body))

https://golang.org/pkg/net/http/#pkg-overview

Python - Module Not Found

I had same error. For those who run python scripts on different servers, please check if the python path is correctly specified in shebang. For me on each server it was located in different dirs.

Turn ON/OFF Camera LED/flash light in Samsung Galaxy Ace 2.2.1 & Galaxy Tab

I will soon released a new version of my app to support to galaxy ace.

You can download here: https://play.google.com/store/apps/details?id=droid.pr.coolflashlightfree

In order to solve your problem you should do this:

this._camera = Camera.open();     
this._camera.startPreview();
this._camera.autoFocus(new AutoFocusCallback() {
public void onAutoFocus(boolean success, Camera camera) {
}
});

Parameters params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_ON);
this._camera.setParameters(params);

params = this._camera.getParameters();
params.setFlashMode(Parameters.FLASH_MODE_OFF);
this._camera.setParameters(params);

don't worry about FLASH_MODE_OFF because this will keep the light on, strange but it's true

to turn off the led just release the camera

Multiple files upload (Array) with CodeIgniter 2.0

There is no predefined method available in codeigniter to upload multiple file at one time but you can send file in array and upload them one by one

here is refer: Here is best option to upload multiple file in codeigniter 3.0.1 with preview https://codeaskbuzz.com/how-to-upload-multiple-file-in-codeigniter-framework/

Setting background colour of Android layout element

You can use simple color resources, specified usually inside res/values/colors.xml.

<color name="red">#ffff0000</color>

and use this via android:background="@color/red". This color can be used anywhere else too, e.g. as a text color. Reference it in XML the same way, or get it in code via getResources().getColor(R.color.red).

You can also use any drawable resource as a background, use android:background="@drawable/mydrawable" for this (that means 9patch drawables, normal bitmaps, shape drawables, ..).

java.io.StreamCorruptedException: invalid stream header: 7371007E

when I send only one object from the client to server all works well.

when I attempt to send several objects one after another on the same stream I get StreamCorruptedException.

Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

How to find column names for all tables in all databases in SQL Server

try the below query

DECLARE @Query VARCHAR(max) 
SELECT @Query = 'USE ? SELECT ''?'' AS DataBaseName,
                                sys.columns.name AS ColumnName  ,
                                sys.tables.name  AS TableName   ,
                                schema_name (sys.tables.schema_Id) AS schemaName
                         FROM sys.columns
                         JOIN sys.tables 
              ON sys.columns.object_id = sys.tables.object_id
              WHERE sys.columns.name = ''id'' '
EXEC SP_MSFOREACHDB @Query

gives list of tables containing ID column from all databases.

random number generator between 0 - 1000 in c#

Use this:

static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(min, max);

}

This is example for you to modify and use in your application.

Moment.js get day name from date

With moment you can parse the date string you have:

var dt = moment(myDate.date, "YYYY-MM-DD HH:mm:ss")

That's for UTC, you'll have to convert the time zone from that point if you so desire.

Then you can get the day of the week:

dt.format('dddd');

Responsive design with media query : screen size?

i will provide mine because @muni s solution was a bit overkill for me

note: if you want to add custom definitions for several resolutions together, say something like this:

//mobile generally   
 @media screen and (max-width: 1199)  {

      .irns-desktop{
        display: none;
      }

      .irns-mobile{
        display: initial;
      }

    }

Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')

//here all definitions to apply globally


//desktop
@media only screen
and (min-width : 1200) {


}

//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px)  {

} // end media query

//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px)  {

}//end media definition


//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px)  {

}//end media query



//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {

}

//end media query

Which data structures and algorithms book should I buy?

If you don't need in a complete reference to the most part of algorithms and data structures that are in use and just want to get acquainted with common techniques I would recommend something more lightweight than Cormen, Sedgewick or Knuth. I think, Algorithms and Data Structures by N. Wirth is not as bad choice even in spite of it was printed far ago.

How would I create a UIAlertView in Swift?

  // UIAlertView is deprecated. Use UIAlertController 
  // title = title of the alert view.
  // message = Alert message you want to show.
  // By tap on "OK" , Alert view will dismiss.

 UIAlertView(title: "Alert", message: "Enter Message here.", delegate: nil, cancelButtonTitle: "OK").show()

Converting a String array into an int Array in java

Since you are trying to get an Integer[] array you could use:

Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);

Your code:

private void processLine(String[] strings) {
    Integer[] intarray = Stream.of(strings).mapToInt(Integer::parseInt).boxed().toArray(Integer[]::new);
}

Note, that this only works for Java 8 and higher.

What does int argc, char *argv[] mean?

argv and argc are how command line arguments are passed to main() in C and C++.

argc will be the number of strings pointed to by argv. This will (in practice) be 1 plus the number of arguments, as virtually all implementations will prepend the name of the program to the array.

The variables are named argc (argument count) and argv (argument vector) by convention, but they can be given any valid identifier: int main(int num_args, char** arg_strings) is equally valid.

They can also be omitted entirely, yielding int main(), if you do not intend to process command line arguments.

Try the following program:

#include <iostream>

int main(int argc, char** argv) {
    std::cout << "Have " << argc << " arguments:" << std::endl;
    for (int i = 0; i < argc; ++i) {
        std::cout << argv[i] << std::endl;
    }
}

Running it with ./test a1 b2 c3 will output

Have 4 arguments:
./test
a1
b2
c3

What is a Python equivalent of PHP's var_dump()?

To display a value nicely, you can use the pprint module. The easiest way to dump all variables with it is to do

from pprint import pprint

pprint(globals())
pprint(locals())

If you are running in CGI, a useful debugging feature is the cgitb module, which displays the value of local variables as part of the traceback.

Is there a way to detach matplotlib plots so that the computation can continue?

You may want to read this document in matplotlib's documentation, titled:

Using matplotlib in a python shell

How to unnest a nested list

Use reduce function

reduce(lambda x, y: x + y, A, [])

Or sum

sum(A, [])