Programs & Examples On #Instruction set

Specification for machine-readable instructions processed on different processing cores. Different processor architectures usually have unique instruction sets.

What is the difference between MOV and LEA?

As stated in the other answers:

  • MOV will grab the data at the address inside the brackets and place that data into the destination operand.
  • LEA will perform the calculation of the address inside the brackets and place that calculated address into the destination operand. This happens without actually going out to the memory and getting the data. The work done by LEA is in the calculating of the "effective address".

Because memory can be addressed in several different ways (see examples below), LEA is sometimes used to add or multiply registers together without using an explicit ADD or MUL instruction (or equivalent).

Since everyone is showing examples in Intel syntax, here are some in AT&T syntax:

MOVL 16(%ebp), %eax       /* put long  at  ebp+16  into eax */
LEAL 16(%ebp), %eax       /* add 16 to ebp and store in eax */

MOVQ (%rdx,%rcx,8), %rax  /* put qword at  rcx*8 + rdx  into rax */
LEAQ (%rdx,%rcx,8), %rax  /* put value of "rcx*8 + rdx" into rax */

MOVW 5(%bp,%si), %ax      /* put word  at  si + bp + 5  into ax */
LEAW 5(%bp,%si), %ax      /* put value of "si + bp + 5" into ax */

MOVQ 16(%rip), %rax       /* put qword at rip + 16 into rax                 */
LEAQ 16(%rip), %rax       /* add 16 to instruction pointer and store in rax */

MOVL label(,1), %eax      /* put long at label into eax            */
LEAL label(,1), %eax      /* put the address of the label into eax */

What in layman's terms is a Recursive Function using PHP

Recursion is an alternative to loops, it's quite seldom that they bring more clearness or elegance to your code. A good example was given by Progman's answer, if he wouldn't use recursion he would be forced to keep track in which directory he is currently (this is called state) recursions allows him to do the bookkeeping using the stack (the area where variables and return adress of a method are stored)

The standard examples factorial and Fibonacci are not useful for understanding the concept because they're easy to replace by a loop.

How to make an Android Spinner with initial text "Select One"?

There is no default API to set hint on Spinner. To add it we need a small workaround with out that not safety reflection implementation

List<Object> objects = new ArrayList<Object>();
objects.add(firstItem);
objects.add(secondItem);
// add hint as last item
objects.add(hint);

HintAdapter adapter = new HintAdapter(context, objects, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

Spinner spinnerFilmType = (Spinner) findViewById(R.id.spinner);
spinner.setAdapter(adapter);

// show hint
spinner.setSelection(adapter.getCount());

Adapter source:

public class HintAdapter
        extends ArrayAdapter<Objects> {

    public HintAdapter(Context theContext, List<Object> objects) {
        super(theContext, android.R.id.text1, android.R.id.text1, objects);
    }

    public HintAdapter(Context theContext, List<Object> objects, int theLayoutResId) {
        super(theContext, theLayoutResId, android.R.id.text1, objects);
    }

    @Override
    public int getCount() {
        // don't display last item. It is used as hint.
        int count = super.getCount();
        return count > 0 ? count - 1 : count;
    }
}

Original source

How to force garbage collection in Java?

FYI

The method call System.runFinalizersOnExit(true) guarantees that finalizer methods are called before Java shuts down. However, this method is inherently unsafe and has been deprecated. An alternative is to add “shutdown hooks” with the method Runtime.addShutdownHook.

Masarrat Siddiqui

Javascript dynamic array of strings

Just initialize an array and push the element on the array. It will automatic scale the array.

var a = [ ];

a.push('Some string'); console.log(a); // ['Some string'] 
a.push('another string'); console.log(a); // ['Some string', 'another string'] 
a.push('Some string'); console.log(a); // ['Some string', 'another string', 'Some string']

How do I dump the data of some SQLite3 tables?

The answer by retracile should be the closest one, yet it does not work for my case. One insert query just broke in the middle and the export just stopped. Not sure what is the reason. However It works fine during .dump.

Finally I wrote a tool for the split up the SQL generated from .dump:

https://github.com/motherapp/sqlite_sql_parser/

What are the differences between a program and an application?

I use the term program to include applications (apps), utilities and even operating systems like windows, linux and mac OS. We kinda need an overall term for all the different terms available. It might be wrong but works for me. :)

Change Background color (css property) using Jquery

$("#bchange").click(function() {
    $("body, this").css("background-color","yellow");
});

Writing a list to a file with Python

In Python3 You Can use this loop

with open('your_file.txt', 'w') as f:
    for item in list:
        f.print("", item)

$(this).val() not working to get text from span using jquery

To retrieve text of an auto generated span value just do this :

var al = $("#id-span-name").text();    
alert(al);

Django development IDE

As far as I know there is not "an IDE" for Django, but there are some IDEs that support Django right out of the box, specifically the Django syntax for templates.

The name is Komodo, and it has a lot of features, but it's not cheap. If you are not worried about source control or debugging then there is a free version called Komodo Edit.

PHP to write Tab Characters inside a file?

The tab character is \t. Notice the use of " instead of '.

$chunk = "abc\tdef\tghi";

PHP Strings - Double quoted

If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:

...

\t horizontal tab (HT or 0x09 (9) in ASCII)


Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.

Image overlay on responsive sized images bootstrap

<div class="col-md-4 py-3 pic-card">
          <div class="card ">
          <div class="pic-overlay"></div>
          <img class="img-fluid " src="images/Site Images/Health & Fitness-01.png" alt="">
          <div class="centeredcard">
            <h3>
              <span class="card-headings">HEALTH & FITNESS</span>
            </h3>
            <div class="content-inner mt-5">
              <p class="lead  p-overlay">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Recusandae ipsam nemo quasi quo quae voluptate.</p>
            </div>
          </div>
          </div>
        </div>


.pic-card{
     position: relative;

 }
 .pic-overlay{

    top: 0;
    left: 0;
    right:0;
    bottom:0;
    width: 100%;
    height: 100%;
    position: absolute;
    transition: background-color 0.5s ease;

 }
 .content-inner{
    position: relative;
     display: none;
 }

 .pic-card:hover{
     .pic-overlay{
        background-color: $dark-overlay;

     }

     .content-inner{
         display: block;
         cursor: pointer;
     }

     .card-headings{
        font-size: 15px;
        padding: 0;
     }

     .card-headings::after{
        content: '';
        width: 80%;
        border-bottom: solid 2px  rgb(52, 178, 179);
        position: absolute;
        left: 5%;
        top: 25%;
        z-index: 1;
     }
     .p-overlay{
         font-size: 15px;
     }
 }



enter code here

CASE WHEN statement for ORDER BY clause

Another simple example from here..

SELECT * FROM dbo.Employee
ORDER BY 
 CASE WHEN Gender='Male' THEN EmployeeName END Desc,
 CASE WHEN Gender='Female' THEN Country END ASC

Difference between RegisterStartupScript and RegisterClientScriptBlock?

Here's a simplest example from ASP.NET Community, this gave me a clear understanding on the concept....

what difference does this make?

For an example of this, here is a way to put focus on a text box on a page when the page is loaded into the browser—with Visual Basic using the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _ 
"document.forms[0]['TextBox1'].focus();", True)

This works well because the textbox on the page is generated and placed on the page by the time the browser gets down to the bottom of the page and gets to this little bit of JavaScript.

But, if instead it was written like this (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)

Focus will not get to the textbox control and a JavaScript error will be generated on the page

The reason for this is that the browser will encounter the JavaScript before the text box is on the page. Therefore, the JavaScript will not be able to find a TextBox1.

String formatting: % vs. .format vs. string literal

If your python >= 3.6, F-string formatted literal is your new friend.

It's more simple, clean, and better performance.

In [1]: params=['Hello', 'adam', 42]

In [2]: %timeit "%s %s, the answer to everything is %d."%(params[0],params[1],params[2])
448 ns ± 1.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [3]: %timeit "{} {}, the answer to everything is {}.".format(*params)
449 ns ± 1.42 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

In [4]: %timeit f"{params[0]} {params[1]}, the answer to everything is {params[2]}."
12.7 ns ± 0.0129 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)

How to add a button to UINavigationBar?

Adding custom button to navigation bar ( with image for buttonItem and specifying action method (void)openView{} and).

UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(0, 0, 32, 32);
[button setImage:[UIImage imageNamed:@"settings_b.png"] forState:UIControlStateNormal];
[button addTarget:self action:@selector(openView) forControlEvents:UIControlEventTouchUpInside];

UIBarButtonItem *barButton=[[UIBarButtonItem alloc] init];
[barButton setCustomView:button];
self.navigationItem.rightBarButtonItem=barButton;

[button release];
[barButton release];

What is git fast-forwarding?

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

In another way,

If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”

There won't be any "merge commit" in fast-forwarding merge.

Android Get Current timestamp?

Solution in Kotlin:

val nowInEpoch = Instant.now().epochSecond

Make sure your minimum SDK version is 26.

datetime to string with series in python pandas

There is a pandas function that can be applied to DateTime index in pandas data frame.

date = dataframe.index #date is the datetime index
date = dates.strftime('%Y-%m-%d') #this will return you a numpy array, element is string.
dstr = date.tolist() #this will make you numpy array into a list

the element inside the list:

u'1910-11-02'

You might need to replace the 'u'.

There might be some additional arguments that I should put into the previous functions.

Countdown timer using Moment js

I thought I'd throw this out there too (no plugins). It counts down for 10 seconds into the future.

_x000D_
_x000D_
    var countDownDate = moment().add(10, 'seconds');_x000D_
_x000D_
      var x = setInterval(function() {_x000D_
        diff = countDownDate.diff(moment());_x000D_
    _x000D_
        if (diff <= 0) {_x000D_
          clearInterval(x);_x000D_
           // If the count down is finished, write some text _x000D_
          $('.countdown').text("EXPIRED");_x000D_
        } else_x000D_
          $('.countdown').text(moment.utc(diff).format("HH:mm:ss"));_x000D_
_x000D_
      }, 1000);
_x000D_
<script src="https://momentjs.com/downloads/moment.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div class="countdown"></div>
_x000D_
_x000D_
_x000D_

Can I use a case/switch statement with two variables?

I don't believe a switch/case is any faster than a series of if/elseif's. They do the same thing, but if/elseif's you can check multiple variables. You cannot use a switch/case on more than one value.

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

I agree with suggestions elsewhere stating that you should use regular URL in href attribute, then call some JavaScript function in onclick. The flaw is, that they automaticaly add return false after the call.

The problem with this approach is, that if the function will not work or if there will be any problem, the link will become unclickable. Onclick event will always return false, so the normal URL will not be called.

There's very simple solution. Let function return true if it works correctly. Then use the returned value to determine if the click should be cancelled or not:

JavaScript

function doSomething() {
    alert( 'you clicked on the link' );
    return true;
}

HTML

<a href="path/to/some/url" onclick="return !doSomething();">link text</a>

Note, that I negate the result of the doSomething() function. If it works, it will return true, so it will be negated (false) and the path/to/some/URL will not be called. If the function will return false (for example, the browser doesn't support something used within the function or anything else goes wrong), it is negated to true and the path/to/some/URL is called.

How to set the background image of a html 5 canvas to .png image

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image

How good is Java's UUID.randomUUID?

I'm not an expert, but I'd assume that enough smart people looked at Java's random number generator over the years. Hence, I'd also assume that random UUIDs are good. So you should really have the theoretical collision probability (which is about 1 : 3 × 10^38 for all possible UUIDs. Does anybody know how this changes for random UUIDs only? Is it 1/(16*4) of the above?)

From my practical experience, I've never seen any collisions so far. I'll probably have grown an astonishingly long beard the day I get my first one ;)

Neither BindingResult nor plain target object for bean name available as request attribute

You would have got this Exception while doing a GET on http://localhost:8080/projectname/login

As Vinay has correctly stated you can definitely use

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String displayLogin(Model model) { 
    model.addAttribute("login", new Login()); 
    return "login"; 
}

But I am going to provide some alternative syntax which I think you were trying with Spring 3.0.

You can also achieve the above functionality with

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String displayLogin(Login loginModel) { 
    return "login"; 
}

and it login.jsp (assuming you are using InternalResourceViewResolver) you can have

<form:form method="POST" action="login.htm" modelAttribute="login">

Notice : modelAttribute is login and not loginModel. It is as per the class name you provide in argument. But if you want to use loginModel as modelAttribute is jsp you can do the following

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String displayLogin(@ModelAttribute("loginModel")Login loginModel) { 
    return "login"; 
}

and jsp would have

<form:form method="POST" action="login.htm" modelAttribute="loginModel">

I know there are just different ways for doing the same thing. But the most important point to note here -

Imp Note: When you add your model class in your methods argument (like public String displayLogin(Login loginModel)) it is automatically created and added to your Model object (which is why you can directly access it in JSP without manually putting it in model). Then it will search your request if request has attributes that it can map with the new ModelObject create. If yes Spring will inject values from request parameters to your custom model object class (Login in this case).

You can test this by doing

@RequestMapping(value = "/login", method = RequestMethod.GET) 
public String displayLogin(Login loginModel, Model model) { 
    System.out.println(model.asMap().get("login").equals(loginModel));
    return "login"; 
}

Note : Above creating of new custom model object may not hold true if you have given @SessionAttributes({"login"}). In this case it will get from session and populate values.

How to add anchor tags dynamically to a div in Javascript?

With jquery

  $("div#id").append('<a href=#>Your LINK TITLE</a>')

With javascript

   var new_a = document.createElement('a');
   new_a.setAttribute("href", "link url here");
   new_a.innerHTML = "your link text";
   //add new link to the DOM
   document.appendChild(new_a);

configure Git to accept a particular self-signed server certificate for a particular https remote

OSX User adjustments.

Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.

I put the cert.pem file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.

Configure git to trust this certificate:

$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem

How to wait until an element exists?

A cleaner example using MutationObserver:

new MutationObserver( mutation => {
    if (!mutation.addedNodes) return
    mutation.addedNodes.forEach( node => {
        // do stuff with node
    })
})

How do I convert an interval into a number of hours with postgres?

To get the number of days the easiest way would be:

SELECT EXTRACT(DAY FROM NOW() - '2014-08-02 08:10:56');

As far as I know it would return the same as:

SELECT (EXTRACT(epoch FROM (SELECT (NOW() - '2014-08-02 08:10:56')))/86400)::int;

Java serialization - java.io.InvalidClassException local class incompatible

This worked for me:

If you wrote your Serialized class object into a file, then made some changes to file and compiled it, and then you try to read an object, then this will happen.

So, write the necessary objects to file again if a class is modified and recompiled.

PS: This is NOT a solution; was meant to be a workaround.

HTML input fields does not get focus when clicked

I just found another possible reason for this issue, some input textboxes were missing the closing "/", so i had <input ...> when the correct form is <input ... />. That fixed it for me.

NULL values inside NOT IN clause

this is for Boy:

select party_code 
from abc as a
where party_code not in (select party_code 
                         from xyz 
                         where party_code = a.party_code);

this works regardless of ansi settings

Spring MVC 4: "application/json" Content Type is not being set correctly

As other people have commented, because the return type of your method is String Spring won't feel need to do anything with the result.

If you change your signature so that the return type is something that needs marshalling, that should help:

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Map<String, Object> bar() {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("test", "jsonRestExample");
    return map;
}

How to set the maximum memory usage for JVM?

use the arguments -Xms<memory> -Xmx<memory>. Use M or G after the numbers for indicating Megs and Gigs of bytes respectively. -Xms indicates the minimum and -Xmx the maximum.

How to use in jQuery :not and hasClass() to get a specific element without a class

Use the not function instead:

var lastOpenSite = $(this).siblings().not('.closedTab');

hasClass only tests whether an element has a class, not will remove elements from the selected set matching the provided selector.

How do I install jmeter on a Mac?

  1. Download apache-Jmeter.zip file
  2. Unzip it
  3. Open terminal-> go to apache-Jmeter/bin
  4. sh jmeter.sh

Git:nothing added to commit but untracked files present

Please Follow this process

First of all install git bash and create a repository on git

1) Go to working directory where the file exist which you want to push on remote and create .git folder by

$ git init

2) Add the files in your new local repository.

$ git add .

Note: while you are in same folder make sure you have placed dot after command if you putting path or not putting dot that will create ambiguity

3) Commit the files that you've staged in your local repository.

$ git commit -m "First commit"**

4) after this go to git repository and copy remote URL

$ git remote add origin *remote repository URL

5)

$ git remote -v

Note: this will ask for user.email and user.name just put it as per config

6)

$ git push origin master

this will push whole committed code to FILE.git on repository

And I think we done

Getting the current date in SQL Server?

As you are using SQL Server 2008, go with Martin's answer.

If you find yourself needing to do it in SQL Server 2005 where you don't have access to the Date column type, I'd use:

SELECT DATEADD(DAY, DATEDIFF(DAY, 0, GETDATE()), 0)

SQLFiddle

How to set tbody height with overflow scroll

By default overflow does not apply to table group elements unless you give a display:block to <tbody> also you have to give a position:relative and display: block to <thead>. Check the DEMO.

.fixed {
  width:350px;
  table-layout: fixed;
  border-collapse: collapse;
}
.fixed th {
  text-decoration: underline;
}
.fixed th,
.fixed td {
  padding: 5px;
  text-align: left;
  min-width: 200px;
}


.fixed thead {
  background-color: red;
  color: #fdfdfd;
}
.fixed thead tr {
  display: block;
  position: relative;
}
.fixed tbody {
  display: block;
  overflow: auto;
  width: 100%;
  height: 100px;
  overflow-y: scroll;
    overflow-x: hidden;
}

IDEA: javac: source release 1.7 requires target release 1.7

I've found required options ('target bytecode version') in settings > compiler > java compiler in my case (intelij idea 12.1.3)

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

I am using Chrome version 21 with SQL 2008 R2 SP1 and none of the above fixes worked for me. Below is the code that did work, as with the other answers I added this bit of code to Append to "C:\Program Files\Microsoft SQL Server\MSRS10_50.MSSQLSERVER\Reporting Services\ReportManager\js\ReportingServices.js" (on the SSRS Server) :

//Fix to allow Chrome to display SSRS Reports
function pageLoad() { 
    var element = document.getElementById("ctl31_ctl09");
    if (element) 
    {
        element.style.overflow = "visible";         
    } 
}

Jenkins pipeline how to change to another folder

Use WORKSPACE environment variable to change workspace directory.

If doing using Jenkinsfile, use following code :

dir("${env.WORKSPACE}/aQA"){
    sh "pwd"
}

Creating a chart in Excel that ignores #N/A or blank cells

I found a way to do it.

you can do an x,y scatterplot. it will ignore null records (i.e. rows)

MySQL: is a SELECT statement case sensitive?

Try with:

order by lower(column_name) asc;

JavaScript: Passing parameters to a callback function

function tryMe(param1, param2) {
  console.log(param1 + " and " + param2);
}

function tryMe2(param1) {
  console.log(param1);
}

function callbackTester(callback, ...params) {
  callback(...params);
}



callbackTester(tryMe, "hello", "goodbye");

callbackTester(tryMe2, "hello");

read more about the spread syntax

SmtpException: Unable to read data from the transport connection: net_io_connectionclosed

I've tried all the answers above but still get this error with Office 365 account. The code seems to work fine with Google account and smtp.gmail.com when allowing less secure apps.

Any other suggestions that I could try?

Here is the code that I'm using

int port = 587;
string host = "smtp.office365.com";
string username = "[email protected]";
string password = "password";
string mailFrom = "[email protected]";
string mailTo = "[email protected]";
string mailTitle = "Testtitle";
string mailMessage = "Testmessage";

using (SmtpClient client = new SmtpClient())
{
    MailAddress from = new MailAddress(mailFrom);
    MailMessage message = new MailMessage
    {
        From = from
    };
    message.To.Add(mailTo);
    message.Subject = mailTitle;
    message.Body = mailMessage;
    message.IsBodyHtml = true;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Host = host;
    client.Port = port;
    client.EnableSsl = true;
    client.Credentials = new NetworkCredential
    {
        UserName = username,
        Password = password
    }; 
    client.Send(message);
}

UPDATE AND HOW I SOLVED IT:

Solved problem by changing Smtp Client to Mailkit. The System.Net.Mail Smtp Client is now not recommended to use by Microsoft because of security issues and you should instead be using MailKit. Using Mailkit gave me clearer error messages that I could understand finding the root cause of the problem (license issue). You can get Mailkit by downloading it as a Nuget Package.

Read documentation about Smtp Client for more information: https://docs.microsoft.com/es-es/dotnet/api/system.net.mail.smtpclient?redirectedfrom=MSDN&view=netframework-4.7.2

Here is how I implemented SmtpClient with MailKit

        int port = 587;
        string host = "smtp.office365.com";
        string username = "[email protected]";
        string password = "password";
        string mailFrom = "[email protected]";
        string mailTo = "[email protected]";
        string mailTitle = "Testtitle";
        string mailMessage = "Testmessage";

        var message = new MimeMessage();
        message.From.Add(new MailboxAddress(mailFrom));
        message.To.Add(new MailboxAddress(mailTo));
        message.Subject = mailTitle;
        message.Body = new TextPart("plain") { Text = mailMessage };

        using (var client = new SmtpClient())
        {
            client.Connect(host , port, SecureSocketOptions.StartTls);
            client.Authenticate(username, password);

            client.Send(message);
            client.Disconnect(true);
        }

Why is 2 * (i * i) faster than 2 * i * i in Java?

Byte codes: https://cs.nyu.edu/courses/fall00/V22.0201-001/jvm2.html Byte codes Viewer: https://github.com/Konloch/bytecode-viewer

On my JDK (Windows 10 64 bit, 1.8.0_65-b17) I can reproduce and explain:

public static void main(String[] args) {
    int repeat = 10;
    long A = 0;
    long B = 0;
    for (int i = 0; i < repeat; i++) {
        A += test();
        B += testB();
    }

    System.out.println(A / repeat + " ms");
    System.out.println(B / repeat + " ms");
}


private static long test() {
    int n = 0;
    for (int i = 0; i < 1000; i++) {
        n += multi(i);
    }
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) {
        n += multi(i);
    }
    long ms = (System.currentTimeMillis() - startTime);
    System.out.println(ms + " ms A " + n);
    return ms;
}


private static long testB() {
    int n = 0;
    for (int i = 0; i < 1000; i++) {
        n += multiB(i);
    }
    long startTime = System.currentTimeMillis();
    for (int i = 0; i < 1000000000; i++) {
        n += multiB(i);
    }
    long ms = (System.currentTimeMillis() - startTime);
    System.out.println(ms + " ms B " + n);
    return ms;
}

private static int multiB(int i) {
    return 2 * (i * i);
}

private static int multi(int i) {
    return 2 * i * i;
}

Output:

...
405 ms A 785527736
327 ms B 785527736
404 ms A 785527736
329 ms B 785527736
404 ms A 785527736
328 ms B 785527736
404 ms A 785527736
328 ms B 785527736
410 ms
333 ms

So why? The byte code is this:

 private static multiB(int arg0) { // 2 * (i * i)
     <localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>

     L1 {
         iconst_2
         iload0
         iload0
         imul
         imul
         ireturn
     }
     L2 {
     }
 }

 private static multi(int arg0) { // 2 * i * i
     <localVar:index=0, name=i , desc=I, sig=null, start=L1, end=L2>

     L1 {
         iconst_2
         iload0
         imul
         iload0
         imul
         ireturn
     }
     L2 {
     }
 }

The difference being: With brackets (2 * (i * i)):

  • push const stack
  • push local on stack
  • push local on stack
  • multiply top of stack
  • multiply top of stack

Without brackets (2 * i * i):

  • push const stack
  • push local on stack
  • multiply top of stack
  • push local on stack
  • multiply top of stack

Loading all on the stack and then working back down is faster than switching between putting on the stack and operating on it.

How can I delete a file from a Git repository?

git rm will only remove the file on this branch from now on, but it remains in history and git will remember it.

The right way to do it is with git filter-branch, as others have mentioned here. It will rewrite every commit in the history of the branch to delete that file.

But, even after doing that, git can remember it because there can be references to it in reflog, remotes, tags and such.

If you want to completely obliterate it in one step, I recommend you to use git forget-blob

https://ownyourbits.com/2017/01/18/completely-remove-a-file-from-a-git-repository-with-git-forget-blob/

It is easy, just do git forget-blob file1.txt.

This will remove every reference, do git filter-branch, and finally run the git garbage collector git gc to completely get rid of this file in your repo.

Insert string at specified position

$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);

substr on PHP Manual

How can I pass a Bitmap object from one activity to another

In my case, the way mentioned above didn't worked for me. Every time I put the bitmap in the intent, the 2nd activity didn't start. The same happened when I passed the bitmap as byte[].

I followed this link and it worked like a charme and very fast:

package your.packagename

import android.graphics.Bitmap;

public class CommonResources { 
      public static Bitmap photoFinishBitmap = null;
}

in my 1st acitiviy:

Constants.photoFinishBitmap = photoFinishBitmap;
Intent intent = new Intent(mContext, ImageViewerActivity.class);
startActivity(intent);

and here is the onCreate() of my 2nd Activity:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap photo = Constants.photoFinishBitmap;
    if (photo != null) {
        mViewHolder.imageViewerImage.setImageDrawable(new BitmapDrawable(getResources(), photo));
    }
}

Assign a login to a user created without login (SQL Server)

I found that this question was still relevant but not clearly answered in my case.

Using SQL Server 2012 with an orphaned SQL_USER this was the fix;

USE databasename                      -- The database I had recently attached
EXEC sp_change_users_login 'Report'   -- Display orphaned users
EXEC sp_change_users_login 'Auto_Fix', 'UserName', NULL, 'Password'

Generate list of all possible permutations of a string

Ruby answer that works:

class String
  def each_char_with_index
    0.upto(size - 1) do |index|
      yield(self[index..index], index)
    end
  end
  def remove_char_at(index)
    return self[1..-1] if index == 0
    self[0..(index-1)] + self[(index+1)..-1]
  end
end

def permute(str, prefix = '')
  if str.size == 0
    puts prefix
    return
  end
  str.each_char_with_index do |char, index|
    permute(str.remove_char_at(index), prefix + char)
  end
end

# example
# permute("abc")

Pass connection string to code-first DbContext

A little late to the game here, but another option is:

public class NerdDinners : DbContext
{
    public NerdDinners(string connString)
    {
        this.Database.Connection.ConnectionString = connString;
    }
    public DbSet<Dinner> Dinners { get; set; }
}

How to get Android GPS location

This code have one problem:

int latitude = (int) (location.getLatitude());
int longitude = (int) (location.getLongitude());

You can change int to double

double latitude = location.getLatitude();
double longitude = location.getLongitude();

What is SOA "in plain english"?

SOA is a buzzword that was invented by technology vendors to help sell their Enterprise Service Bus related technologies. The idea is that you make your little island applications in the enterprise (eg: accounting system, stock control system, etc) all expose services, so that they can be orchestrated flexibly into 'applications', or rather become parts of aggregate enterprise scoped business logic.

Basically a load of old bollocks that nearly never works, because it misses the point that the reasons why technology is the way it is in an organisation is down to culture, evolution, history of the firm, and the lock in is so high that any attempt to restructure the technology is bound to fail.

What is the difference between CloseableHttpClient and HttpClient in Apache HttpClient API?

  • The main entry point of the HttpClient API is the HttpClient interface.
  • The most essential function of HttpClient is to execute HTTP methods.
  • Execution of an HTTP method involves one or several HTTP request / HTTP response exchanges, usually handled internally by HttpClient.

  • CloseableHttpClient is an abstract class which is the base implementation of HttpClient that also implements java.io.Closeable.
  • Here is an example of request execution process in its simplest form:

    CloseableHttpClient httpclient = HttpClients.createDefault();
    HttpGet httpget = new HttpGet("http://localhost/");
    CloseableHttpResponse response = httpclient.execute(httpget);
    try {
        //do something
    } finally {
        response.close();
    }

  • HttpClient resource deallocation: When an instance CloseableHttpClient is no longer needed and is about to go out of scope the connection manager associated with it must be shut down by calling the CloseableHttpClient#close() method.

    CloseableHttpClient httpclient = HttpClients.createDefault();
    try {
        //do something
    } finally {
        httpclient.close();
    }

see the Reference to learn fundamentals.


@Scadge Since Java 7, Use of try-with-resources statement ensures that each resource is closed at the end of the statement. It can be used both for the client and for each response

try(CloseableHttpClient httpclient = HttpClients.createDefault()){

    // e.g. do this many times
    try (CloseableHttpResponse response = httpclient.execute(httpget)) {
    //do something
    }

    //do something else with httpclient here
}

How to insert a line break <br> in markdown

Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so

let markdown = `
    1. Apple
    2. Mango
     this is juicy
    3. Orange
`

Can I use a min-height for table, tr or td?

In CSS 2.1, the effect of 'min-height' and 'max-height' on tables, inline tables, table cells, table rows, and row groups is undefined.

So try wrapping the content in a div, and give the div a min-height jsFiddle here

<table cellspacing="0" cellpadding="0" border="0" style="width:300px">
    <tbody>
        <tr>
            <td>
                <div style="min-height: 100px; background-color: #ccc">
                    Hello World !
                </div>
            </td>
            <td>
                <div style="min-height: 100px; background-color: #f00">
                    Good Morning !
                </div>
            </td>
        </tr>
    </tbody>
</table>

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

For most of the people still receiving the error after fixing project properties, you probably installed Java 7 SDK when setting up your environment, but it is not currently supported for Android development.

As the error message sais, you should have installed Java 5.0 or 6.0, but Java 7 was found.

If you fix project properties without first installing Java 5 or 6, you will see the same error again.

  • So first, ensure you have Java SDK 5 or 6 installed, or install it.
  • Check your environment variable (JAVA_HOME) is pointing to SDK 5/6.

And then:

  • Check that Eclipse is using SDK 5/6 by default (Window => Prefs. => Java => Compiler
  • Disable Project Specific Settings (Project Properties => Java Compiler)
  • Fix Project Properties

OR

  • Leave Eclipse using JDK 7 by default.
  • Enable Project Specific Settings (Project Properties => Java Compiler)
  • Select Compiler Compliance 1.5 or 1.6 (Project Properties => Java Compiler)

Using Linq to get the last N elements of a collection?

Honestly I'm not super proud of the answer, but for small collections you could use the following:

var lastN = collection.Reverse().Take(n).Reverse();

A bit hacky but it does the job ;)

How to link to a <div> on another page?

You simply combine the ideas of a link to another page, as with href=foo.html, and a link to an element on the same page, as with href=#bar, so that the fragment like #bar is written immediately after the URL that refers to another page:

<a href="foo.html#bar">Some nice link text</a>

The target is specified the same was as when linking inside one page, e.g.

<div id="bar">
<h2>Some heading</h2>
Some content
</div>

or (if you really want to link specifically to a heading only)

<h2 id="bar">Some heading</h2>

How to test if string exists in file with Bash?

grep -Fxq "String to be found" | ls -a
  • grep will helps you to check content
  • ls will list all the Files

Setting multiple attributes for an element at once with JavaScript

You could make a helper function:

function setAttributes(el, attrs) {
  for(var key in attrs) {
    el.setAttribute(key, attrs[key]);
  }
}

Call it like this:

setAttributes(elem, {"src": "http://example.com/something.jpeg", "height": "100%", ...});

MySQL - Select the last inserted row easiest way

In concurrency, the latest record may not be the record you just entered. It may better to get the latest record using the primary key.

If it is a auto increment field, use SELECT LAST_INSERT_ID(); to get the id you just created.

How permission can be checked at runtime without throwing SecurityException?

Sharing my methods in case someone needs them:

 /** Determines if the context calling has the required permission
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermission(Context context, String permission) {

    int res = context.checkCallingOrSelfPermission(permission);

    Log.v(TAG, "permission: " + permission + " = \t\t" + 
    (res == PackageManager.PERMISSION_GRANTED ? "GRANTED" : "DENIED"));

    return res == PackageManager.PERMISSION_GRANTED;

}

/** Determines if the context calling has the required permissions
 * @param context - the IPC context
 * @param permissions - The permissions to check
 * @return true if the IPC has the granted permission
 */
public static boolean hasPermissions(Context context, String... permissions) {

    boolean hasAllPermissions = true;

    for(String permission : permissions) {
        //you can return false instead of assigning, but by assigning you can log all permission values
        if (! hasPermission(context, permission)) {hasAllPermissions = false; }
    }

    return hasAllPermissions;

}

And to call it:

boolean hasAndroidPermissions = SystemUtils.hasPermissions(mContext, new String[] {
                android.Manifest.permission.ACCESS_WIFI_STATE,
                android.Manifest.permission.READ_PHONE_STATE,
                android.Manifest.permission.ACCESS_NETWORK_STATE,
                android.Manifest.permission.INTERNET,
        });

What is the documents directory (NSDocumentDirectory)?

You can access documents directory using this code it is basically used for storing file in plist format:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
return documentsDirectory;

asp.net validation to make sure textbox has integer values

There are several different ways you can handle this. You could add a RequiredFieldValidator as well as a RangeValidator (if that works for your case) or you could add a CustomFieldValidator.

Link to the CustomFieldValidator: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.customvalidator%28VS.71%29.aspx

Link to MSDN Article on ASP.NET Validation: http://msdn.microsoft.com/en-us/library/aa479045.aspx

JQuery add class to parent element

Specify the optional selector to target what you want:

jQuery(this).parent('li').addClass('yourClass');

Or:

jQuery(this).parents('li').addClass('yourClass');

Using a scanner to accept String input and storing in a String Array

Please correct me if I'm wrong.`

public static void main(String[] args) {

    Scanner na = new Scanner(System.in);
    System.out.println("Please enter the number of contacts: ");
    int num = na.nextInt();

    String[] contactName = new String[num];
    String[] contactPhone = new String[num];
    String[] contactAdd1 = new String[num];
    String[] contactAdd2 = new String[num];

    Scanner input = new Scanner(System.in);

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

        System.out.println("Enter contacts name: " + (i+1));
        contactName[i] = input.nextLine();

        System.out.println("Enter contacts addressline1: " + (i+1));
        contactAdd1[i] = input.nextLine();

        System.out.println("Enter contacts addressline2: " + (i+1));
        contactAdd2[i] = input.nextLine();

        System.out.println("Enter contact phone number: " + (i+1));
        contactPhone[i] = input.nextLine();

    }

    for (int i = 0; i < num; i++) {
        System.out.println("Contact Name No." + (i+1) + " is "+contactName[i]);
        System.out.println("First Contacts Address No." + (i+1) + " is "+contactAdd1[i]);
        System.out.println("Second Contacts Address No." + (i+1) + " is "+contactAdd2[i]);
        System.out.println("Contact Phone Number No." + (i+1) + " is "+contactPhone[i]);
    }
}

`

syntax error, unexpected T_VARIABLE

If that is the entire line, it very well might be because you are missing a ; at the end of the line.

How do I set log4j level on the command line?

These answers actually dissuaded me from trying the simplest possible thing! Simply specify a threshold for an appender (say, "console") in your log4j.configuration like so:

log4j.appender.console.threshold=${my.logging.threshold}

Then, on the command line, include the system property -Dlog4j.info -Dmy.logging.threshold=INFO. I assume that any other property can be parameterized in this way, but this is the easiest way to raise or lower the logging level globally.

Android sqlite how to check if a record exists

SQLiteDatabase sqldb = MyProvider.db;
String Query = "Select * from " + TABLE_NAME ;
Cursor cursor = sqldb.rawQuery(Query, null);
cursor.moveToLast(); //if you not place this cursor.getCount() always give same integer (1) or current position of cursor.

if(cursor.getCount()<=0){
    Log.v("tag","if 1 "+cursor.getCount());
    return false;
}
Log.v("tag","2 else  "+cursor.getCount());

return true;

if you not use cursor.moveToLast();

cursor.getCount() always give same integer (1) or current position of cursor.

Get Multiple Values in SQL Server Cursor

This should work:

DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table; 
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0  
BEGIN  

       --Do stuff with scalar values

       FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;

Read .csv file in C

Thought I'd share this code. It's fairly simple, but effective. It parses comma-separated files with parenthesis. You can easily modify it to suit your needs.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>


int main(int argc, char *argv[])
{
  //argv[1] path to csv file
  //argv[2] number of lines to skip
  //argv[3] length of longest value (in characters)

  FILE *pfinput;
  unsigned int nSkipLines, currentLine, lenLongestValue;
  char *pTempValHolder;
  int c;
  unsigned int vcpm; //value character marker
  int QuotationOnOff; //0 - off, 1 - on

  nSkipLines = atoi(argv[2]);
  lenLongestValue = atoi(argv[3]);

  pTempValHolder = (char*)malloc(lenLongestValue);  

  if( pfinput = fopen(argv[1],"r") ) {

    rewind(pfinput);

    currentLine = 1;
    vcpm = 0;
    QuotationOnOff = 0;

    //currentLine > nSkipLines condition skips ignores first argv[2] lines
    while( (c = fgetc(pfinput)) != EOF)
    {
       switch(c)
       {
          case ',':
            if(!QuotationOnOff && currentLine > nSkipLines) 
            {
              pTempValHolder[vcpm] = '\0';
              printf("%s,",pTempValHolder);
              vcpm = 0;
            }
            break;
          case '\n':
            if(currentLine > nSkipLines)
            {
              pTempValHolder[vcpm] = '\0';
              printf("%s\n",pTempValHolder);
              vcpm = 0;
            }
            currentLine++;
            break;
          case '\"':
            if(currentLine > nSkipLines)
            {
              if(!QuotationOnOff) {
                QuotationOnOff = 1;
                pTempValHolder[vcpm] = c;
                vcpm++;
              } else {
                QuotationOnOff = 0;
                pTempValHolder[vcpm] = c;
                vcpm++;
              }
            }
            break;
          default:
            if(currentLine > nSkipLines)
            {
              pTempValHolder[vcpm] = c;
              vcpm++;
            }
            break;
       }
    }

    fclose(pfinput); 
    free(pTempValHolder);

  }

  return 0;
}

Variables within app.config/web.config

You can use environment variables in your app.config for that scenario you describe

<configuration>
  <appSettings>
    <add key="Dir1" value="%MyBaseDir%\Dir1"/>
  </appSettings>
</configuration>

Then you can easily get the path with:

var pathFromConfig = ConfigurationManager.AppSettings["Dir1"];
var expandedPath = Environment.ExpandEnvironmentVariables(pathFromConfig);

try/catch with InputMismatchException creates infinite loop

YOu can also try the following

   do {
        try {
            System.out.println("Enter first num: ");
            n1 = Integer.parseInt(input.next());

            System.out.println("Enter second num: ");
            n2 = Integer.parseInt(input.next());

            nQuotient = n1/n2;

            bError = false;
        } 
        catch (Exception e) {
            System.out.println("Error!");
            input.reset();
        }
    } while (bError);

SELECT *, COUNT(*) in SQLite

If you want to count the number of records in your table, simply run:

    SELECT COUNT(*) FROM your_table;

Alert handling in Selenium WebDriver (selenium 2) with Java

try 
    {
        //Handle the alert pop-up using seithTO alert statement
        Alert alert = driver.switchTo().alert();

        //Print alert is present
        System.out.println("Alert is present");

        //get the message which is present on pop-up
        String message = alert.getText();

        //print the pop-up message
        System.out.println(message);

        alert.sendKeys("");
        //Click on OK button on pop-up
        alert.accept();
    } 
    catch (NoAlertPresentException e) 
    {
        //if alert is not present print message
        System.out.println("alert is not present");
    }

Android Split string

android split string by comma

String data = "1,Diego Maradona,Footballer,Argentina";
String[] items = data.split(",");
for (String item : items)
{
    System.out.println("item = " + item);
}

How do I upload a file with metadata using a REST web service?

I realize this is a very old question, but hopefully this will help someone else out as I came upon this post looking for the same thing. I had a similar issue, just that my metadata was a Guid and int. The solution is the same though. You can just make the needed metadata part of the URL.

POST accepting method in your "Controller" class:

public Task<HttpResponseMessage> PostFile(string name, float latitude, float longitude)
{
    //See http://stackoverflow.com/a/10327789/431906 for how to accept a file
    return null;
}

Then in whatever you're registering routes, WebApiConfig.Register(HttpConfiguration config) for me in this case.

config.Routes.MapHttpRoute(
    name: "FooController",
    routeTemplate: "api/{controller}/{name}/{latitude}/{longitude}",
    defaults: new { }
);

Convert java.util.date default format to Timestamp in Java

Best one

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;

How to use CSS to surround a number with a circle?

Late to the party, but here is a bootstrap-only solution that has worked for me. I'm using Bootstrap 4:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<body>_x000D_
<div class="row mt-4">_x000D_
<div class="col-md-12">_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">1</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">2</span>_x000D_
<span class="bg-dark text-white rounded-circle px-3 py-1 mx-2 h3">3</span>_x000D_
</div>_x000D_
</div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

You basically add bg-dark text-white rounded-circle px-3 py-1 mx-2 h3 classes to your <span> (or whatever) element and you're done.

Note that you might need to adjust margin and padding classes if your content has more than one digits.

How can I set up an editor to work with Git on Windows?

Based on VonC's suggestion, this worked for me (was driving me crazy):

git config --global core.editor "'C:/Program Files (x86)/Sublime Text 3/subl.exe' -wait"

Omitting -wait can cause problems, especially if you are working with Gerrit and change ids that have to be manually copied to the bottom of your commit message.

Speed up rsync with Simultaneous/Concurrent File Transfers?

You can use xargs which supports running many processes at a time. For your case it will be:

ls -1 /main/files | xargs -I {} -P 5 -n 1 rsync -avh /main/files/{} /main/filesTest/

How do you get a directory listing sorted by creation date in python?

I've done this in the past for a Python script to determine the last updated files in a directory:

import glob
import os

search_dir = "/mydir/"
# remove anything from the list that is not a file (directories, symlinks)
# thanks to J.F. Sebastion for pointing out that the requirement was a list 
# of files (presumably not including directories)  
files = list(filter(os.path.isfile, glob.glob(search_dir + "*")))
files.sort(key=lambda x: os.path.getmtime(x))

That should do what you're looking for based on file mtime.

EDIT: Note that you can also use os.listdir() in place of glob.glob() if desired - the reason I used glob in my original code was that I was wanting to use glob to only search for files with a particular set of file extensions, which glob() was better suited to. To use listdir here's what it would look like:

import os

search_dir = "/mydir/"
os.chdir(search_dir)
files = filter(os.path.isfile, os.listdir(search_dir))
files = [os.path.join(search_dir, f) for f in files] # add path to each file
files.sort(key=lambda x: os.path.getmtime(x))

Remove duplicate elements from array in Ruby

array = array.uniq

uniq removes all duplicate elements and retains all unique elements in the array.

This is one of many beauties of the Ruby language.

Force “landscape” orientation mode

It is now possible with the HTML5 webapp manifest. See below.


Original answer:

You can't lock a website or a web application in a specific orientation. It goes against the natural behaviour of the device.

You can detect the device orientation with CSS3 media queries like this:

@media screen and (orientation:portrait) {
    // CSS applied when the device is in portrait mode
}

@media screen and (orientation:landscape) {
    // CSS applied when the device is in landscape mode
}

Or by binding a JavaScript orientation change event like this:

document.addEventListener("orientationchange", function(event){
    switch(window.orientation) 
    {  
        case -90: case 90:
            /* Device is in landscape mode */
            break; 
        default:
            /* Device is in portrait mode */
    }
});

Update on November 12, 2014: It is now possible with the HTML5 webapp manifest.

As explained on html5rocks.com, you can now force the orientation mode using a manifest.json file.

You need to include those line into the json file:

{
    "display":      "standalone", /* Could be "fullscreen", "standalone", "minimal-ui", or "browser" */
    "orientation":  "landscape", /* Could be "landscape" or "portrait" */
    ...
}

And you need to include the manifest into your html file like this:

<link rel="manifest" href="manifest.json">

Not exactly sure what the support is on the webapp manifest for locking orientation mode, but Chrome is definitely there. Will update when I have the info.

How do I drag and drop files into an application?

Another common gotcha is thinking you can ignore the Form DragOver (or DragEnter) events. I typically use the Form's DragOver event to set the AllowedEffect, and then a specific control's DragDrop event to handle the dropped data.

Material effect on button with background color

Use backgroundTint instead of background

How can I find the latitude and longitude from address?

This is how you can find the latitude and longitude of where we have click on map.

public boolean onTouchEvent(MotionEvent event, MapView mapView) 
{   
    //---when user lifts his finger---
    if (event.getAction() == 1) 
    {                
        GeoPoint p = mapView.getProjection().fromPixels(
            (int) event.getX(),
            (int) event.getY());

        Toast.makeText(getBaseContext(), 
             p.getLatitudeE6() / 1E6 + "," + 
             p.getLongitudeE6() /1E6 , 
             Toast.LENGTH_SHORT).show();
    }                            
    return false;
} 

it works well.

To get the location's address we can use geocoder class.

Run Function After Delay

$(document).ready(function() {

  // place this within dom ready function
  function showpanel() {     
    $(".navigation").hide();
    $(".page").children(".panel").fadeIn(1000);
 }

 // use setTimeout() to execute
 setTimeout(showpanel, 1000)

});

For more see here

PHP - regex to allow letters and numbers only

try this way .eregi("[^A-Za-z0-9.]", $value)

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Here is a more complete example using a fieldset for accessibility reasons and specifying the first button as the default. Without a fieldset, what the radio buttons are for as a whole can not be programmatically determined.

Model

public class MyModel
{
    public bool IsMarried { get; set; }
}

View

<fieldset>
    <legend>Married</legend>

    @Html.RadioButtonFor(e => e.IsMarried, true, new { id = "married-true" })
    @Html.Label("married-true", "Yes")

    @Html.RadioButtonFor(e => e.IsMarried, false, new { id = "married-false" })
    @Html.Label("married-false", "No")
</fieldset>

You can add a @checked argument to the anonymous object to set the radio button as the default:

new { id = "married-true", @checked = 'checked' }

Note that you can bind to a string by replacing true and false with the string values.

How to get nth jQuery element

For iterations using a selector doesn't seem to make any sense though:

var some = $( '...' );

for( i = some.length -1; i>=0; --i )
{
   // Have to transform in a jquery object again:
   //
   var item = $( some[ i ] );

   // use item at will
   // ...
}

How to use ternary operator in razor (specifically on HTML attributes)?

in my problem I want the text of anchor <a>text</a> inside my view to be based on some value and that text is retrieved form App string Resources

so, this @() is the solution

<a href='#'>
      @(Model.ID == 0 ? Resource_en.Back : Resource_en.Department_View_DescartChanges)
</a>

if the text is not from App string Resources use this

@(Model.ID == 0 ? "Back" :"Descart Changes")

How do I compile and run a program in Java on my Mac?

Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/

Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/


Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:

  • The source code editor
    • With syntax highlighting, colors and other visual cues
    • Easy cross-referencing to the documentation to facilitate learning
  • Compiler
    • Run the code with one click
    • Get notified of errors/mistakes as you go

As you gain more experience, you'll start to appreciate the rest of its rich set of features.

Return from a promise then()

When you return something from a then() callback, it's a bit magic. If you return a value, the next then() is called with that value. However, if you return something promise-like, the next then() waits on it, and is only called when that promise settles (succeeds/fails).

Source: https://web.dev/promises/#queuing-asynchronous-actions

Get MD5 hash of big files in Python

Here's my version of @Piotr Czapla's method:

def md5sum(filename):
    md5 = hashlib.md5()
    with open(filename, 'rb') as f:
        for chunk in iter(lambda: f.read(128 * md5.block_size), b''):
            md5.update(chunk)
    return md5.hexdigest()

Uninitialized constant ActiveSupport::Dependencies::Mutex (NameError)

I'm posting my solution for the other sleep-deprived souls out there:

If you're using RVM, double-check that you're in the correct folder, using the correct ruby version and gemset. I had an array of terminal tabs open, and one of them was in a different directory. typing "rails console" produced the error because my default rails distro is 2.3.x.

I noticed the error on my part, cd'd to the correct directory, and my .rvmrc file did the rest.

RVM is not like Git. In git, changing branches in one shell changes it everywhere. It's literally rewriting the files in question. RVM, on the other hand, is just setting shell variables, and must be set for each new shell you open.

In case you're not familiar with .rvmrc, you can put a file with that name in any directory, and rvm will pick it up and use the version/gemset specified therein, whenever you change to that directory. Here's a sample .rvmrc file:

rvm use 1.9.2@turtles

This will switch to the latest version of ruby 1.9.2 in your RVM collection, using the gemset "turtles". Now you can open up a hundred tabs in Terminal (as I end up doing) and never worry about the ruby version it's pointing to.

Bash script prints "Command Not Found" on empty lines

I ran into this today, absentmindedly copying the dollar command prompt $ (ahead of a command string) into the script.

How do I calculate the date six months from the current date using the datetime Python module?

From this answer, see parsedatetime. Code example follows. More details: unit test with many natural-language -> YYYY-MM-DD conversion examples, and apparent parsedatetime conversion challenges/bugs.

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time, calendar
from datetime import date

# from https://github.com/bear/parsedatetime
import parsedatetime as pdt

def print_todays_date():
    todays_day_of_week = calendar.day_name[date.today().weekday()]
    print "today's date = " + todays_day_of_week + ', ' + \
                              time.strftime('%Y-%m-%d')

def convert_date(natural_language_date):
    cal = pdt.Calendar()
    (struct_time_date, success) = cal.parse(natural_language_date)
    if success:
        formal_date = time.strftime('%Y-%m-%d', struct_time_date)
    else:
        formal_date = '(conversion failed)'
    print '{0:12s} -> {1:10s}'.format(natural_language_date, formal_date)

print_todays_date()
convert_date('6 months')

The above code generates the following from a MacOSX machine:

$ ./parsedatetime_simple.py 
today's date = Wednesday, 2015-05-13
6 months     -> 2015-11-13
$ 

How to remove a build from itunes connect?

I had this problem. I'll share my ride on the learning curve.

First, I couldn't find how to reject the binary but remembered seeing it earlier today in the iTunesConnect App. So using the App I rejected the binary.

If you "mouse over" the rejected binary under the "Build" section you'll notice that a red circle icon with a - (i.e. a delete button) appears. Tap on this and then hit the save button at the top of the screen. Submitted binary is now gone.

You should now get all the notifications for the app being in state "Prepare for Upload" (email, App notification etc).

Xcode organiser was still giving me "Redundant Binary". After a bit of research I now understand the difference between "Version" & "Build". Version is what iTunes displays and the user sees. Build is just the internal tracking number. I had both at 2.3.0, I changed build to 2.3.0.1 and re-Archive. Now it validates and I can upload the new binary and re-submit. Hope that helps others!

Choosing the default value of an Enum type without having to change values

The default value of any enum is zero. So if you want to set one enumerator to be the default value, then set that one to zero and all other enumerators to non-zero (the first enumerator to have the value zero will be the default value for that enum if there are several enumerators with the value zero).

enum Orientation
{
    None = 0, //default value since it has the value '0'
    North = 1,
    East = 2,
    South = 3,
    West = 4
}

Orientation o; // initialized to 'None'

If your enumerators don't need explicit values, then just make sure the first enumerator is the one you want to be the default enumerator since "By default, the first enumerator has the value 0, and the value of each successive enumerator is increased by 1." (C# reference)

enum Orientation
{
    None, //default value since it is the first enumerator
    North,
    East,
    South,
    West
}

Orientation o; // initialized to 'None'

IIS sc-win32-status codes

Here's the list of all Win32 error codes. You can use this page to lookup the error code mentioned in IIS logs:
http://msdn.microsoft.com/en-us/library/ms681381.aspx

You can also use command line utility net to find information about a Win32 error code. The syntax would be:
net helpmsg Win32_Status_Code

forEach loop Java 8 for Map entry set

Stream API

public void iterateStreamAPI(Map<String, Integer> map) {
    map.entrySet().stream().forEach(e -> System.out.println(e.getKey() + ":"e.getValue()));
}

Installing ADB on macOS

Note for zsh users: replace all references to ~/.bash_profile with ~/.zshrc.

Option 1 - Using Homebrew

This is the easiest way and will provide automatic updates.

  1. Install the homebrew package manager

     /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
    
  2. Install adb

     brew install android-platform-tools
    
  3. Start using adb

     adb devices
    

Option 2 - Manually (just the platform tools)

This is the easiest way to get a manual installation of ADB and Fastboot.

  1. Delete your old installation (optional)

     rm -rf ~/.android-sdk-macosx/
    
  2. Navigate to https://developer.android.com/studio/releases/platform-tools.html and click on the SDK Platform-Tools for Mac link.

  3. Go to your Downloads folder

     cd ~/Downloads/
    
  4. Unzip the tools you downloaded

     unzip platform-tools-latest*.zip 
    
  5. Move them somewhere you won't accidentally delete them

     mkdir ~/.android-sdk-macosx
     mv platform-tools/ ~/.android-sdk-macosx/platform-tools
    
  6. Add platform-tools to your path

     echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
    
  7. Refresh your bash profile (or restart your terminal app)

     source ~/.bash_profile
    
  8. Start using adb

     adb devices
    

Option 3 - Manually (with SDK Manager)

  1. Delete your old installation (optional)

     rm -rf ~/.android-sdk-macosx/
    
  2. Download the Mac SDK Tools from the Android developer site under "Get just the command line tools". Make sure you save them to your Downloads folder.

  3. Go to your Downloads folder

     cd ~/Downloads/
    
  4. Unzip the tools you downloaded

     unzip tools_r*-macosx.zip 
    
  5. Move them somewhere you won't accidentally delete them

     mkdir ~/.android-sdk-macosx
     mv tools/ ~/.android-sdk-macosx/tools
    
  6. Run the SDK Manager

     sh ~/.android-sdk-macosx/tools/android
    
  7. Uncheck everything but Android SDK Platform-tools (optional)

enter image description here

  1. Click Install Packages, accept licenses, click Install. Close the SDK Manager window.

enter image description here

  1. Add platform-tools to your path

     echo 'export PATH=$PATH:~/.android-sdk-macosx/platform-tools/' >> ~/.bash_profile
    
  2. Refresh your bash profile (or restart your terminal app)

    source ~/.bash_profile
    
  3. Start using adb

    adb devices
    

Changing iframe src with Javascript

Maybe this can be helpful... It's plain html - no javascript:

_x000D_
_x000D_
<p>Click on link bellow to change iframe content:</p>_x000D_
<a href="http://www.bing.com" target="search_iframe">Bing</a> -_x000D_
<a href="http://en.wikipedia.org" target="search_iframe">Wikipedia</a> -_x000D_
<a href="http://google.com" target="search_iframe">Google</a> (not allowed in inframe)_x000D_
_x000D_
<iframe src="http://en.wikipedia.org" width="100%" height="100%" name="search_iframe"></iframe>
_x000D_
_x000D_
_x000D_

By the way some sites do not allow you to open them in iframe (security reasons - clickjacking)

How to upgrade rubygems

Or:

gem update `gem outdated | cut -d ' ' -f 1`

How to compare two strings are equal in value, what is the best method?

You can either use the == operator or the Object.equals(Object) method.

The == operator checks whether the two subjects are the same object, whereas the equals method checks for equal contents (length and characters).

if(objectA == objectB) {
   // objects are the same instance. i.e. compare two memory addresses against each other.
}

if(objectA.equals(objectB)) {
   // objects have the same contents. i.e. compare all characters to each other 
}

Which you choose depends on your logic - use == if you can and equals if you do not care about performance, it is quite fast anyhow.

String.intern() If you have two strings, you can internate them, i.e. make the JVM create a String pool and returning to you the instance equal to the pool instance (by calling String.intern()). This means that if you have two Strings, you can call String.intern() on both and then use the == operator. String.intern() is however expensive, and should only be used as an optimalization - it only pays off for multiple comparisons.

All in-code Strings are however already internated, so if you are not creating new Strings, you are free to use the == operator. In general, you are pretty safe (and fast) with

if(objectA == objectB || objectA.equals(objectB)) {

}

if you have a mix of the two scenarios. The inline

if(objectA == null ? objectB == null : objectA.equals(objectB)) {

}

can also be quite useful, it also handles null values since String.equals(..) checks for null.

Accessing items in an collections.OrderedDict by index

It is dramatically more efficient to use IndexedOrderedDict from the indexed package.

Following Niklas's comment, I have done a benchmark on OrderedDict and IndexedOrderedDict with 1000 entries.

In [1]: from numpy import *
In [2]: from indexed import IndexedOrderedDict
In [3]: id=IndexedOrderedDict(zip(arange(1000),random.random(1000)))
In [4]: timeit id.keys()[56]
1000000 loops, best of 3: 969 ns per loop

In [8]: from collections import OrderedDict
In [9]: od=OrderedDict(zip(arange(1000),random.random(1000)))
In [10]: timeit od.keys()[56]
10000 loops, best of 3: 104 µs per loop

IndexedOrderedDict is ~100 times faster in indexing elements at specific position in this specific case.

Is it possible to create a remote repo on GitHub from the CLI without opening browser?

This can be done with three commands:

curl -u 'nyeates' https://api.github.com/user/repos -d '{"name":"projectname","description":"This project is a test"}'
git remote add origin [email protected]:nyeates/projectname.git
git push origin master

(updated for v3 Github API)


Explanation of these commands...

Create github repo

    curl -u 'nyeates' https://api.github.com/user/repos -d '{"name":"projectname","description":"This project is a test"}'
  • curl is a unix command (above works on mac too) that retrieves and interacts with URLs. It is commonly already installed.
  • "-u" is a curl parameter that specifies the user name and password to use for server authentication.
    • If you just give the user name (as shown in example above) curl will prompt for a password.
    • If you do not want to have to type in the password, see githubs api documentation on Authentication
  • "-d" is a curl parameter that allows you to send POST data with the request
  • "name" is the only POST data required; I like to also include "description"
  • I found that it was good to quote all POST data with single quotes ' '

Define where to push to

git remote add origin [email protected]:nyeates/projectname.git
  • add definition for location and existance of connected (remote) repo on github
  • "origin" is a default name used by git for where the source came from
    • technically didnt come from github, but now the github repo will be the source of record
  • "[email protected]:nyeates" is a ssh connection that assumes you have already setup a trusted ssh keypair with github.

Push local repo to github

git push origin master
  • push to the origin remote (github) from the master local branch

Get restaurants near my location

Is this what you are looking for?

https://maps.googleapis.com/maps/api/place/search/xml?location=49.260691,-123.137784&radius=500&sensor=false&key=*PlacesAPIKey*&types=restaurant

types is optional

Turn off display errors using file "php.ini"

It is not enough in case of PHP fpm. It was one more configuration file which can enable display_error. You should find www.conf. In my case it is in directory /etc/php/7.1/fpm/pool.d/

You should find php_flag[display_errors] = on and disable it, php_flag[display_errors] = off. This should solve the issue.

get path for my .exe

in visualstudio 2008 you could use this code :

   var _assembly = System.Reflection.Assembly
               .GetExecutingAssembly().GetName().CodeBase;

   var _path = System.IO.Path.GetDirectoryName(_assembly) ;

Custom exception type

Use the throw statement.

JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".

If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.

How do I convert an integer to string as part of a PostgreSQL query?

You can cast an integer to a string in this way

intval::text

and so in your case

SELECT * FROM table WHERE <some integer>::text = 'string of numbers'

Javascript - object key->value

I use the following syntax:

objTest = {"error": true, "message": "test message"};

get error:

 var name = "error"
 console.log(objTest[name]);

get message:

 name = "message"
 console.log(objTest[name]);

Do HttpClient and HttpClientHandler have to be disposed between requests?

In my understanding, calling Dispose() is necessary only when it's locking resources you need later (like a particular connection). It's always recommended to free resources you're no longer using, even if you don't need them again, simply because you shouldn't generally be holding onto resources you're not using (pun intended).

The Microsoft example is not incorrect, necessarily. All resources used will be released when the application exits. And in the case of that example, that happens almost immediately after the HttpClient is done being used. In like cases, explicitly calling Dispose() is somewhat superfluous.

But, in general, when a class implements IDisposable, the understanding is that you should Dispose() of its instances as soon as you're fully ready and able. I'd posit this is particularly true in cases like HttpClient wherein it's not explicitly documented as to whether resources or connections are being held onto/open. In the case wherein the connection will be reused again [soon], you'll want to forgo Dipose()ing of it -- you're not "fully ready" in that case.

See also: IDisposable.Dispose Method and When to call Dispose

Loop and get key/value pair for JSON array using jQuery

You can get the values directly in case of one array like this:

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName'];  // return ''Doe'
result['Email']; // return '[email protected]'
result['Phone'];  // return '123'

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

Turn on the fusion logging, see this question for lots of advice on how to do that. Debugging mixed-mode apps loading problems can be a right royal pain. The fusion logging can be a big help.

How can I get selector from jQuery object

How about:

var selector = "*"
$(selector).click(function() {
    alert(selector);
});

I don't believe jQuery store the selector text that was used. After all, how would that work if you did something like this:

$("div").find("a").click(function() {
    // what would expect the 'selector' to be here?
});

jQuery make global variable

Your code looks fine except the possibility that if the variable declaration is inside a dom read handler then it will not be a global variable... it will be a closure variable

jQuery(function(){
    //here it is a closure variable
    var a_href;
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

To make the variable global, one solution is to declare the variable in global scope

var a_href;
jQuery(function(){
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

another is to set the variable as a property of the window object

window.a_href = $(this).attr('href')

Why console printing undefined

You are getting the output as undefined because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a element is clicked till that time the variable will have the value undefined. If you are not declaring the variable it will throw a ReferenceError

OpenCV & Python - Image too big to display

Try this:

image = cv2.imread("img/Demo.jpg")
image = cv2.resize(image,(240,240))

The image is now resized. Displaying it will render in 240x240.

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

How to check the value given is a positive or negative integer?

You should first check if the input value is interger with isNumeric() function. Then add the condition or greater than 0. This is the jQuery code for it.

function isPositiveInteger(n) {
        return ($.isNumeric(n) && (n > 0));
}

How to listen state changes in react.js?

The following lifecycle methods will be called when state changes. You can use the provided arguments and the current state to determine if something meaningful changed.

componentWillUpdate(object nextProps, object nextState)
componentDidUpdate(object prevProps, object prevState)

IOPub data rate exceeded in Jupyter notebook (when viewing image)

I ran into this using networkx and bokeh

This works for me in Windows 7 (taken from here):

  1. To create a jupyter_notebook_config.py file, with all the defaults commented out, you can use the following command line:

    $ jupyter notebook --generate-config

  2. Open the file and search for c.NotebookApp.iopub_data_rate_limit

  3. Comment out the line c.NotebookApp.iopub_data_rate_limit = 1000000 and change it to a higher default rate. l used c.NotebookApp.iopub_data_rate_limit = 10000000

This unforgiving default config is popping up in a lot of places. See git issues:

It looks like it might get resolved with the 5.1 release

Update:

Jupyter notebook is now on release 5.2.2. This problem should have been resolved. Upgrade using conda or pip.

Google Maps API OVER QUERY LIMIT per second limit

Instead of client-side geocoding

geocoder.geocode({
    'address': your_address
  }, function (results, status) {
     if (status == google.maps.GeocoderStatus.OK) {
       var geo_data = results[0];
       // your code ...
   } 
})

I would go to server-side geocoding API

var apikey = YOUR_API_KEY;
var query = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + apikey;
$.getJSON(query, function (data) {
  if (data.status === 'OK') { 
    var geo_data = data.results[0];
  } 
})

Can Google Chrome open local links?

LocalLinks now seems to be obsolete.

LocalExplorer seems to have taken it's place and provides similar functionality:

https://chrome.google.com/webstore/detail/local-explorer-file-manag/eokekhgpaakbkfkmjjcbffibkencdfkl/reviews?hl=en

It's basically a chrome plugin that replaces file:// links with localexplorer:// links, combined with an installable protocol handler that intercepts localexplorer:// links.

Best thing I can find available right now, I have no affiliation with the developer.

What's the difference between Apache's Mesos and Google's Kubernetes

Kubernetes and Mesos are a match made in heaven. Kubernetes enables the Pod (group of co-located containers) abstraction, along with Pod labels for service discovery, load-balancing, and replication control. Mesos provides the fine-grained resource allocations for pods across nodes in a cluster, and can make Kubernetes play nicely with other frameworks running on the same cluster resources.

from readme of kubernetes-mesos

Is it possible to decrypt SHA1

Since SHA-1 maps several byte sequences to one, you can't "decrypt" a hash, but in theory you can find collisions: strings that have the same hash.

It seems that breaking a single hash would cost about 2.7 million dollars worth of computer time currently, so your efforts are probably better spent somewhere else.

type object 'datetime.datetime' has no attribute 'datetime'

Datetime is a module that allows for handling of dates, times and datetimes (all of which are datatypes). This means that datetime is both a top-level module as well as being a type within that module. This is confusing.

Your error is probably based on the confusing naming of the module, and what either you or a module you're using has already imported.

>>> import datetime
>>> datetime
<module 'datetime' from '/usr/lib/python2.6/lib-dynload/datetime.so'>
>>> datetime.datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)

But, if you import datetime.datetime:

>>> from datetime import datetime
>>> datetime
<type 'datetime.datetime'>
>>> datetime.datetime(2001,5,1) # You shouldn't expect this to work 
                                # as you imported the type, not the module
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
>>> datetime(2001,5,1)
datetime.datetime(2001, 5, 1, 0, 0)

I suspect you or one of the modules you're using has imported like this: from datetime import datetime.

Why do people say that Ruby is slow?

Ruby is slower than C++ at a number of easily measurable tasks (e.g., doing code that is heavily dependent on floating point). This is not very surprising, but enough justification for some people to say that “Ruby is Slow” without qualification. They don't count the fact that it is far easier and safer to write Ruby code than C++.

The best fix is to use targeted modules written in another language (e.g., C, C++, Fortran) in your Ruby code. Those can do the heavy lifting and your scripts can focus on higher level coordination issues.

How to get the currently logged in user's user id in Django?

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is  : {{user.id|default: Unknown}} </p>

javascript: Disable Text Select

Just use this css method:

body{
    -webkit-touch-callout: none;
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

You can find the same answer here: How to disable text selection highlighting using CSS?

SQL Update Multiple Fields FROM via a SELECT Statement

I would write it this way

UPDATE s
SET    OrgAddress1 = bd.OrgAddress1,    OrgAddress2 = bd.OrgAddress2,    
     ...    DestZip = bd.DestZip
--select s.OrgAddress1, bd.OrgAddress1, s.OrgAddress2, bd.OrgAddress2, etc 
FROM    Shipment s
JOIN ProfilerTest.dbo.BookingDetails bd on  bd.MyID =s.MyID2
WHERE    bd.MyID = @MyId 

This way the join is explicit as implicit joins are a bad thing IMHO. You can run the commented out select (usually I specify the fields I'm updating old and new values next to each other) to make sure that what I am going to update is exactly what I meant to update.

Unable to execute dex: Multiple dex files define

I found below solution in eclipse...hope it works for you :)

Right click on the Project Name

Select Java Build Path, go to the tab Order and Export

Unchecked your .jar library's

C#: what is the easiest way to subtract time?

Check out all the DateTime methods here: http://msdn.microsoft.com/en-us/library/system.datetime.aspx

Add Returns a new DateTime that adds the value of the specified TimeSpan to the value of this instance.

AddDays Returns a new DateTime that adds the specified number of days to the value of this instance.

AddHours Returns a new DateTime that adds the specified number of hours to the value of this instance.

AddMilliseconds Returns a new DateTime that adds the specified number of milliseconds to the value of this instance.

AddMinutes Returns a new DateTime that adds the specified number of minutes to the value of this instance.

AddMonths Returns a new DateTime that adds the specified number of months to the value of this instance.

AddSeconds Returns a new DateTime that adds the specified number of seconds to the value of this instance.

AddTicks Returns a new DateTime that adds the specified number of ticks to the value of this instance.

AddYears Returns a new DateTime that adds the specified number of years to the value of this instance.

Eclipse - debugger doesn't stop at breakpoint

Go to Right click->Debug Configuration and check if too many debug instances are created. My issue was resolved when i deleted multiple debug instances from configuration and freshly started debugging.

Google Maps v2 - set both my location and zoom in

this is simple solution for your question

LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
map.animateCamera(yourLocation);

How to make/get a multi size .ico file?

Fresh answer 2018:

Step 1 Launch Microsoft Paint. Not Paint.Net but plain Paint

Step 2 Open the image you want to convert to icon format by clicking the “Paint” toolbar tab and selecting “Open.”

Step 3 Click the “Paint” tab, highlight the “Save As” option and select the “BMP picture” option. As 256-colored. There is a dropdown list.

Step 4 You have to open it in Paint.net now. Enter a file name for the icon and type “.ico” (without quotations) as the file extension. Select your preferred output folder for the icon and click “Save.”(still in bmp type) , exposing auto definition in saving parameters window.

This is a solution for those WHO DOESN'T WANT THE THIRD PARTY APPS TO GAIN PERMISSIONS ON THEIR COMP.
I use this simple way to create custom icons for folders on my desktop or documents.

How to set root password to null

If you know your Root Password and just wish to reset it then do as below:

  • Start MySQL Service from control panel > Administrative Tools > Services. (only if it was stopped by you earlier ! Otherwise, just skip this step)

  • Start MySQL Workbench

  • Type in this command/SQL line

    ALTER USER 'root'@'localhost' PASSWORD EXPIRE;

To reset any other user password... just type other user name instead of root.

Create list or arrays in Windows Batch

Yes, you may use both ways. If you just want to separate the elements and show they in separated lines, a list is simpler:

set list=A B C D

A list of values separated by space may be easily processed by for command:

(for %%a in (%list%) do (
   echo %%a
   echo/
)) > theFile.txt

You may also create an array this way:

setlocal EnableDelayedExpansion
set n=0
for %%a in (A B C D) do (
   set vector[!n!]=%%a
   set /A n+=1
)

and show the array elements this way:

(for /L %%i in (0,1,3) do (
   echo !vector[%%i]!
   echo/
)) > theFile.txt

For further details about array management in Batch files, see: Arrays, linked lists and other data structures in cmd.exe (batch) script

ATTENTION! You must know that all characters included in set command are inserted in the variable name (at left of equal sign), or in the variable value. For example, this command:

set list = "A B C D"

create a variable called list (list-space) with the value "A B C D" (space, quote, A, etc). For this reason, it is a good idea to never insert spaces in set commands. If you need to enclose the value in quotes, you must enclose both the variable name and its value:

set "list=A B C D"

PS - You should NOT use ECHO. in order to left blank lines! An alternative is ECHO/. For further details about this point, see: http://www.dostips.com/forum/viewtopic.php?f=3&t=774

How do I get the directory from a file's full path?

Use below mentioned code to get the folder path

Path.GetDirectoryName(filename);

This will return "C:\MyDirectory" in your case

How to specify preference of library path?

Add the path to where your new library is to LD_LIBRARY_PATH (it has slightly different name on Mac ...)

Your solution should work with using the -L/my/dir -lfoo options, at runtime use LD_LIBRARY_PATH to point to the location of your library.

Careful with using LD_LIBRARY_PATH - in short (from link):

..implications..:
Security: Remember that the directories specified in LD_LIBRARY_PATH get searched before(!) the standard locations? In that way, a nasty person could get your application to load a version of a shared library that contains malicious code! That’s one reason why setuid/setgid executables do neglect that variable!
Performance: The link loader has to search all the directories specified, until it finds the directory where the shared library resides – for ALL shared libraries the application is linked against! This means a lot of system calls to open(), that will fail with “ENOENT (No such file or directory)”! If the path contains many directories, the number of failed calls will increase linearly, and you can tell that from the start-up time of the application. If some (or all) of the directories are in an NFS environment, the start-up time of your applications can really get long – and it can slow down the whole system!
Inconsistency: This is the most common problem. LD_LIBRARY_PATH forces an application to load a shared library it wasn’t linked against, and that is quite likely not compatible with the original version. This can either be very obvious, i.e. the application crashes, or it can lead to wrong results, if the picked up library not quite does what the original version would have done. Especially the latter is sometimes hard to debug.

OR

Use the rpath option via gcc to linker - runtime library search path, will be used instead of looking in standard dir (gcc option):

-Wl,-rpath,$(DEFAULT_LIB_INSTALL_PATH)

This is good for a temporary solution. Linker first searches the LD_LIBRARY_PATH for libraries before looking into standard directories.

If you don't want to permanently update LD_LIBRARY_PATH you can do it on the fly on command line:

LD_LIBRARY_PATH=/some/custom/dir ./fooo

You can check what libraries linker knows about using (example):

/sbin/ldconfig -p | grep libpthread
        libpthread.so.0 (libc6, OS ABI: Linux 2.6.4) => /lib/libpthread.so.0

And you can check which library your application is using:

ldd foo
        linux-gate.so.1 =>  (0xffffe000)
        libpthread.so.0 => /lib/libpthread.so.0 (0xb7f9e000)
        libxml2.so.2 => /usr/lib/libxml2.so.2 (0xb7e6e000)
        librt.so.1 => /lib/librt.so.1 (0xb7e65000)
        libm.so.6 => /lib/libm.so.6 (0xb7d5b000)
        libc.so.6 => /lib/libc.so.6 (0xb7c2e000)
        /lib/ld-linux.so.2 (0xb7fc7000)
        libdl.so.2 => /lib/libdl.so.2 (0xb7c2a000)
        libz.so.1 => /lib/libz.so.1 (0xb7c18000)

JavaScript: SyntaxError: missing ) after argument list

You got an extra } to many as seen below:

var nav = document.getElementsByClassName('nav-coll');
for (var i = 0; i < button.length; i++) {
    nav[i].addEventListener('click',function(){
            console.log('haha');
        } // <-- REMOVE THIS :)
    }, false);
};

A very good tool for those things is jsFiddle. I have created a fiddle with your invalid code and when clicking the TidyUp button it formats your code which makes it clearer if there are any possible mistakes with missing braces.


DEMO - Your code in a fiddle, have a play :)


Use PHP to convert PNG to JPG with compression?

You might want to look into Image Magick, usually considered the de facto standard library for image processing. Does require an extra php module to be installed though, not sure if any/which are available in a default installation.

HTH.

How to make div fixed after you scroll to that div?

Adding on to @Alexandre Aimbiré's answer - sometimes you may need to specify z-index:1 to have the element always on top while scrolling. Like this:

position: -webkit-sticky; /* Safari & IE */
position: sticky;
top: 0;
z-index: 1;

Laravel eloquent update record without loading from database

You can simply use Query Builder rather than Eloquent, this code directly update your data in the database :) This is a sample:

DB::table('post')
            ->where('id', 3)
            ->update(['title' => "Updated Title"]);

You can check the documentation here for more information: http://laravel.com/docs/5.0/queries#updates

How do I launch the Android emulator from the command line?

The android create avd command is deprecated. It's now recommended to use avdmanager instead to launch emulators from the command line.

First, create a new emulator if one doesn't already exist:

avdmanager create avd --name "MyEmulator" -k "system-images;android-
26;google_apis;x86"

This assumes that you already have an X86 system image installed that matches API 26, and has the Google APIs installed.

You can then launch the emulator with emulator @MyEmulator.

Proper way to set response status and JSON content in a REST API made with nodejs and express

try {
  var data = {foo: "bar"};
  res.json(JSON.stringify(data));
}
catch (e) {
  res.status(500).json(JSON.stringify(e));
}

Extract file name from path, no matter what the os/path format

Using os.path.split or os.path.basename as others suggest won't work in all cases: if you're running the script on Linux and attempt to process a classic windows-style path, it will fail.

Windows paths can use either backslash or forward slash as path separator. Therefore, the ntpath module (which is equivalent to os.path when running on windows) will work for all(1) paths on all platforms.

import ntpath
ntpath.basename("a/b/c")

Of course, if the file ends with a slash, the basename will be empty, so make your own function to deal with it:

def path_leaf(path):
    head, tail = ntpath.split(path)
    return tail or ntpath.basename(head)

Verification:

>>> paths = ['a/b/c/', 'a/b/c', '\\a\\b\\c', '\\a\\b\\c\\', 'a\\b\\c', 
...     'a/b/../../a/b/c/', 'a/b/../../a/b/c']
>>> [path_leaf(path) for path in paths]
['c', 'c', 'c', 'c', 'c', 'c', 'c']


(1) There's one caveat: Linux filenames may contain backslashes. So on linux, r'a/b\c' always refers to the file b\c in the a folder, while on Windows, it always refers to the c file in the b subfolder of the a folder. So when both forward and backward slashes are used in a path, you need to know the associated platform to be able to interpret it correctly. In practice it's usually safe to assume it's a windows path since backslashes are seldom used in Linux filenames, but keep this in mind when you code so you don't create accidental security holes.

What version of Java is running in Eclipse?

The one the eclipse run in is the default java installed in the system (unless set specifically in the eclipse.ini file, use the -vm option). You can of course add more Java runtimes and use them for your projects

The string you've written is the right one, but it is specific to your environment. If you want to know the exact update then run the following code:

public class JavaVersion {
  public static void main(String[] args) {
    System.out.println(System.getProperty("java.runtime.version"));
  }
}

How to get the wsdl file from a webservice's URL

Its only possible to get the WSDL if the webservice is configured to deliver it. Therefor you have to specify a serviceBehavior and enable httpGetEnabled:

<serviceBehaviors>
    <behavior name="BindingBehavior">
        <serviceMetadata httpGetEnabled="true" />
        <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
</serviceBehaviors>

In case the webservice is only accessible via https you have to enable httpsGetEnabled instead of httpGetEnabled.

Unable to load script from assets index.android.bundle on windows

For me gradle clean fixed it when I was having issue on Android

cd android

./gradlew clean

Disable double-tap "zoom" option in browser on touch devices

Here we go

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

What's the -practical- difference between a Bare and non-Bare repository?

5 years too late, I know, but no-one actually answered the question:

Then, why should I use the bare repository and why not? What's the practical difference? That would not be beneficial to more people working on a project, I suppose.

What are your methods for this kind of work? Suggestions?

To quote directly from the Loeliger/MCullough book (978-1-449-31638-9, p196/7):

A bare repository might seem to be of little use, but its role is crucial: to serve as an authoritative focal point for collaborative development. Other developers clone and fetch from the bare repository and push updates to it... if you set up a repository into which developers push changes, it should be bare. In effect, this is a special case of the more general best practice that a published repository should be bare.

Json.net serialize/deserialize derived types?

If you are storing the type in your text (as you should be in this scenario), you can use the JsonSerializerSettings.

See: how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET

Be careful, though. Using anything other than TypeNameHandling = TypeNameHandling.None could open yourself up to a security vulnerability.

Runnable with a parameter?

I would first want to know what you are trying to accomplish here to need an argument to be passed to new Runnable() or to run(). The usual way should be to have a Runnable object which passes data(str) to its threads by setting member variables before starting. The run() method then uses these member variable values to do execute someFunc()

How to create a numpy array of all True or all False?

Quickly ran a timeit to see, if there are any differences between the np.full and np.ones version.

Answer: No

import timeit

n_array, n_test = 1000, 10000
setup = f"import numpy as np; n = {n_array};"

print(f"np.ones: {timeit.timeit('np.ones((n, n), dtype=bool)', number=n_test, setup=setup)}s")
print(f"np.full: {timeit.timeit('np.full((n, n), True)', number=n_test, setup=setup)}s")

Result:

np.ones: 0.38416870904620737s
np.full: 0.38430388597771525s


IMPORTANT

Regarding the post about np.empty (and I cannot comment, as my reputation is too low):

DON'T DO THAT. DON'T USE np.empty to initialize an all-True array

As the array is empty, the memory is not written and there is no guarantee, what your values will be, e.g.

>>> print(np.empty((4,4), dtype=bool))
[[ True  True  True  True]
 [ True  True  True  True]
 [ True  True  True  True]
 [ True  True False False]]

Failed to install *.apk on device 'emulator-5554': EOF

I solved The problem by restart Eclipse then Project -> build all

How can I commit files with git?

Git uses "the index" to prepare commits. You can add and remove changes from the index before you commit (in your paste you already have deleted ~10 files with git rm). When the index looks like you want it, run git commit.

Usually this will fire up vim. To insert text hit i, <esc> goes back to normal mode, hit ZZ to save and quit (ZQ to quit without saving). voilà, there's your commit

React Router v4 - How to get current route?

There's a hook called useLocation in react-router v5, no need for HOC or other stuff, it's very succinctly and convenient.

import { useLocation } from 'react-router-dom';

const ExampleComponent: React.FC = () => {
  const location = useLocation();  

  return (
    <Router basename='/app'>
      <main>
        <AppBar handleMenuIcon={this.handleMenuIcon} title={location.pathname} />
      </main>
    </Router>
  );
}

How to 'grep' a continuous stream?

I use the tail -f <file> | grep <pattern> all the time.

It will wait till grep flushes, not till it finishes (I'm using Ubuntu).

base 64 encode and decode a string in angular (2+)

Use the btoa() function to encode:

_x000D_
_x000D_
console.log(btoa("password")); // cGFzc3dvcmQ=
_x000D_
_x000D_
_x000D_

To decode, you can use the atob() function:

_x000D_
_x000D_
console.log(atob("cGFzc3dvcmQ=")); // password
_x000D_
_x000D_
_x000D_

mysqli::query(): Couldn't fetch mysqli

Probably somewhere you have DBconnection->close(); and then some queries try to execute .


Hint: It's sometimes mistake to insert ...->close(); in __destruct() (because __destruct is event, after which there will be a need for execution of queries)

Read properties file outside JAR file

There's always a problem accessing files on your file directory from a jar file. Providing the classpath in a jar file is very limited. Instead try using a bat file or a sh file to start your program. In that way you can specify your classpath anyway you like, referencing any folder anywhere on the system.

Also check my answer on this question:

making .exe file for java project containing sqlite

ERROR Could not load file or assembly 'AjaxControlToolkit' or one of its dependencies

Might sound obvious but do you definitely have AjaxControlToolkit.dll in your bin?

How do I install TensorFlow's tensorboard?

Try typing which tensorboard in your terminal. It should exist if you installed with pip as mentioned in the tensorboard README (although the documentation doesn't tell you that you can now launch tensorboard without doing anything else).

You need to give it a log directory. If you are in the directory where you saved your graph, you can launch it from your terminal with something like:

tensorboard --logdir .

or more generally:

tensorboard --logdir /path/to/log/directory

for any log directory.

Then open your favorite web browser and type in localhost:6006 to connect.

That should get you started. As for logging anything useful in your training process, you need to use the TensorFlow Summary API. You can also use the TensorBoard callback in Keras.

What is the difference between JavaScript and ECMAScript?

I think a little history lesson is due.

JavaScript was originally named Mocha and changed to Livescript but ultimately became JavaScript.

It's important to note that JavaScript came before ECMAscript and the history will tell you why.

To start from the beginning, JavaScript derived its name from Java and initially Brendan Eich (the creator of JS) was asked to develop a language that resembled Java for the web for Netscape.

Eich, however decided that Java was too complicated with all its rules and so set out to create a simpler language that even a beginner could code in. This is evident in such things like the relaxing of the need to have a semicolon.

After the language was complete, the marketing team of Netscape requested Sun to allow them to name it JavaScript as a marketing stunt and hence why most people who have never used JavaScript think it's related to Java.

About a year or two after JavaScript's release in the browser, Microsoft's IE took the language and started making its own implementations such as JScript. At the same time, IE was dominating the market and not long after Netscape had to shut its project.

Before Netscape went down, they decided to start a standard that would guide the path of JavaScript, named ECMAScript.

ECMAScript had a few releases and in 1999 they released their last version (ECMAScript 3) before they went into hibernation for the next 10 years. During this 10 years, Microsoft dominated the scenes but at the same time they weren't improving their product and hence Firefox was born (led by Eich) and a whole heap of other browsers such as Chrome, Opera.

ECMAScript released its 5th Edition in 2009 (the 4th edition was abandoned) with features such as strict mode. Since then, ECMAScript has gained a lot of momentum and is scheduled to release its 6th Edition in a few months from now with the biggest changes its had thus far.

You can use a list of features for ECMAScript 6 here http://kangax.github.io/es5-compat-table/es6/ and also the browser support. You can even start writing Ecmascript 6 like you do with CoffeeScript and use a compiler to compile down to Ecmascript 5.

Whether ECMAScript is the language and JavaScript is a dialect is arguable, but not important. If you continue to think like this it might confuse you. There is no compiler out there that would run ECMAScript, and I believe JavaScript is considered the Language which implements a standard called ECMAScript.

There are also other noticeable languages that implement ECMAScript such as ActionScript (used for Flash)

Giving UIView rounded corners

You need to first import header file <QuartzCore/QuartzCore.h>

 #import QuartzCore/QuartzCore.h>

[yourView.layer setCornerRadius:8.0f];
yourView.layer.borderColor = [UIColor redColor].CGColor;
yourView.layer.borderWidth = 2.0f;
[yourView.layer setMasksToBounds:YES];

Don't miss to use -setMasksToBounds , otherwise the effect may not be shown.

What is a mutex?

When I am having a big heated discussion at work, I use a rubber chicken which I keep in my desk for just such occasions. The person holding the chicken is the only person who is allowed to talk. If you don't hold the chicken you cannot speak. You can only indicate that you want the chicken and wait until you get it before you speak. Once you have finished speaking, you can hand the chicken back to the moderator who will hand it to the next person to speak. This ensures that people do not speak over each other, and also have their own space to talk.

Replace Chicken with Mutex and person with thread and you basically have the concept of a mutex.

Of course, there is no such thing as a rubber mutex. Only rubber chicken. My cats once had a rubber mouse, but they ate it.

Of course, before you use the rubber chicken, you need to ask yourself whether you actually need 5 people in one room and would it not just be easier with one person in the room on their own doing all the work. Actually, this is just extending the analogy, but you get the idea.

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

Asp.net - <customErrors mode="Off"/> error when trying to access working webpage

For example in my case I accidentaly changed role of some users to incorrect, and my application got error during starting (NullReferenceException). When I fixed it - the app starts fine.

List of zeros in python

zeros=[0]*4

you can replace 4 in the above example with whatever number you want.

Save plot to image file instead of displaying it using Matplotlib

import datetime
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt

# Create the PdfPages object to which we will save the pages:
# The with statement makes sure that the PdfPages object is closed properly at
# the end of the block, even if an Exception occurs.
with PdfPages('multipage_pdf.pdf') as pdf:
    plt.figure(figsize=(3, 3))
    plt.plot(range(7), [3, 1, 4, 1, 5, 9, 2], 'r-o')
    plt.title('Page One')
    pdf.savefig()  # saves the current figure into a pdf page
    plt.close()

    plt.rc('text', usetex=True)
    plt.figure(figsize=(8, 6))
    x = np.arange(0, 5, 0.1)
    plt.plot(x, np.sin(x), 'b-')
    plt.title('Page Two')
    pdf.savefig()
    plt.close()

    plt.rc('text', usetex=False)
    fig = plt.figure(figsize=(4, 5))
    plt.plot(x, x*x, 'ko')
    plt.title('Page Three')
    pdf.savefig(fig)  # or you can pass a Figure object to pdf.savefig
    plt.close()

    # We can also set the file's metadata via the PdfPages object:
    d = pdf.infodict()
    d['Title'] = 'Multipage PDF Example'
    d['Author'] = u'Jouni K. Sepp\xe4nen'
    d['Subject'] = 'How to create a multipage pdf file and set its metadata'
    d['Keywords'] = 'PdfPages multipage keywords author title subject'
    d['CreationDate'] = datetime.datetime(2009, 11, 13)
    d['ModDate'] = datetime.datetime.today()

Calculate time difference in Windows batch file

A re-hash of Aacini's code because most likely you are going to set the start time as a variable and want to save that data for output:

    @echo off

    rem ******************  MAIN CODE SECTION
    set STARTTIME=%TIME%

    rem Your code goes here (remove the ping line)
    ping -n 4 -w 1 127.0.0.1 >NUL

    set ENDTIME=%TIME%

    rem ******************  END MAIN CODE SECTION


    rem Change formatting for the start and end times
    for /F "tokens=1-4 delims=:.," %%a in ("%STARTTIME%") do (
       set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
    )

    for /F "tokens=1-4 delims=:.," %%a in ("%ENDTIME%") do ( 
       IF %ENDTIME% GTR %STARTTIME% set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100" 
       IF %ENDTIME% LSS %STARTTIME% set /A "end=((((%%a+24)*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100" 
    )

    rem Calculate the elapsed time by subtracting values
    set /A elapsed=end-start

    rem Format the results for output
    set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
    if %hh% lss 10 set hh=0%hh%
    if %mm% lss 10 set mm=0%mm%
    if %ss% lss 10 set ss=0%ss%
    if %cc% lss 10 set cc=0%cc%

    set DURATION=%hh%:%mm%:%ss%,%cc%

    echo Start    : %STARTTIME%
    echo Finish   : %ENDTIME%
    echo          ---------------
    echo Duration : %DURATION% 

Output:

    Start    : 11:02:45.92
    Finish   : 11:02:48.98
             ---------------
    Duration : 00:00:03,06

ExecutorService that interrupts tasks after a timeout

You can use this implementation that ExecutorService provides

invokeAll(Collection<? extends Callable<T>> tasks,long timeout, TimeUnit unit)
as

executor.invokeAll(Arrays.asList(task), 2 , TimeUnit.SECONDS);

However, in my case, I could not as Arrays.asList took extra 20ms.

How can I convert a Unix timestamp to DateTime and vice versa?

Written a simplest extension that works for us. If anyone looks for it...

public static class DateTimeExtensions
{
    public static DateTime FromUnixTimeStampToDateTime(this string unixTimeStamp)
    {

        return DateTimeOffset.FromUnixTimeSeconds(long.Parse(unixTimeStamp)).UtcDateTime;
    }
}

How to fix "set SameSite cookie to none" warning?

I am using both JavaScript Cookie and Java CookieUtil in my project, below settings solved my problem:

JavaScript Cookie

var d = new Date();
d.setTime(d.getTime() + (30*24*60*60*1000)); //keep cookie 30 days
var expires = "expires=" + d.toGMTString();         
document.cookie = "visitName" + "=Hailin;" + expires + ";path=/;SameSite=None;Secure"; //can set SameSite=Lax also

JAVA Cookie (set proxy_cookie_path in Nginx)

location / {
   proxy_pass http://96.xx.xx.34;
   proxy_intercept_errors on;
   #can set SameSite=None also
   proxy_cookie_path / "/;SameSite=Lax;secure";
   proxy_connect_timeout 600;
   proxy_read_timeout 600;
}

Check result in Firefox enter image description here

Read more on https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

MySQL Error 1153 - Got a packet bigger than 'max_allowed_packet' bytes

As michaelpryor said, you have to change it for both the client and the daemon mysqld server.

His solution for the client command-line is good, but the ini files don't always do the trick, depending on configuration.

So, open a terminal, type mysql to get a mysql prompt, and issue these commands:

set global net_buffer_length=1000000; 
set global max_allowed_packet=1000000000; 

Keep the mysql prompt open, and run your command-line SQL execution on a second terminal..

How to customize the configuration file of the official PostgreSQL Docker image?

I was also using the official image (FROM postgres) and I was able to change the config by executing the following commands.

The first thing is to locate the PostgreSQL config file. This can be done by executing this command in your running database.

SHOW config_file;

I my case it returns /data/postgres/postgresql.conf.

The next step is to find out what is the hash of your running PostgreSQL docker container.

docker ps -a

This should return a list of all the running containers. In my case it looks like this.

...
0ba35e5427d9    postgres    "docker-entrypoint.s…" ....
...

Now you have to switch to the bash inside your container by executing:

docker exec -it 0ba35e5427d9 /bin/bash

Inside the container check if the config is at the correct path and display it.

cat /data/postgres/postgresql.conf

I wanted to change the max connections from 100 to 1000 and the shared buffer from 128MB to 3GB. With the sed command I can do a search and replace with the corresponding variables ins the config.

sed -i -e"s/^max_connections = 100.*$/max_connections = 1000/" /data/postgres/postgresql.conf
sed -i -e"s/^shared_buffers = 128MB.*$/shared_buffers = 3GB/" /data/postgres/postgresql.conf

The last thing we have to do is to restart the database within the container. Find out which version you of PostGres you are using.

cd /usr/lib/postgresql/
ls 

In my case its 12 So you can now restart the database by executing the following command with the correct version in place.

su - postgres -c "PGDATA=$PGDATA /usr/lib/postgresql/12/bin/pg_ctl -w restart"

PHP multidimensional array search by value

Even though this is an old question and has an accepted answer, Thought i would suggest one change to the accepted answer.. So first off, i agree the accepted answer is correct here.

function searchArrayKeyVal($sKey, $id, $array) {
   foreach ($array as $key => $val) {
       if ($val[$sKey] == $id) {
           return $key;
       }
   }
   return false;
}

Replacing the preset 'uid' with a parameter in the function instead, so now calling the below code means you can use the one function across multiple array types. Small change, but one that makes the slight difference.

    // Array Data Of Users
$userdb = array (
    array ('uid' => '100','name' => 'Sandra Shush','url' => 'urlof100' ),
    array ('uid' => '5465','name' => 'Stefanie Mcmohn','url' => 'urlof100' ),
    array ('uid' => '40489','name' => 'Michael','url' => 'urlof40489' ),
);

// Obtain The Key Of The Array
$arrayKey = searchArrayKeyVal("uid", '100', $userdb);
if ($arrayKey!==false) {
    echo "Search Result: ", $userdb[$arrayKey]['name'];
} else {
    echo "Search Result can not be found";
}

PHP Fiddle Example

jQuery change URL of form submit

Try using this:

$(".move_to").on("click", function(e){
    e.preventDefault();
    $('#contactsForm').attr('action', "/test1").submit();
});

Moving the order in which you use .preventDefault() might fix your issue. You also didn't use function(e) so e.preventDefault(); wasn't working.

Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1.

How to load URL in UIWebView in Swift?

Loading URL to WebView is very easy. Just create a WebView in your storyboard and then you can use the following code to load url.

    let url = NSURL (string: "https://www.simplifiedios.net");
    let request = NSURLRequest(URL: url!);
    webView.loadRequest(request);

As simple as that only 3 lines of codes :)

Ref: UIWebView Example

Changing capitalization of filenames in Git

Set ignorecase to false in git config

As the original post is about "Changing capitalization of filenames in Git":

If you are trying to change capitalisation of a filename in your project, you do not need to force rename it from Git. IMO, I would rather change the capitalisation from my IDE/editor and make sure that I configure Git properly to pick up the renaming.

By default, a Git template is set to ignore case (Git case insensitive). To verify you have the default template, use --get to retrieve the value for a specified key. Use --local and --global to indicate to Git whether to pick up a configuration key-value from your local Git repository configuration or global one. As an example, if you want to lookup your global key core.ignorecase:

git config --global --get core.ignorecase

If this returns true, make sure to set it as:

git config --global core.ignorecase false

(Make sure you have proper permissions to change global.) And there you have it; now your Git installation would not ignore capitalisations and treat them as changes.

As a suggestion, if you are working on multi-language projects and you feel not all projects should be treated as case-sensitive by Git, just update the local core.ignorecase file.

How to assign name for a screen?

To create a new screen with the name foo, use

screen -S foo

Then to reattach it, run

screen -r foo  # or use -x, as in
screen -x foo  # for "Multi display mode" (see the man page)

How to run SQL script in MySQL?

If you’re at the MySQL command line mysql> you have to declare the SQL file as source.

mysql> source \home\user\Desktop\test.sql;

onchange file input change img src and change image color

Simple Solution. No Jquery

_x000D_
_x000D_
<img id="output" src="" width="100" height="100">_x000D_
_x000D_
<input name="photo" type="file" accept="image/*" onchange="document.getElementById('output').src = window.URL.createObjectURL(this.files[0])">
_x000D_
_x000D_
_x000D_

C# getting its own class name

Use this

Let say Application Test.exe is running and function is foo() in form1 [basically it is class form1], then above code will generate below response.

string s1 = System.Reflection.MethodBase.GetCurrentMethod().DeclaringType.Name;

This will return .

s1 = "TEST.form1"

for function name:

string s1 = System.Reflection.MethodBase.GetCurrentMethod().Name;

will return

s1 = foo 

Note if you want to use this in exception use :

catch (Exception ex)
{

    MessageBox.Show(ex.StackTrace );

}

Rails: Adding an index after adding column

If you need to create a user_id then it would be a reasonable assumption that you are referencing a user table. In which case the migration shall be:

rails generate migration AddUserRefToProducts user:references

This command will generate the following migration:

class AddUserRefToProducts < ActiveRecord::Migration
  def change
    add_reference :user, :product, index: true
  end
end

After running rake db:migrate both a user_id column and an index will be added to the products table.

In case you just need to add an index to an existing column, e.g. name of a user table, the following technique may be helpful:

rails generate migration AddIndexToUsers name:string:index will generate the following migration:

class AddIndexToUsers < ActiveRecord::Migration
  def change
    add_column :users, :name, :string
    add_index :users, :name
  end
end

Delete add_column line and run the migration.

In the case described you could have issued rails generate migration AddIndexIdToTable index_id:integer:index command and then delete add_column line from the generated migration. But I'd rather recommended to undo the initial migration and add reference instead:

rails generate migration RemoveUserIdFromProducts user_id:integer
rails generate migration AddUserRefToProducts user:references

How to write/update data into cells of existing XLSX workbook using xlsxwriter in python

You can do by xlwings as well

import xlwings as xw
for book in xlwings.books:
    print(book)

cvc-elt.1: Cannot find the declaration of element 'MyElement'

Your schema is for its target namespace http://www.example.org/Test so it defines an element with name MyElement in that target namespace http://www.example.org/Test. Your instance document however has an element with name MyElement in no namespace. That is why the validating parser tells you it can't find a declaration for that element, you haven't provided a schema for elements in no namespace.

You either need to change the schema to not use a target namespace at all or you need to change the instance to use e.g. <MyElement xmlns="http://www.example.org/Test">A</MyElement>.

What is {this.props.children} and when you should use it?

I assume you're seeing this in a React component's render method, like this (edit: your edited question does indeed show that):

_x000D_
_x000D_
class Example extends React.Component {_x000D_
  render() {_x000D_
    return <div>_x000D_
      <div>Children ({this.props.children.length}):</div>_x000D_
      {this.props.children}_x000D_
    </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
class Widget extends React.Component {_x000D_
  render() {_x000D_
    return <div>_x000D_
      <div>First <code>Example</code>:</div>_x000D_
      <Example>_x000D_
        <div>1</div>_x000D_
        <div>2</div>_x000D_
        <div>3</div>_x000D_
      </Example>_x000D_
      <div>Second <code>Example</code> with different children:</div>_x000D_
      <Example>_x000D_
        <div>A</div>_x000D_
        <div>B</div>_x000D_
      </Example>_x000D_
    </div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <Widget/>,_x000D_
  document.getElementById("root")_x000D_
);
_x000D_
<div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
_x000D_
_x000D_
_x000D_

children is a special property of React components which contains any child elements defined within the component, e.g. the divs inside Example above. {this.props.children} includes those children in the rendered result.

...what are the situations to use the same

You'd do it when you want to include the child elements in the rendered output directly, unchanged; and not if you didn't.

What's the best/easiest GUI Library for Ruby?

Glimmer is an interesting option for JRuby users which provides a very Ruby-ish interface to the SWT toolkit. (SWT is the user interface framework behind Eclipse, which delivers fast performance and familiar UI metaphors by making use of native widgets on the various platforms it supports: Windows, OS X, Linux, etc.) SWT always appealed to me as a Java developer, but coding it was painful in the extreme. Glimmer makes the process a lot more straightforward by emphasizing convention over configuration, and by valuing DRYness and all the other normal Ruby goodness.

Another neat option is SproutCore, a Javascript-based GUI toolkit with Ruby bindings developed by Apple. At least, the demos for it look great, and otherinbox built a pretty slick looking application on top of it. Personally, I've spent quite a few hours trying to get it running on two systems -- one Windows and one Linux -- and haven't succeeded on either one -- I keep running into dependency issues with Merb or other pieces of the SproutCore stack. But it's intriguing enough that I'll go back after a few weeks and try again, hoping that the issues get resolved in that time.

Convert a list to a data frame

Update July 2020:

The default for the parameter stringsAsFactors is now default.stringsAsFactors() which in turn yields FALSE as its default.


Assuming your list of lists is called l:

df <- data.frame(matrix(unlist(l), nrow=length(l), byrow=TRUE))

The above will convert all character columns to factors, to avoid this you can add a parameter to the data.frame() call:

df <- data.frame(matrix(unlist(l), nrow=132, byrow=TRUE),stringsAsFactors=FALSE)

Convert Existing Eclipse Project to Maven Project

It's necessary because, more or less, when we import a project from git, it's not a maven project, so the maven dependencies are not in the build path.

Here's what I have done to turn a general project to a maven project.

general project-->java project right click the project, properties->project facets, click "java". This step will turn a general project into java project.

java project --> maven project right click project, configure-->convert to maven project At this moment, maven dependencies lib are still not in the build path. project properties, build path, add library, add maven dependencies lib

And wait a few seconds, when the dependencies are loaded, the project is ready!

JavaScript: Class.method vs. Class.prototype.method

A. Static Method:

      Class.method = function () { /* code */ }
  1. method() here is a function property added to an another function (here Class).
  2. You can directly access the method() by the class / function name. Class.method();
  3. No need for creating any object/instance (new Class()) for accessing the method(). So you could call it as a static method.

B. Prototype Method (Shared across all the instances):

     Class.prototype.method = function () { /* code using this.values */ }
  1. method() here is a function property added to an another function protype (here Class.prototype).
  2. You can either directly access by class name or by an object/instance (new Class()).
  3. Added advantage - this way of method() definition will create only one copy of method() in the memory and will be shared across all the object's/instance's created from the Class

C. Class Method (Each instance has its own copy):

   function Class () {
      this.method = function () { /* do something with the private members */};
   }
  1. method() here is a method defined inside an another function (here Class).
  2. You can't directly access the method() by the class / function name. Class.method();
  3. You need to create an object/instance (new Class()) for the method() access.
  4. This way of method() definition will create a unique copy of the method() for each and every objects created using the constructor function (new Class()).
  5. Added advantage - Bcos of the method() scope it has the full right to access the local members(also called private members) declared inside the constructor function (here Class)

Example:

    function Class() {
        var str = "Constructor method"; // private variable
        this.method = function () { console.log(str); };
    }
    Class.prototype.method = function() { console.log("Prototype method"); };
    Class.method = function() { console.log("Static method"); };

    new Class().method();     // Constructor method
    // Bcos Constructor method() has more priority over the Prototype method()

    // Bcos of the existence of the Constructor method(), the Prototype method 
    // will not be looked up. But you call it by explicity, if you want.
    // Using instance
    new Class().constructor.prototype.method(); // Prototype method

    // Using class name
    Class.prototype.method(); // Prototype method

    // Access the static method by class name
    Class.method();           // Static method