Programs & Examples On #Ocracoke

Long vs Integer, long vs int, what to use and when?

When it comes to using a very long number that may exceed 32 bits to represent, you may use long to make sure that you'll not have strange behavior.

From Java 5 you can use in-boxing and out-boxing features to make the use of int and Integer completely the same. It means that you can do :

int myInt = new Integer(11);
Integer myInt2 = myInt;

The in and out boxing allow you to switch between int and Integer without any additional conversion (same for Long,Double,Short too)

You may use int all the time, but Integer contains some helper methods that can help you to do some complex operations with integers (such as Integer.parseInt(String) )

Pythonic way to print list items

Assuming you are using Python 3.x:

print(*myList, sep='\n')

You can get the same behavior on Python 2.x using from __future__ import print_function, as noted by mgilson in comments.

With the print statement on Python 2.x you will need iteration of some kind, regarding your question about print(p) for p in myList not working, you can just use the following which does the same thing and is still one line:

for p in myList: print p

For a solution that uses '\n'.join(), I prefer list comprehensions and generators over map() so I would probably use the following:

print '\n'.join(str(p) for p in myList) 

forEach loop Java 8 for Map entry set

HashMap<String,Integer> hm = new HashMap();

 hm.put("A",1);
 hm.put("B",2);
 hm.put("C",3);
 hm.put("D",4);

 hm.forEach((key,value)->{
     System.out.println("Key: "+key + " value: "+value);
 });

PHP: Get key from array?

$foo = array('a' => 'apple', 'b' => 'ball', 'c' => 'coke');

foreach($foo as $key => $item) {
  echo $item.' is begin with ('.$key.')';
}

Fill background color left to right CSS

The thing you will need to do here is use a linear gradient as background and animate the background position. In code:

Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.

background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;

On hover, change the background position to right bottom and with transition:all 2s ease;, the position will change gradually (it's nicer with linear tough) background-position:right bottom;

http://jsfiddle.net/75Umu/3/

As for the -vendor-prefix'es, see the comments to your question

extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).

background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;

Demo:

_x000D_
_x000D_
div {
    font: 22px Arial;
    display: inline-block;
    padding: 1em 2em;
    text-align: center;
    color: white;
    background: red; /* default color */

    /* "to left" / "to right" - affects initial color */
    background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
    background-size: 200%;
    transition: .5s ease-out;
}
div:hover {
    background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
_x000D_
_x000D_

Sending files using POST with HttpURLConnection

I actually found a better way to send files using HttpURLConnection using MultipartEntity

private static String multipost(String urlString, MultipartEntity reqEntity) {
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setUseCaches(false);
        conn.setDoInput(true);
        conn.setDoOutput(true);

        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.addRequestProperty("Content-length", reqEntity.getContentLength()+"");
        conn.addRequestProperty(reqEntity.getContentType().getName(), reqEntity.getContentType().getValue());

        OutputStream os = conn.getOutputStream();
        reqEntity.writeTo(conn.getOutputStream());
        os.close();
        conn.connect();

        if (conn.getResponseCode() == HttpURLConnection.HTTP_OK) {
            return readStream(conn.getInputStream());
        }

    } catch (Exception e) {
        Log.e(TAG, "multipart post error " + e + "(" + urlString + ")");
    }
    return null;        
}

private static String readStream(InputStream in) {
    BufferedReader reader = null;
    StringBuilder builder = new StringBuilder();
    try {
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine()) != null) {
            builder.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return builder.toString();
} 

Assuming you are uploading an image with bitmap data:

    Bitmap bitmap = ...;
    String filename = "filename.png";
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, bos);
    ContentBody contentPart = new ByteArrayBody(bos.toByteArray(), filename);

    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("picture", contentPart);
    String response = multipost("http://server.com", reqEntity);

And Voila! Your post data will contain picture field along with the filename and path on your server.

Why is the parent div height zero when it has floated children

Ordinarily, floats aren't counted in the layout of their parents.

To prevent that, add overflow: hidden to the parent.

Why doesn't Python have multiline comments?

There should only be one way to do a thing, is contradicted by the usage of multiline strings and single line strings or switch/case and if, different form of loops.

Multiline comments are a pretty common feature and lets face it the multiline string comment is a hack with negative sideffects! I have seen lots of code doing the multiline comment trick and even editors use it.

But I guess every language has its quirks where the devs insist on never fixing it. I know such quirks from the java side as well, which have been open since the late 90s, never to be fixed!

Plotting a 3d cube, a sphere and a vector in Matplotlib

My answer is an amalgamation of the above two with extension to drawing sphere of user-defined opacity and some annotation. It finds application in b-vector visualization on a sphere for magnetic resonance image (MRI). Hope you find it useful:

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

# draw sphere
u, v = np.mgrid[0:2*np.pi:50j, 0:np.pi:50j]
x = np.cos(u)*np.sin(v)
y = np.sin(u)*np.sin(v)
z = np.cos(v)
# alpha controls opacity
ax.plot_surface(x, y, z, color="g", alpha=0.3)


# a random array of 3D coordinates in [-1,1]
bvecs= np.random.randn(20,3)

# tails of the arrows
tails= np.zeros(len(bvecs))

# heads of the arrows with adjusted arrow head length
ax.quiver(tails,tails,tails,bvecs[:,0], bvecs[:,1], bvecs[:,2],
          length=1.0, normalize=True, color='r', arrow_length_ratio=0.15)

ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')

ax.set_title('b-vectors on unit sphere')

plt.show()

insert data from one table to another in mysql

If you want insert all data from one table to another table there is a very simply sql

INSERT INTO destinationTable  (SELECT * FROM sourceDbName.SourceTableName);

Show/hide forms using buttons and JavaScript

Use the following code fragment to hide the form on button click.

document.getElementById("your form id").style.display="none";

And the following code to display it:

document.getElementById("your form id").style.display="block";

Or you can use the same function for both purposes:

function asd(a)
{
    if(a==1)
        document.getElementById("asd").style.display="none";
    else
        document.getElementById("asd").style.display="block";
}

And the HTML:

<form id="asd">form </form>
<button onclick="asd(1)">Hide</button>
<button onclick="asd(2)">Show</button>

How to obtain the query string from the current URL with JavaScript?

You can use this function, for split string from ?id=

 function myfunction(myvar){
  var urls = myvar;
  var myurls = urls.split("?id=");
  var mylasturls = myurls[1];
  var mynexturls = mylasturls.split("&");
  var url = mynexturls[0];
  alert(url)
}
myfunction(window.top.location.href);
myfunction("http://www.myname.com/index.html?id=dance&emp;cid=in_social_facebook-hhp-food-moonlight-influencer_s7_20160623");

here is the fiddle

Unstaged changes left after git reset --hard

RESOLVED!!!

I have resolved this problem using following steps

1) Remove every file from Git's index.

git rm --cached -r .

2) Rewrite the Git index to pick up all the new line endings.

git reset --hard

Solution was part of steps described on git site https://help.github.com/articles/dealing-with-line-endings/

Quick way to list all files in Amazon S3 bucket?

In Java you can get the keys using ListObjects (see AWS documentation)

FileWriter fileWriter;
BufferedWriter bufferedWriter;
// [...]

AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());        

ListObjectsRequest listObjectsRequest = new ListObjectsRequest()
.withBucketName(bucketName)
.withPrefix("myprefix");
ObjectListing objectListing;

do {
    objectListing = s3client.listObjects(listObjectsRequest);
    for (S3ObjectSummary objectSummary : 
        objectListing.getObjectSummaries()) {
        // write to file with e.g. a bufferedWriter
        bufferedWriter.write(objectSummary.getKey());
    }
    listObjectsRequest.setMarker(objectListing.getNextMarker());
} while (objectListing.isTruncated());

How can I discard remote changes and mark a file as "resolved"?

Make sure of the conflict origin: if it is the result of a git merge, see Brian Campbell's answer.

But if is the result of a git rebase, in order to discard remote (their) changes and use local changes, you would have to do a:

git checkout --theirs -- .

See "Why is the meaning of “ours” and “theirs” reversed"" to see how ours and theirs are swapped during a rebase (because the upstream branch is checked out).

How do I reverse a commit in git?

This article has an excellent explanation as to how to go about various scenarios (where a commit has been done as well as the push OR just a commit, before the push):

http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html

From the article, the easiest command I saw to revert a previous commit by its commit id, was:

git revert dd61ab32

How to update the value stored in Dictionary in C#?

You can follow this approach:

void addOrUpdate(Dictionary<int, int> dic, int key, int newValue)
{
    int val;
    if (dic.TryGetValue(key, out val))
    {
        // yay, value exists!
        dic[key] = val + newValue;
    }
    else
    {
        // darn, lets add the value
        dic.Add(key, newValue);
    }
}

The edge you get here is that you check and get the value of corresponding key in just 1 access to the dictionary. If you use ContainsKey to check the existance and update the value using dic[key] = val + newValue; then you are accessing the dictionary twice.

PostgreSQL: insert from another table

You could use coalesce:

insert into destination select coalesce(field1,'somedata'),... from source;

Center content vertically on Vuetify

<v-container> has to be right after <template>, if there is a <div> in between, the vertical align will just not work.

<template>
  <v-container fill-height>
      <v-row class="justify-center align-center">
        <v-col cols="12" sm="4">
            Centered both vertically and horizontally
        </v-col>
      </v-row>
  </v-container>
</template>

angularjs to output plain text instead of html

You can use ng-bind-html, don't forget to inject $sanitize service into your module Hope it helps

Interface vs Abstract Class (general OO)

As you might have got the theoretical knowledge from the experts, I am not spending much words in repeating all those here, rather let me explain with a simple example where we can use/cannot use Interface and Abstract class.

Consider you are designing an application to list all the features of Cars. In various points you need inheritance in common, as some of the properties like DigitalFuelMeter, Air Conditioning, Seat adjustment, etc are common for all the cars. Likewise, we need inheritance for some classes only as some of the properties like the Braking system (ABS,EBD) are applicable only for some cars.

The below class acts as a base class for all the cars:

public class Cars
{
    public string DigitalFuelMeter()
    {
        return "I have DigitalFuelMeter";
    }

    public string AirCondition()
    {
        return "I have AC";
    }

    public string SeatAdjust()
    {
        return "I can Adjust seat";
    }
}

Consider we have a separate class for each Cars.

public class Alto : Cars
{
    // Have all the features of Car class    
}

public class Verna : Cars
{
    // Have all the features of Car class + Car need to inherit ABS as the Braking technology feature which is not in Cars        
}

public class Cruze : Cars
{
    // Have all the features of Car class + Car need to inherit EBD as the Braking technology feature which is not in Cars        
}

Consider we need a method for inheriting the Braking technology for the cars Verna and Cruze (not applicable for Alto). Though both uses braking technology, the "technology" is different. So we are creating an abstract class in which the method will be declared as Abstract and it should be implemented in its child classes.

public abstract class Brake
{
    public abstract string GetBrakeTechnology();
}

Now we are trying to inherit from this abstract class and the type of braking system is implemented in Verna and Cruze:

public class Verna : Cars,Brake
{
    public override string GetBrakeTechnology()
    {
        return "I use ABS system for braking";
    }       
}

public class Cruze : Cars,Brake
{
    public override string GetBrakeTechnology()
    {
       return "I use EBD system for braking";
    }         
}

See the problem in the above two classes? They inherit from multiple classes which C#.Net doesn't allow even though the method is implemented in the children. Here it comes the need of Interface.

interface IBrakeTechnology
{
    string GetBrakeTechnology();
}

And the implementation is given below:

public class Verna : Cars, IBrakeTechnology
{
    public string GetBrakeTechnology()
    {
        return "I use ABS system for braking";
    }
}

public class Cruze : Cars, IBrakeTechnology
{
   public string GetBrakeTechnology()
   {
       return "I use EBD system for braking";
   }        
}

Now Verna and Cruze can achieve multiple inheritance with its own kind of braking technologies with the help of Interface.

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:

import numpy as np
from sklearn import linear_model
from sklearn import svm

classifiers = [
    svm.SVR(),
    linear_model.SGDRegressor(),
    linear_model.BayesianRidge(),
    linear_model.LassoLars(),
    linear_model.ARDRegression(),
    linear_model.PassiveAggressiveRegressor(),
    linear_model.TheilSenRegressor(),
    linear_model.LinearRegression()]

trainingData    = np.array([ [2.3, 4.3, 2.5],  [1.3, 5.2, 5.2],  [3.3, 2.9, 0.8],  [3.1, 4.3, 4.0]  ])
trainingScores  = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData  = np.array([ [2.5, 2.4, 2.7],  [2.7, 3.2, 1.2] ])

for item in classifiers:
    print(item)
    clf = item
    clf.fit(trainingData, trainingScores)
    print(clf.predict(predictionData),'\n')

What should I do when 'svn cleanup' fails?

Run svn cleanup command in a terminal (if it fails from Eclipse which was my case):

~/path/to/svn-folder/$ svn cleanup

I tried different solutions explained here, but none worked.

Action Team ? Update to head fails:

svn: E155004: There are unfinished work items in '/home/user/path/to/svn-folder'; run 'svn cleanup' first.

Action Team ? Cleanup fails with same error.

Solution that worked for me: run svn cleanup command in a terminal.

The command succeeded.

Then Team ? Update in Eclipse worked again.

Note: my SVN version is 1.9.3.

Also check Chris's answer if svn cleanup does not work.

How do I hide javascript code in a webpage?

I'm not sure anyone else actually addressed your question directly which is code being viewed from the browser's View Source command.

As other have said, there is no way to protect javascript intended to run in a browser from a determined viewer. If the browser can run it, then any determined person can view/run it also.

But, if you put your javascript in an external javascript file that is included with:

<script type="text/javascript" src="http://mydomain.com/xxxx.js"></script>

tags, then the javascript code won't be immediately visible with the View Source command - only the script tag itself will be visible that way. That doesn't mean that someone can't just load that external javascript file to see it, but you did ask how to keep it out of the browser's View Source command and this will do it.

If you wanted to really make it more work to view the source, you would do all of the following:

  1. Put it in an external .js file.
  2. Obfuscate the file so that most native variable names are replaced with short versions, so that all unneeded whitespace is removed, so it can't be read without further processing, etc...
  3. Dynamically include the .js file by programmatically adding script tags (like Google Analytics does). This will make it even more difficult to get to the source code from the View Source command as there will be no easy link to click on there.
  4. Put as much interesting logic that you want to protect on the server that you retrieve via ajax calls rather than do local processing.

With all that said, I think you should focus on performance, reliability and making your app great. If you absolutely have to protect some algorithm, put it on the server, but other than that, compete on being the best at you do, not by having secrets. That's ultimately how success works on the web anyway.

Calling filter returns <filter object at ... >

It's an iterator returned by the filter function.

If you want a list, just do

list(filter(f, range(2, 25)))

Nonetheless, you can just iterate over this object with a for loop.

for e in filter(f, range(2, 25)):
    do_stuff(e)

TypeError: cannot perform reduce with flexible type

It looks like your 'trainData' is a list of strings:

['-214' '-153' '-58' ..., '36' '191' '-37']

Change your 'trainData' to a numeric type.

 import numpy as np
 np.array(['1','2','3']).astype(np.float)

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

There is a dirty trick, what I have used:

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

Suggestion are heartily welcome towards this.

Adding class on run time:

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

Check mySQL version on Mac 10.8.5

Or just call mysql command with --version option.

mysql --version

How do I print an IFrame from javascript in Safari/Chrome

I had to make few modifications in order to make it with in IE8 (didn't test with other IE flavours)

1) document.frames[param] seem to accept a number, not ID

printIframe(0, 'print');

function printIframe(num, id)
{
  var iframe = document.frames ? document.frames[num] : document.getElementById(id);
  var ifWin = iframe.contentWindow || iframe;

  ifWin.focus();
  ifWin.printPage();

  return false;
}

2) I had a print dialog displayed upon page load and also there was a link to "Click here to start printing" (if it didn't start automatically). In order to get it work I had to add focus() call

<script type="text/javascript">
  $(function(){
    printPage();
  });

  function printPage()
  {
    focus();
    print();
  }
</script>

What does the PHP error message "Notice: Use of undefined constant" mean?

You missed putting single quotes around your array keys:

$_POST[email]

should be:

$_POST['email']

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

Are there any worse sorting algorithms than Bogosort (a.k.a Monkey Sort)?

I had a lecturer who once suggested generating a random array, checking if it was sorted and then checking if the data was the same as the array to be sorted.

Best case O(N) (first time baby!) Worst case O(Never)

Getting last month's date in php

Simply get last month.

Example:

Today is: 2020-09-02

Code:

echo date('Y-m-d', strtotime(date('Y-m-d')." -1 month"));

Result:

2020-08-02

Why does the jquery change event not trigger when I set the value of a select using val()?

To make it easier add a custom function and call it when ever you want that changing the value also trigger change

$.fn.valAndTrigger = function (element) {
    return $(this).val(element).trigger('change');
}

and

$("#sample").valAndTirgger("NewValue");

Or you can override the val function to always call the change when the val is called

(function ($) {
    var originalVal = $.fn.val;
    $.fn.val = function (value) {
        this.trigger("change");
        return originalVal.call(this, value);
    };
})(jQuery);

Sample at http://jsfiddle.net/r60bfkub/

MySQL Daemon Failed to Start - centos 6

It may be a permission issue,

Please try the following command /etc/init.d/mysqld start as root user.

Rails 4 Authenticity Token

This is a security feature in Rails. Add this line of code in the form:

<%= hidden_field_tag :authenticity_token, form_authenticity_token %>

Documentation can be found here: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html

Convert time fields to strings in Excel

The below worked for me

  • First copy the content say "1:00:15" in notepad
  • Then select a new column where you need to copy the text from notepad.
  • Then right click and select format cell option and in that select numbers tab and in that tab select the option "Text".
  • Now copy the content from notepad and paste in this Excel column. it will be text but in format "1:00:15".

How to make a redirection on page load in JSF 1.x

FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
response.sendRedirect("somePage.jsp");

How to sort a List of objects by their date (java collections, List<Object>)

You're using Comparators incorrectly.

 Collections.sort(movieItems, new Comparator<Movie>(){
           public int compare (Movie m1, Movie m2){
               return m1.getDate().compareTo(m2.getDate());
           }
       });

Set keyboard caret position in html textbox

Since I actually really needed this solution, and the typical baseline solution (focus the input - then set the value equal to itself) doesn't work cross-browser, I spent some time tweaking and editing everything to get it working. Building upon @kd7's code here's what I've come up with.

Enjoy! Works in IE6+, Firefox, Chrome, Safari, Opera

Cross-browser caret positioning technique (example: moving the cursor to the END)

// ** USEAGE ** (returns a boolean true/false if it worked or not)
// Parameters ( Id_of_element, caretPosition_you_want)

setCaretPosition('IDHERE', 10); // example

The meat and potatoes is basically @kd7's setCaretPosition, with the biggest tweak being if (el.selectionStart || el.selectionStart === 0), in firefox the selectionStart is starting at 0, which in boolean of course is turning to False, so it was breaking there.

In chrome the biggest issue was that just giving it .focus() wasn't enough (it kept selecting ALL of the text!) Hence, we set the value of itself, to itself el.value = el.value; before calling our function, and now it has a grasp & position with the input to use selectionStart.

function setCaretPosition(elemId, caretPos) {
    var el = document.getElementById(elemId);

    el.value = el.value;
    // ^ this is used to not only get "focus", but
    // to make sure we don't have it everything -selected-
    // (it causes an issue in chrome, and having it doesn't hurt any other browser)

    if (el !== null) {

        if (el.createTextRange) {
            var range = el.createTextRange();
            range.move('character', caretPos);
            range.select();
            return true;
        }

        else {
            // (el.selectionStart === 0 added for Firefox bug)
            if (el.selectionStart || el.selectionStart === 0) {
                el.focus();
                el.setSelectionRange(caretPos, caretPos);
                return true;
            }

            else  { // fail city, fortunately this never happens (as far as I've tested) :)
                el.focus();
                return false;
            }
        }
    }
}

Swift Set to Array

call this method and pass your set

func getArrayFromSet(set:NSSet)-> NSArray {

return set.map ({ String($0) })
}

Like This :

var letters:Set = Set<String>(arrayLiteral: "test","test") // your set
print(self.getArrayFromSet(letters))

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

Convert Linq Query Result to Dictionary

Looking at your example, I think this is what you want:

var dict = TableObj.ToDictionary(t => t.Key, t=> t.TimeStamp);

How to find out if a Python object is a string?

Python 3

In Python 3.x basestring is not available anymore, as str is the sole string type (with the semantics of Python 2.x's unicode).

So the check in Python 3.x is just:

isinstance(obj_to_test, str)

This follows the fix of the official 2to3 conversion tool: converting basestring to str.

How do you set the title color for the new Toolbar?

Create a toolbar in your xml...toolbar.xml:

<android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"

    </android.support.v7.widget.Toolbar>

Then add the following in your toolbar.xml:

app:titleTextColor="@color/colorText"
app:title="@string/app_name">

Remeber @color/colorText is simply your color.xml file with the color attribute named colorText and your color.This is the best way to calll your strings rather than hardcoding your color inside your toolbar.xml. You also have other options to modify your text,such as:textAppearance...etc...just type app:text...and intelisense will give you options in android studio.

your final toolbar should look like this:

 <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:layout_weight="1"
        android:background="?attr/colorPrimary"
        app:layout_scrollFlags="scroll|enterAlways"
        app:popupTheme="@style/Theme.AppCompat"
       app:subtitleTextAppearance="@drawable/icon"
        app:title="@string/app_name">
    </android.support.v7.widget.Toolbar>

NB:This toolbar should be inside your activity_main.xml.Easy Peasie

Another option is to do it all in your class:

Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(Color.WHITE);

Good Luck

Easy way to dismiss keyboard?

You may also need to override UIViewController disablesAutomaticKeyboardDismissal to get this to work in some cases. This may have to be done on the UINavigationController if you have one.

Conditional formatting using AND() function

COLUMN() and ROW() won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.

For instance, if you want to use this conditional formating on a range begining on cell A1, you can try:

`COLUMN(A1)` and `ROW(A1)`

Excel will automatically adapt the conditional formating to the current cell.

Reset textbox value in javascript

With jQuery, I've found that sometimes using val to clear the value of a textbox has no effect, in those situations I've found that using attr does the job

$('#searchField').attr("value", "");

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

I found that I could access the checkbox directly using Worksheets("SheetName").CB_Checkboxname.value directly without relating to additional objects.

Subtract a value from every number in a list in Python?

To clarify an already posted solution due to questions in the comments

import numpy

array = numpy.array([49, 51, 53, 56])
array = array - 13

will output:

array([36, 38, 40, 43])

What's the difference between JavaScript and Java?

Everything. They're unrelated languages.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I've had this problem. See The Python "Connection Reset By Peer" Problem.

You have (most likely) run afoul of small timing issues based on the Python Global Interpreter Lock.

You can (sometimes) correct this with a time.sleep(0.01) placed strategically.

"Where?" you ask. Beats me. The idea is to provide some better thread concurrency in and around the client requests. Try putting it just before you make the request so that the GIL is reset and the Python interpreter can clear out any pending threads.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

Direct answer:

  • Use a = operator

We can use the public member function std::vector::operator= of the container std::vector for assigning values from a vector to another.

  • Use a constructor function

Besides, a constructor function also makes sense. A constructor function with another vector as parameter(e.g. x) constructs a container with a copy of each of the elements in x , in the same order.

Caution:

  • Do not use std::vector::swap

std::vector::swap is not copying a vector to another, it is actually swapping elements of two vectors, just as its name suggests. In other words, the source vector to copy from is modified after std::vector::swap is called, which is probably not what you are expected.

  • Deep or shallow copy?

If the elements in the source vector are pointers to other data, then a deep copy is wanted sometimes.

According to wikipedia:

A deep copy, meaning that fields are dereferenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B.

Actually, there is no currently a built-in way in C++ to do a deep copy. All of the ways mentioned above are shallow. If a deep copy is necessary, you can traverse a vector and make copy of the references manually. Alternatively, an iterator can be considered for traversing. Discussion on iterator is beyond this question.

References

The page of std::vector on cplusplus.com

c++ and opencv get and set pixel color to Mat

You did everything except copying the new pixel value back to the image.

This line takes a copy of the pixel into a local variable:

Vec3b color = image.at<Vec3b>(Point(x,y));

So, after changing color as you require, just set it back like this:

image.at<Vec3b>(Point(x,y)) = color;

So, in full, something like this:

Mat image = img;
for(int y=0;y<img.rows;y++)
{
    for(int x=0;x<img.cols;x++)
    {
        // get pixel
        Vec3b & color = image.at<Vec3b>(y,x);

        // ... do something to the color ....
        color[0] = 13;
        color[1] = 13;
        color[2] = 13;

        // set pixel
        //image.at<Vec3b>(Point(x,y)) = color;
        //if you copy value
    }
}

Oracle: SQL query that returns rows with only numeric values

You can use the REGEXP_LIKE function as:

SELECT X 
FROM myTable 
WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

Sample run:

SQL> SELECT X FROM SO;

X
--------------------
12c
123
abc
a12

SQL> SELECT X  FROM SO WHERE REGEXP_LIKE(X, '^[[:digit:]]+$');

X
--------------------
123

SQL> 

How to set JAVA_HOME for multiple Tomcat instances?

Also, note that there shouldn't be any space after =:

set JAVA_HOME=C:\Program Files\Java\jdk1.6.0_27

iPhone SDK on Windows (alternative solutions)

You could do what saurik of Cydia does, and write your code on a PC then build it on the iPhone itself (it is a Mac, technically!) after you jailbreak it. However, you don't get Interface Builder, so you're basically creating UIs in code by hand. It'd also be pretty tough to actually submit your app without a Mac.

How to create directory automatically on SD card

Had the same problem and just want to add that AndroidManifest.xml also needs this permission:

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

VBA Excel - Insert row below with same format including borders and frames

The easiest option is to make use of the Excel copy/paste.

Public Sub insertRowBelow()
ActiveCell.Offset(1).EntireRow.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromRightOrAbove
ActiveCell.EntireRow.Copy
ActiveCell.Offset(1).EntireRow.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
End Sub

How to make bootstrap 3 fluid layout without horizontal scrollbar

This worked for me. Tested in FF, Chrome, IE11, IE10

.row {
    width:99.99%;
}

Detect touch press vs long press vs movement?

I discovered this after a lot of experimentation.

In the initialisation of your activity:

setOnLongClickListener(new View.OnLongClickListener() {
  public boolean onLongClick(View view) {
    activity.openContextMenu(view);  
    return true;  // avoid extra click events
  }
});
setOnTouch(new View.OnTouchListener(){
  public boolean onTouch(View v, MotionEvent e){
    switch(e.getAction & MotionEvent.ACTION_MASK){
      // do drag/gesture processing. 
    }
    // you MUST return false for ACTION_DOWN and ACTION_UP, for long click to work
    // you can return true for ACTION_MOVEs that you consume. 
    // DOWN/UP are needed by the long click timer.
    // if you want, you can consume the UP if you have made a drag - so that after 
    // a long drag, no long-click is generated.
    return false;
  }
});
setLongClickable(true);

Loop in react-native

You can create render the results (payments) and use a fancy way to iterate over items instead of adding a for loop.

_x000D_
_x000D_
const noGuest = 3;_x000D_
_x000D_
Array(noGuest).fill(noGuest).map(guest => {_x000D_
  console.log(guest);_x000D_
});
_x000D_
_x000D_
_x000D_

Example:

renderPayments(noGuest) {
  return Array(noGuest).fill(noGuest).map((guess, index) => {
    return(
      <View key={index}>
        <View><TextInput /></View>
        <View><TextInput /></View>
        <View><TextInput /></View>
      </View>
    );
  }
}

Then use it where you want it

render() {
  return(
     const { guest } = this.state;
     ...
     {this.renderPayments(guest)}
  );
}

Hope you got the idea.

If you want to understand this in simple Javascript check Array.prototype.fill()

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

All answers above contribute important info on the original question. However, there is a generalization that seems wrong.

It is possible to set width and height to at least one inline element (that I can think of) – the <img> element.

Both accepted answers here and on this duplicate state that this is not possible but this doesn’t seem like a valid general rule.

Example:

_x000D_
_x000D_
img {_x000D_
  width: 200px;_x000D_
  height: 200px;_x000D_
  border: 1px solid red;_x000D_
}
_x000D_
<img src="#" />
_x000D_
_x000D_
_x000D_

The img has display: inline, but its width and height were successfully set.

React PropTypes : Allow different types of PropTypes for one prop

This might work for you:

height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),

node.js require all files in a folder?

If you include all files of *.js in directory example ("app/lib/*.js"):

In directory app/lib

example.js:

module.exports = function (example) { }

example-2.js:

module.exports = function (example2) { }

In directory app create index.js

index.js:

module.exports = require('./app/lib');

CSV with comma or semicolon?

CSV is a Comma Seperated File. Generally the delimiter is a comma, but I have seen many other characters used as delimiters. They are just not as frequently used.

As for advising you on what to use, we need to know your application. Is the file specific to your application/program, or does this need to work with other programs?

How do browser cookie domains work?

I tested all the cases in the latest Chrome, Firefox, Safari in 2019.

Response to Added:

  • Will a cookie for .example.com be available for www.example.com? YES
  • Will a cookie for .example.com be available for example.com? YES
  • Will a cookie for example.com be available for www.example.com? NO, Domain without wildcard only matches itself.
  • Will a cookie for example.com be available for anotherexample.com? NO
  • Will www.example.com be able to set cookie for example.com? NO, it will be able to set cookie for '.example.com', but not 'example.com'.
  • Will www.example.com be able to set cookie for www2.example.com? NO. But it can set cookie for .example.com, which www2.example.com can access.
  • Will www.example.com be able to set cookie for .com? NO

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

You actually need 3 meta tags to support Android, iPhone and Windows Phone

<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">

Skip the headers when editing a csv file using Python

Your reader variable is an iterable, by looping over it you retrieve the rows.

To make it skip one item before your loop, simply call next(reader, None) and ignore the return value.

You can also simplify your code a little; use the opened files as context managers to have them closed automatically:

with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
   reader = csv.reader(infile)
   next(reader, None)  # skip the headers
   writer = csv.writer(outfile)
   for row in reader:
       # process each row
       writer.writerow(row)

# no need to close, the files are closed automatically when you get to this point.

If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next() to writer.writerow():

headers = next(reader, None)  # returns the headers or `None` if the input is empty
if headers:
    writer.writerow(headers)

Facebook Graph API : get larger pictures in one request

rest-fb users (square image, bigger res.): Connection myFriends = fbClient.fetchConnection("me/friends", User.class, Parameter.with("fields", "public_profile,email,first_name,last_name,gender,picture.width(100).height(100)"));

How to make rectangular image appear circular with CSS

I've been researching this very same problem and couldn't find a decent solution other than having the div with the image as background and the img tag inside of it with visibility none or something like this.

One thing I might add is that you should add a background-size: cover to the div, so that your image fills the background by clipping it's excess.

How to use SVG markers in Google Maps API v3

Things are going better, right now you can use SVG files.

        marker = new google.maps.Marker({
            position: {lat: 36.720426, lng: -4.412573},
            map: map,
            draggable: true,
            icon: "img/tree.svg"
        });

Closing Applications

What role do they play when exiting an application in C#?

The same as every other application. Basically they get returned to the caller. Irrelvant if ythe start was an iicon double click. Relevant is the call is a batch file that decides whether the app worked on the return code. SO, unless you write a program that needs this, the return dcode IS irrelevant.

But what is the difference?

One comes from environment one from the System.Windows.Forms?.Application. Functionall there should not bbe a lot of difference.

Pass in an array of Deferreds to $.when()

If you're using angularJS or some variant of the Q promise library, then you have a .all() method that solves this exact problem.

var savePromises = [];
angular.forEach(models, function(model){
  savePromises.push(
    model.saveToServer()
  )
});

$q.all(savePromises).then(
  function success(results){...},
  function failed(results){...}
);

see the full API:

https://github.com/kriskowal/q/wiki/API-Reference#promiseall

https://docs.angularjs.org/api/ng/service/$q

What is Linux’s native GUI API?

I suppose the question is more like "What is linux's native GUI API".

In most cases X (aka X11) will be used for that: http://en.wikipedia.org/wiki/X_Window_System.

You can find the API documentation here

"An attempt was made to access a socket in a way forbidden by its access permissions" while using SMTP

Please confirm that your firewall is allowing outbound traffic and that you are not being blocked by antivirus software.

I received the same issue and the culprit was antivirus software.

Specifying an Index (Non-Unique Key) Using JPA

EclipseLink provided an annotation (e.g. @Index) to define an index on columns. There is an example of its use. Part of the example is included...

The firstName and lastName fields are indexed, together and individually.

@Entity
@Index(name="EMP_NAME_INDEX", columnNames={"F_NAME","L_NAME"})  // Columns indexed together
public class Employee{
    @Id
    private long id;

    @Index                      // F_NAME column indexed
    @Column(name="F_NAME")
    private String firstName;

    @Index                      // L_NAME column indexed
    @Column(name="L_NAME")
    private String lastName;
    ...
}

How to add a primary key to a MySQL table?

Remove quotes to work properly...

alter table goods add column id int(10) unsigned primary KEY AUTO_INCREMENT;

Failed to build gem native extension (installing Compass)

For me to solve this issue, I had to make sure I had the most current version of Ruby and the gems gem update --system; then, I had to make sure that Xcode & the Command Line Tools were installed: xcode-select --install.

How to do Base64 encoding in node.js?

The accepted answer previously contained new Buffer(), which is considered a security issue in node versions greater than 6 (although it seems likely for this usecase that the input can always be coerced to a string).

The Buffer constructor is deprecated according to the documentation.

Here is an example of a vulnerability that can result from using it in the ws library.

The code snippets should read:

console.log(Buffer.from("Hello World").toString('base64'));
console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'));

After this answer was written, it has been updated and now matches this.

How to get a string after a specific substring?

I'm surprised nobody mentioned partition.

def substring_after(s, delim):
    return s.partition(delim)[2]

IMHO, this solution is more readable than @arshajii's. Other than that, I think @arshajii's is the best for being the fastest -- it does not create any unnecessary copies/substrings.

Check if all checkboxes are selected

Part 1 of your question:

var allChecked = true;
$("input.abc").each(function(index, element){
  if(!element.checked){
    allChecked = false;
    return false;
  } 
});

EDIT:

The answer (http://stackoverflow.com/questions/5541387/check-if-all-checkboxes-are-selected/5541480#5541480) above is probably better.

Solve Cross Origin Resource Sharing with Flask

I struggled a lot with something similar. Try the following:

  1. Use some sort of browser plugin which can display the HTML headers.
  2. Enter the URL to your service, and view the returned header values.
  3. Make sure Access-Control-Allow-Origin is set to one and only one domain, which should be the request origin. Do not set Access-Control-Allow-Origin to *.

If this doesn't help, take a look at this article. It's on PHP, but it describes exactly which headers must be set to which values for CORS to work.

CORS That Works In IE, Firefox, Chrome And Safari

Available text color classes in Bootstrap

You can use text classes:

.text-primary
.text-secondary
.text-success
.text-danger
.text-warning
.text-info
.text-light
.text-dark
.text-muted
.text-white

use text classes in any tag where needed.

<p class="text-primary">.text-primary</p>
<p class="text-secondary">.text-secondary</p>
<p class="text-success">.text-success</p>
<p class="text-danger">.text-danger</p>
<p class="text-warning">.text-warning</p>
<p class="text-info">.text-info</p>
<p class="text-light bg-dark">.text-light</p>
<p class="text-dark">.text-dark</p>
<p class="text-muted">.text-muted</p>
<p class="text-white bg-dark">.text-white</p>

You can add your own classes or modify above classes as your requirement.

Populating a database in a Laravel migration file

I tried this DB insert method, but as it does not use the model, it ignored a sluggable trait I had on the model. So, given the Model for this table exists, as soon as its migrated, I figured the model would be available to use to insert data. And I came up with this:

public function up() {
        Schema::create('parent_categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('slug');
            $table->timestamps();
        });
        ParentCategory::create(
            [
                'id' => 1,
                'name' => 'Occasions',
            ],
        );
    }

This worked correctly, and also took into account the sluggable trait on my Model to automatically generate a slug for this entry, and uses the timestamps too. NB. Adding the ID was no neccesary, however, I wanted specific IDs for my categories in this example. Tested working on Laravel 5.8

Google maps Marker Label with multiple characters

First of all, Thanks to code author!

I found the below link while googling and it is very simple and works best. Would never fail unless SVG is deprecated.

https://codepen.io/moistpaint/pen/ywFDe/

There is some js loading error in the code here but its perfectly working on the codepen.io link provided.

_x000D_
_x000D_
var mapOptions = {_x000D_
    zoom: 16,_x000D_
    center: new google.maps.LatLng(-37.808846, 144.963435)_x000D_
  };_x000D_
  map = new google.maps.Map(document.getElementById('map-canvas'),_x000D_
      mapOptions);_x000D_
_x000D_
_x000D_
var pinz = [_x000D_
    {_x000D_
        'location':{_x000D_
            'lat' : -37.807817,_x000D_
            'lon' : 144.958377_x000D_
        },_x000D_
        'lable' : 2_x000D_
    },_x000D_
    {_x000D_
        'location':{_x000D_
            'lat' : -37.807885,_x000D_
            'lon' : 144.965415_x000D_
        },_x000D_
        'lable' : 42_x000D_
    },_x000D_
    {_x000D_
        'location':{_x000D_
            'lat' : -37.811377,_x000D_
            'lon' : 144.956596_x000D_
        },_x000D_
        'lable' : 87_x000D_
    },_x000D_
    {_x000D_
        'location':{_x000D_
            'lat' : -37.811293,_x000D_
            'lon' : 144.962883_x000D_
        },_x000D_
        'lable' : 145_x000D_
    },_x000D_
    {_x000D_
        'location':{_x000D_
            'lat' : -37.808089,_x000D_
            'lon' : 144.962089_x000D_
        },_x000D_
        'lable' : 999_x000D_
    },_x000D_
];_x000D_
_x000D_
 _x000D_
_x000D_
for(var i = 0; i <= pinz.length; i++){_x000D_
   var image = 'data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%2238%22%20height%3D%2238%22%20viewBox%3D%220%200%2038%2038%22%3E%3Cpath%20fill%3D%22%23808080%22%20stroke%3D%22%23ccc%22%20stroke-width%3D%22.5%22%20d%3D%22M34.305%2016.234c0%208.83-15.148%2019.158-15.148%2019.158S3.507%2025.065%203.507%2016.1c0-8.505%206.894-14.304%2015.4-14.304%208.504%200%2015.398%205.933%2015.398%2014.438z%22%2F%3E%3Ctext%20transform%3D%22translate%2819%2018.5%29%22%20fill%3D%22%23fff%22%20style%3D%22font-family%3A%20Arial%2C%20sans-serif%3Bfont-weight%3Abold%3Btext-align%3Acenter%3B%22%20font-size%3D%2212%22%20text-anchor%3D%22middle%22%3E' + pinz[i].lable + '%3C%2Ftext%3E%3C%2Fsvg%3E';_x000D_
_x000D_
  _x000D_
   var myLatLng = new google.maps.LatLng(pinz[i].location.lat, pinz[i].location.lon);_x000D_
   var marker = new google.maps.Marker({_x000D_
      position: myLatLng,_x000D_
      map: map,_x000D_
      icon: image_x000D_
  });_x000D_
}
_x000D_
html, body, #map-canvas {_x000D_
  height: 100%;_x000D_
  margin: 0px;_x000D_
  padding: 0px_x000D_
}
_x000D_
<div id="map-canvas"></div>_x000D_
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDtc3qowwB96ObzSu2vvjEoM2pVhZRQNSA&signed_in=true&callback=initMap&libraries=drawing,places"></script>
_x000D_
_x000D_
_x000D_

You just need to uri-encode your SVG html and replace the one in the image variable after "data:image/svg+xml" in the for loop.

For uri encoding you can use uri-encoder-decoder

You can decode the existing svg code first to get a better understanding of what is written.

Warning: Failed propType: Invalid prop `component` supplied to `Route`

If you are not giving export default then it throws an error. check if you have given module.exports = Speaker; //spelling mistake here you have written exoprts and check in all the modules whether you have exported correct.

This certificate has an invalid issuer Apple Push Services

  1. Download https://developer.apple.com/certificationauthority/AppleWWDRCA.cer and double-click to install to Keychain.
  2. Select "View" -> "Show Expired Certificates" in Keychain app.
  3. Confirm "Certificates" category is selected.

    enter image description here

  4. Remove expired Apple Worldwide Developer Relations Certificate Authority certificates from "login" tab and "System" tab.


Here's Apple's answer.

Thanks for bringing this to the attention of the community and apologies for the issues you’ve been having. This issue stems from having a copy of the expired WWDR Intermediate certificate in both your System and Login keychains. To resolve the issue, you should first download and install the new WWDR intermediate certificate (by double-clicking on the file). Next, in the Keychain Access application, select the System keychain. Make sure to select “Show Expired Certificates” in the View menu and then delete the expired version of the Apple Worldwide Developer Relations Certificate Authority Intermediate certificate (expired on February 14, 2016). Your certificates should now appear as valid in Keychain Access and be available to Xcode for submissions to the App Store.

https://forums.developer.apple.com/thread/37208

How can I run a php without a web server?

PHP is a normal sripting language similar to bash or python or perl. So a script with shebang works, at least on linux.

Example PHP file:

#!/usr/bin/env php

<?php

echo("Hello World!\n")

?>

How to run it:

$ chmod 755 hello.php  # do this only once
$ ./hello.php

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

its even easier:

fileList.Where(item => filterList.Contains(item))

in case you want to filter not for an exact match but for a "contains" you can use this expression:

var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));

Https to http redirect using htaccess

Attempt 2 was close to perfect. Just modify it slightly:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

Pass multiple parameters to rest API - Spring

Multiple parameters can be given like below,

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

How to style the parent element when hovering a child element?

Well, this question is asked many times before, and the short typical answer is: It cannot be done by pure CSS. It's in the name: Cascading Style Sheets only supports styling in cascading direction, not up.

But in most circumstances where this effect is wished, like in the given example, there still is the possibility to use these cascading characteristics to reach the desired effect. Consider this pseudo markup:

<parent>
    <sibling></sibling>
    <child></child>
</parent>

The trick is to give the sibling the same size and position as the parent and to style the sibling instead of the parent. This will look like the parent is styled!

Now, how to style the sibling?

When the child is hovered, the parent is too, but the sibling is not. The same goes for the sibling. This concludes in three possible CSS selector paths for styling the sibling:

parent sibling { }
parent sibling:hover { }
parent:hover sibling { }

These different paths allow for some nice possibilities. For instance, unleashing this trick on the example in the question results in this fiddle:

div {position: relative}
div:hover {background: salmon}
div p:hover {background: white}
div p {padding-bottom: 26px}
div button {position: absolute; bottom: 0}

Style parent image example

Obviously, in most cases this trick depends on the use of absolute positioning to give the sibling the same size as the parent, ánd still let the child appear within the parent.

Sometimes it is necessary to use a more qualified selector path in order to select a specific element, as shown in this fiddle which implements the trick multiple times in a tree menu. Quite nice really.

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

I've been struggling with this for 3 days now while attempting to connect to a local API running Laravel valet. I finally figured it out. In my case I had to drag and drop over the LaravelValetCASelfSigned.pem file from ~/.config/valet/CA/LaravelValetCASelfSigned.pem

After verifying the installing within the simulator I had to go to Settings > About > Certificate Trust Settings > and Enable the Laravel Valet VA Self Signed CN

Finally working!!!

Fetch: POST json data

With ES2017 async/await support, this is how to POST a JSON payload:

_x000D_
_x000D_
(async () => {_x000D_
  const rawResponse = await fetch('https://httpbin.org/post', {_x000D_
    method: 'POST',_x000D_
    headers: {_x000D_
      'Accept': 'application/json',_x000D_
      'Content-Type': 'application/json'_x000D_
    },_x000D_
    body: JSON.stringify({a: 1, b: 'Textual content'})_x000D_
  });_x000D_
  const content = await rawResponse.json();_x000D_
_x000D_
  console.log(content);_x000D_
})();
_x000D_
_x000D_
_x000D_

Can't use ES2017? See @vp_art's answer using promises

The question however is asking for an issue caused by a long since fixed chrome bug.
Original answer follows.

chrome devtools doesn't even show the JSON as part of the request

This is the real issue here, and it's a bug with chrome devtools, fixed in Chrome 46.

That code works fine - it is POSTing the JSON correctly, it just cannot be seen.

I'd expect to see the object I've sent back

that's not working because that is not the correct format for JSfiddle's echo.

The correct code is:

var payload = {
    a: 1,
    b: 2
};

var data = new FormData();
data.append( "json", JSON.stringify( payload ) );

fetch("/echo/json/",
{
    method: "POST",
    body: data
})
.then(function(res){ return res.json(); })
.then(function(data){ alert( JSON.stringify( data ) ) })

For endpoints accepting JSON payloads, the original code is correct

Get clicked item and its position in RecyclerView

From the designer, you can set the onClick property of the listItem to a method defined with a single parameter. I have an example method defined below. The method getAdapterPosition will give you the index of the selected listItem.

public void exampleOnClickMethod(View view){
    myRecyclerView.getChildViewHolder(view).getAdapterPosition());
}

For information on setting up a RecyclerView, see the documentation here: https://developer.android.com/guide/topics/ui/layout/recyclerview

Event for Handling the Focus of the EditText

  1. Declare object of EditText on top of class:

     EditText myEditText;
    
  2. Find EditText in onCreate Function and setOnFocusChangeListener of EditText:

    myEditText = findViewById(R.id.yourEditTextNameInxml); 
    
    myEditText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
                @Override
                public void onFocusChange(View view, boolean hasFocus) {
                    if (!hasFocus) {
                         Toast.makeText(this, "Focus Lose", Toast.LENGTH_SHORT).show();
                    }else{
                        Toast.makeText(this, "Get Focus", Toast.LENGTH_SHORT).show();
                    }
    
                }
            });
    

It works fine.

Using Python, find anagrams for a list of words

# list of words
words = ["ROOPA","TABU","OOPAR","BUTA","BUAT" , "PAROO","Soudipta",
        "Kheyali Park", "Tollygaunge", "AROOP","Love","AOORP",
         "Protijayi","Paikpara","dipSouta","Shyambazaar",
        "jayiProti", "North Calcutta", "Sovabazaar"]

#Method 1
A = [''.join(sorted(word)) for word in words]

dict ={}

for indexofsamewords,samewords in enumerate(A):
    dict.setdefault(samewords, []).append(indexofsamewords)
    
print(dict)
#{'AOOPR': [0, 2, 5, 9, 11], 'ABTU': [1, 3, 4], 'Sadioptu': [6, 14], ' KPaaehiklry': [7], 'Taeggllnouy': [8], 'Leov': [10], 'Paiijorty': [12, 16], 'Paaaikpr': [13], 'Saaaabhmryz': [15], ' CNaachlortttu': [17], 'Saaaaborvz': [18]}

for index in dict.values(): 
    print( [words[i] for i in index ] )
    

The Output :

['ROOPA', 'OOPAR', 'PAROO', 'AROOP', 'AOORP']
['TABU', 'BUTA', 'BUAT']
['Soudipta', 'dipSouta']
['Kheyali Park']
['Tollygaunge']
['Love']
['Protijayi', 'jayiProti']
['Paikpara']
['Shyambazaar']
['North Calcutta']
['Sovabazaar']

How to display loading message when an iFrame is loading?

Here's a quick solution for most of the cases:

CSS:

.iframe-loading { 
    background:url(/img/loading.gif) center center no-repeat; 
}

You can use an animated loading GIF if you want to,

HTML:

<div class="iframe-loading">
    <iframe src="http://your_iframe_url_goes_here"  onload="$('.iframe-loading').css('background-image', 'none');"></iframe>
</div>

Using the onload event you can remove the loading image after the source page is loaded inside your iframe.

If you are not using jQuery, just put an id into the div and replace this part of code:

$('.iframe-loading').css('background-image', 'none');

by something like this:

document.getElementById("myDivName").style.backgroundImage = "none";

All the best!

Why are exclamation marks used in Ruby methods?

In general, methods that end in ! indicate that the method will modify the object it's called on. Ruby calls these as "dangerous methods" because they change state that someone else might have a reference to. Here's a simple example for strings:

foo = "A STRING"  # a string called foo
foo.downcase!     # modifies foo itself
puts foo          # prints modified foo

This will output:

a string

In the standard libraries, there are a lot of places you'll see pairs of similarly named methods, one with the ! and one without. The ones without are called "safe methods", and they return a copy of the original with changes applied to the copy, with the callee unchanged. Here's the same example without the !:

foo = "A STRING"    # a string called foo
bar = foo.downcase  # doesn't modify foo; returns a modified string
puts foo            # prints unchanged foo
puts bar            # prints newly created bar

This outputs:

A STRING
a string

Keep in mind this is just a convention, but a lot of Ruby classes follow it. It also helps you keep track of what's getting modified in your code.

npm not working - "read ECONNRESET"

I found "npm config edit" to be more useful to update the entries for https-proxy, proxy, registry

I did something like this

  • npm config list
  • npm config edit (opens in vi)
  • Edit or set the config entries for https-proxy, proxy, registry
  • npm install

iOS: How to store username/password within an app?

There is a small bug in the above code (by the way Dave it was very helpful your post thank you)

In the part where we save the credentials it also needs the following code in order to work properly.

[self.keychainItem setObject:@"myCredentials" forKey:(__bridge id)(kSecAttrService)];

most probably is because the second time we try to (re-)sign in with the same credentials it finds them already assigned in the keychain items and the app crashes. with the above code it works like a charm.

Group by with union mysql select query

select sum(qty), name
from (
    select count(m.owner_id) as qty, o.name
    from transport t,owner o,motorbike m
    where t.type='motobike' and o.owner_id=m.owner_id
        and t.type_id=m.motorbike_id
    group by m.owner_id

    union all

    select count(c.owner_id) as qty, o.name,
    from transport t,owner o,car c
    where t.type='car' and o.owner_id=c.owner_id and t.type_id=c.car_id
    group by c.owner_id
) t
group by name

Floating point exception( core dump

You are getting Floating point exception because Number % i, when i is 0:

int Is_Prime( int Number ){

  int i ;

  for( i = 0 ; i < Number / 2 ; i++ ){

    if( Number % i != 0 ) return -1 ;

  }

  return Number ;

}

Just start the loop at i = 2. Since i = 1 in Number % i it always be equal to zero, since Number is a int.

Maximum number of threads per process in Linux?

check the stack size per thread with ulimit, in my case Redhat Linux 2.6:

    ulimit -a
...
    stack size              (kbytes, -s) 10240

Each of your threads will get this amount of memory (10MB) assigned for it's stack. With a 32bit program and a maximum address space of 4GB, that is a maximum of only 4096MB / 10MB = 409 threads !!! Minus program code, minus heap-space will probably lead to an observed max. of 300 threads.

You should be able to raise this by compiling and running on 64bit or setting ulimit -s 8192 or even ulimit -s 4096. But if this is advisable is another discussion...

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

I think this error can happen for various reasons, but it can be specific to the module you're using. For example I saw this using the uwsgi module, so had to set "uwsgi_read_timeout".

How can I move a tag on a git branch to a different commit?

Delete it with git tag -d <tagname> and then recreate it on the correct commit.

mysql extract year from date format

This should work if the date format is consistent:

select SUBSTRING_INDEX( subdateshow,"/",-1 ) from table 

Difference between char* and const char*?

In neither case can you modify a string literal, regardless of whether the pointer to that string literal is declared as char * or const char *.

However, the difference is that if the pointer is const char * then the compiler must give a diagnostic if you attempt to modify the pointed-to value, but if the pointer is char * then it does not.

Java converting Image to BufferedImage

If you are getting back a sun.awt.image.ToolkitImage, you can cast the Image to that, and then use getBufferedImage() to get the BufferedImage.

So instead of your last line of code where you are casting you would just do:

BufferedImage buffered = ((ToolkitImage) image).getBufferedImage();

Get human readable version of file size?

This feature if available in Boltons which is a very handy library to have for most projects.

>>> bytes2human(128991)
'126K'
>>> bytes2human(100001221)
'95M'
>>> bytes2human(0, 2)
'0.00B'

print arraylist element?

If you want to print an arraylist with integer numbers, as an example you can use below code.

class Test{
    public static void main(String[] args){
        ArrayList<Integer> arraylist = new ArrayList<Integer>();

        for(int i=0; i<=10; i++){
            arraylist .add(i);
        }
       for (Integer n : arraylist ){
            System.out.println(n);
       }
   }
}

The output is above code:

0
1
2
3
4
5
6
7
8
9
10

for loop in Python

In C/C++, we can do the following, as you mentioned

for(int k = 1; k <= c ; k++)
for(int k = 1; k <= c ; k +=2)

We know that here k starts with 1 and go till (predefined) c with step value 1 or 2 gradually. We can do this in Python by following,

for k in range(1,c+1):
for k in range(1,c+1,2):

Check this for more in depth.

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

Convert Json string to Json object in Swift 4

I tried the solutions here, and as? [String:AnyObject] worked for me:

do{
    if let json = stringToParse.data(using: String.Encoding.utf8){
        if let jsonData = try JSONSerialization.jsonObject(with: json, options: .allowFragments) as? [String:AnyObject]{
            let id = jsonData["id"] as! String
            ...
        }
    }
}catch {
    print(error.localizedDescription)

}

I cannot access tomcat admin console?

Perhaps manager app does not exist look if you the manager application is on $APACHE_HOME/server/webapps directory. on this directory you must have : docs,examples, host-manager,manager, ROOT.

How to use confirm using sweet alert?

_x000D_
_x000D_
document.querySelector('#from1').onsubmit = function(e){_x000D_
_x000D_
 swal({_x000D_
    title: "Are you sure?",_x000D_
    text: "You will not be able to recover this imaginary file!",_x000D_
    type: "warning",_x000D_
    showCancelButton: true,_x000D_
    confirmButtonColor: '#DD6B55',_x000D_
    confirmButtonText: 'Yes, I am sure!',_x000D_
    cancelButtonText: "No, cancel it!",_x000D_
    closeOnConfirm: false,_x000D_
    closeOnCancel: false_x000D_
 },_x000D_
 function(isConfirm){_x000D_
_x000D_
   if (isConfirm.value){_x000D_
     swal("Shortlisted!", "Candidates are successfully shortlisted!", "success");_x000D_
_x000D_
    } else {_x000D_
      swal("Cancelled", "Your imaginary file is safe :)", "error");_x000D_
         e.preventDefault();_x000D_
    }_x000D_
 });_x000D_
};
_x000D_
_x000D_
_x000D_

How to save a list to a file and read it as a list type?

Although the accepted answer works, you should really be using python's json module:

import json

score=[1,2,3,4,5]

with open("file.json", 'w') as f:
    # indent=2 is not needed but makes the file human-readable
    json.dump(score, f, indent=2) 

with open("file.json", 'r') as f:
    score = json.load(f)

print(score)

Advantages:

  1. json is a widely adopted and standardized data format, so non-python programs can easily read and understand the json files
  2. json files are human-readable
  3. Any nested or non-nested list/dictionary structure can be saved to a json file (as long as all the contents are serializable).

Disadvantages:

  1. The data is stored in plain-text (ie it's uncompressed), which makes it a slow and bloated option for large amounts of data (ie probably a bad option for storing large numpy arrays, that's what hdf5 is for).
  2. The contents of a list/dictionary need to be serializable before you can save it as a json, so while you can save things like strings, ints, and floats, you'll need to write custom serialization and deserialization code to save objects, classes, and functions

When to use json vs pickle:

  • If you want to store something you know you're only ever going to use in the context of a python program, use pickle
  • If you need to save data that isn't serializable by default (ie objects), save yourself the trouble and use pickle.
  • If you need a platform agnostic solution, use json
  • If you need to be able to inspect and edit the data directly, use json

Common use cases:

  • Configuration files (for example, node.js uses a package.json file to track project details, dependencies, scripts, etc ...)
  • Most REST APIs use json to transmit and receive data
  • Data that requires a nested list/dictionary structure, or requires variable length lists/dicts
  • Can be an alternative to csv, xml or yaml files

Removing header column from pandas dataframe

How to get rid of a header(first row) and an index(first column).

To write to CSV file:

df = pandas.DataFrame(your_array)
df.to_csv('your_array.csv', header=False, index=False)

To read from CSV file:

df = pandas.read_csv('your_array.csv')
a = df.values

If you want to read a CSV file that doesn't contain a header, pass additional parameter header:

df = pandas.read_csv('your_array.csv', header=None)

referenced before assignment error in python

I think you are using 'global' incorrectly. See Python reference. You should declare variable without global and then inside the function when you want to access global variable you declare it global yourvar.

#!/usr/bin/python

total

def checkTotal():
    global total
    total = 0

See this example:

#!/usr/bin/env python

total = 0

def doA():
    # not accessing global total
    total = 10

def doB():
    global total
    total = total + 1

def checkTotal():
    # global total - not required as global is required
    # only for assignment - thanks for comment Greg
    print total

def main():
    doA()
    doB()
    checkTotal()

if __name__ == '__main__':
    main()

Because doA() does not modify the global total the output is 1 not 11.

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Sorting a vector in descending order

With c++14 you can do this:

std::sort(numbers.begin(), numbers.end(), std::greater<>());

Visual Studio opens the default browser instead of Internet Explorer

Quick note if you don't have an .aspx in your project (i.e. its XBAP) but you still need to debug using IE, just add a htm page to your project and right click on that to set the default. It's hacky, but it works :P

How are echo and print different in PHP?

They are:

  • print only takes one parameter, while echo can have multiple parameters.
  • print returns a value (1), so can be used as an expression.
  • echo is slightly faster.

What’s the best RESTful method to return total number of items in an object?

Alternative when you don't need actual items

Franci Penov's answer is certainly the best way to go so you always return items along with all additional metadata about your entities being requested. That's the way it should be done.

but sometimes returning all data doesn't make sense, because you may not need them at all. Maybe all you need is that metadata about your requested resource. Like total count or number of pages or something else. In such case you can always have URL query tell your service not to return items but rather just metadata like:

/api/members?metaonly=true
/api/members?includeitems=0

or something similar...

How an 'if (A && B)' statement is evaluated?

In C and C++, the && and || operators "short-circuit". That means that they only evaluate a parameter if required. If the first parameter to && is false, or the first to || is true, the rest will not be evaluated.

The code you posted is safe, though I question why you'd include an empty else block.

Transpose list of lists

Here is a solution for transposing a list of lists that is not necessarily square:

maxCol = len(l[0])
for row in l:
    rowLength = len(row)
    if rowLength > maxCol:
        maxCol = rowLength
lTrans = []
for colIndex in range(maxCol):
    lTrans.append([])
    for row in l:
        if colIndex < len(row):
            lTrans[colIndex].append(row[colIndex])

Finding the direction of scrolling in a UIScrollView?

No need to add an extra variable to keep track of this. Just use the UIScrollView's panGestureRecognizer property like this. Unfortunately, this works only if the velocity isn't 0:

CGFloat yVelocity = [scrollView.panGestureRecognizer velocityInView:scrollView].y;
if (yVelocity < 0) {
    NSLog(@"Up");
} else if (yVelocity > 0) {
    NSLog(@"Down");
} else {
    NSLog(@"Can't determine direction as velocity is 0");
}

You can use a combination of x and y components to detect up, down, left and right.

How do I declare a model class in my Angular 2 component using TypeScript?

create model.ts in your component directory as below

export module DataModel {
       export interface DataObjectName {
         propertyName: type;
        }
       export interface DataObjectAnother {
         propertyName: type;
        }
    }

then in your component import above as, import {DataModel} from './model';

export class YourComponent {
   public DataObject: DataModel.DataObjectName;
}

your DataObject should have all the properties from DataObjectName.

only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices

put a int infront of the all the voxelCoord's...Like this below :

patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]

How to find the mysql data directory from command line in windows

You can try this-

mysql> select @@datadir;

PS- It works on every platform.

How can I download HTML source in C#

@cms way is the more recent, suggested in MS website, but I had a hard problem to solve, with both method posted here, now I post the solution for all!

problem: if you use an url like this: www.somesite.it/?p=1500 in some case you get an internal server error (500), although in web browser this www.somesite.it/?p=1500 perfectly work.

solution: you have to move out parameters, working code is:

using System.Net;
//...
using (WebClient client = new WebClient ()) 
{
    client.QueryString.Add("p", "1500"); //add parameters
    string htmlCode = client.DownloadString("www.somesite.it");
    //...
}

here official documentation

How can I confirm a database is Oracle & what version it is using SQL?

You can either use

SELECT * FROM v$version;

or

SET SERVEROUTPUT ON
EXEC dbms_output.put_line( dbms_db_version.version );

if you don't want to parse the output of v$version.

How do you tell if a checkbox is selected in Selenium for Java?

public boolean getcheckboxvalue(String element)
    {   
        WebElement webElement=driver.findElement(By.xpath(element));
        return webElement.isSelected();
    }

JavaScript: clone a function

const oldFunction = params => {
  // do something
};

const clonedFunction = (...args) => oldFunction(...args);

Whitespace Matching Regex - Java

You can’t use \s in Java to match white space on its own native character set, because Java doesn’t support the Unicode white space property — even though doing so is strictly required to meet UTS#18’s RL1.2! What it does have is not standards-conforming, alas.

Unicode defines 26 code points as \p{White_Space}: 20 of them are various sorts of \pZ GeneralCategory=Separator, and the remaining 6 are \p{Cc} GeneralCategory=Control.

White space is a pretty stable property, and those same ones have been around virtually forever. Even so, Java has no property that conforms to The Unicode Standard for these, so you instead have to use code like this:

String whitespace_chars =  ""       /* dummy empty string for homogeneity */
                        + "\\u0009" // CHARACTER TABULATION
                        + "\\u000A" // LINE FEED (LF)
                        + "\\u000B" // LINE TABULATION
                        + "\\u000C" // FORM FEED (FF)
                        + "\\u000D" // CARRIAGE RETURN (CR)
                        + "\\u0020" // SPACE
                        + "\\u0085" // NEXT LINE (NEL) 
                        + "\\u00A0" // NO-BREAK SPACE
                        + "\\u1680" // OGHAM SPACE MARK
                        + "\\u180E" // MONGOLIAN VOWEL SEPARATOR
                        + "\\u2000" // EN QUAD 
                        + "\\u2001" // EM QUAD 
                        + "\\u2002" // EN SPACE
                        + "\\u2003" // EM SPACE
                        + "\\u2004" // THREE-PER-EM SPACE
                        + "\\u2005" // FOUR-PER-EM SPACE
                        + "\\u2006" // SIX-PER-EM SPACE
                        + "\\u2007" // FIGURE SPACE
                        + "\\u2008" // PUNCTUATION SPACE
                        + "\\u2009" // THIN SPACE
                        + "\\u200A" // HAIR SPACE
                        + "\\u2028" // LINE SEPARATOR
                        + "\\u2029" // PARAGRAPH SEPARATOR
                        + "\\u202F" // NARROW NO-BREAK SPACE
                        + "\\u205F" // MEDIUM MATHEMATICAL SPACE
                        + "\\u3000" // IDEOGRAPHIC SPACE
                        ;        
/* A \s that actually works for Java’s native character set: Unicode */
String     whitespace_charclass = "["  + whitespace_chars + "]";    
/* A \S that actually works for  Java’s native character set: Unicode */
String not_whitespace_charclass = "[^" + whitespace_chars + "]";

Now you can use whitespace_charclass + "+" as the pattern in your replaceAll.


Sorry ’bout all that. Java’s regexes just don’t work very well on its own native character set, and so you really have to jump through exotic hoops to make them work.

And if you think white space is bad, you should see what you have to do to get \w and \b to finally behave properly!

Yes, it’s possible, and yes, it’s a mindnumbing mess. That’s being charitable, even. The easiest way to get a standards-comforming regex library for Java is to JNI over to ICU’s stuff. That’s what Google does for Android, because OraSun’s doesn’t measure up.

If you don’t want to do that but still want to stick with Java, I have a front-end regex rewriting library I wrote that “fixes” Java’s patterns, at least to get them conform to the requirements of RL1.2a in UTS#18, Unicode Regular Expressions.

What is an undefined reference/unresolved external symbol error and how do I fix it?

The order in which interdependent linked libraries are specified is wrong.

The order in which libraries are linked DOES matter if the libraries depend on each other. In general, if library A depends on library B, then libA MUST appear before libB in the linker flags.

For example:

// B.h
#ifndef B_H
#define B_H

struct B {
    B(int);
    int x;
};

#endif

// B.cpp
#include "B.h"
B::B(int xx) : x(xx) {}

// A.h
#include "B.h"

struct A {
    A(int x);
    B b;
};

// A.cpp
#include "A.h"

A::A(int x) : b(x) {}

// main.cpp
#include "A.h"

int main() {
    A a(5);
    return 0;
};

Create the libraries:

$ g++ -c A.cpp
$ g++ -c B.cpp
$ ar rvs libA.a A.o 
ar: creating libA.a
a - A.o
$ ar rvs libB.a B.o 
ar: creating libB.a
a - B.o

Compile:

$ g++ main.cpp -L. -lB -lA
./libA.a(A.o): In function `A::A(int)':
A.cpp:(.text+0x1c): undefined reference to `B::B(int)'
collect2: error: ld returned 1 exit status
$ g++ main.cpp -L. -lA -lB
$ ./a.out

So to repeat again, the order DOES matter!

Why isn't .ico file defined when setting window's icon?

Try this:

from tkinter import *
import os
import sys

root = Tk()
root.iconbitmap(os.path.join(sys.path[0], '<your-ico-file>'))

root.mainloop()

Note: replace <your-ico-file> with the name of the ico file you are using otherwise it won't work.

I have tried this in Python 3. It worked.

Concept of void pointer in C programming

No, it is not possible. What type should the dereferenced value have?

How to format DateTime in Flutter , How to get current time in flutter?

there is some change since the 0.16 so here how i did,

import in the pubspec.yaml

dependencies:
      flutter:
        sdk: flutter
      intl: ^0.16.1

then use

  txdate= DateTime.now()


  DateFormat.yMMMd().format(txdate)

Javascript to set hidden form value on drop down change

If you have HTML like this, for example:

<select id='myselect'>
    <option value='1'>A</option>
    <option value='2'>B</option>
    <option value='3'>C</option>
    <option value='4'>D</option>
</select>
<input type='hidden' id='myhidden' value=''>

All you have to do is bind a function to the change event of the select, and do what you need there:

<script type='text/javascript'>
$(function() {
    $('#myselect').change(function() {
        // if changed to, for example, the last option, then
        // $(this).find('option:selected').text() == D
        // $(this).val() == 4
        // get whatever value you want into a variable
        var x = $(this).val();
        // and update the hidden input's value
        $('#myhidden').val(x);
    });
});
</script>

All things considered, if you're going to be doing a lot of jQuery programming, always have the documentation open. It is very easy to find what you need there if you give it a chance.

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

I wouldn't worry about it. Don't put it on your own server, it sounds like this is an issue with Google, but as good as it gets. Putting the file on your own server will create many new problems.

They probably need the file to get called every time rather than getting it from the client's cache, since that way you wouldn't count the visits.

If you have a problem to feel fine with that, run the Google insights URL on Google insights itself, have a laugh, relax and get on with your work.

Initialise a list to a specific length in Python

list multiplication works.

>>> [0] * 10
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

The given key was not present in the dictionary. Which key?

string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"

With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.

Adding files to java classpath at runtime

Try this one on for size.

private static void addSoftwareLibrary(File file) throws Exception {
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", new Class[]{URL.class});
    method.setAccessible(true);
    method.invoke(ClassLoader.getSystemClassLoader(), new Object[]{file.toURI().toURL()});
}

This edits the system class loader to include the given library jar. It is pretty ugly, but it works.

C++ Erase vector element by value rather than by position?

You can use std::find to get an iterator to a value:

#include <algorithm>
std::vector<int>::iterator position = std::find(myVector.begin(), myVector.end(), 8);
if (position != myVector.end()) // == myVector.end() means the element was not found
    myVector.erase(position);

How do I implement __getattribute__ without an infinite recursion error?

You get a recursion error because your attempt to access the self.__dict__ attribute inside __getattribute__ invokes your __getattribute__ again. If you use object's __getattribute__ instead, it works:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return object.__getattribute__(self, name)

This works because object (in this example) is the base class. By calling the base version of __getattribute__ you avoid the recursive hell you were in before.

Ipython output with code in foo.py:

In [1]: from foo import *

In [2]: d = D()

In [3]: d.test
Out[3]: 0.0

In [4]: d.test2
Out[4]: 21

Update:

There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.

Show/Hide Table Rows using Javascript classes

It's difficult to figure out what you're trying to do with this sample but you're actually on the right track thinking about using classes. I've created a JSFiddle to help demonstrate a slightly better way (I hope) of doing this.

Here's the fiddle: link.

What you do is, instead of working with IDs, you work with classes. In your code sample, there are Oranges and Apples. I treat them as product categories (as I don't really know what your purpose is), with their own ids. So, I mark the product <tr>s with class="cat1" or class="cat2".

I also mark the links with a simple .toggler class. It's not good practice to have onclick attributes on elements themselves. You should 'bind' the events on page load using JavaScript. I do this using jQuery.

$(".toggler").click(function(e){
    // you handle the event here
});

With this format, you are binding an event handler to the click event of links with class toggler. In my code, I add a data-prod-cat attribute to the toggler links to specify which product rows they should control. (The reason for my using a data-* attribute is explained here. You can Google 'html5 data attributes' for more information.)

In the event handler, I do this:

$('.cat'+$(this).attr('data-prod-cat')).toggle();

With this code, I'm actually trying to create a selector like $('.cat1') so I can select rows for a specific product category, and change their visibility. I use $(this).attr('data-prod-cat') this to access the data-prod-cat attribute of the link the user clicks. I use the jQuery toggle function, so that I don't have to write logic like if visible, then hide element, else make it visible like you do in your JS code. jQuery deals with that. The toggle function does what it says and toggles the visibility of the specified element(s).

I hope this was explanatory enough.

Repeat string to certain length

def extended_string (word, length) :

    extra_long_word = word * (length//len(word) + 1)
    required_string = extra_long_word[:length]
    return required_string

print(extended_string("abc", 7))

Extracting specific columns in numpy array

One more thing you should pay attention to when selecting columns from N-D array using a list like this:

data[:,:,[1,9]]

If you are removing a dimension (by selecting only one row, for example), the resulting array will be (for some reason) permuted. So:

print data.shape            # gives [10,20,30]
selection = data[1,:,[1,9]]
print selection.shape       # gives [2,20] instead of [20,2]!!

BackgroundWorker vs background Thread

The basic difference is, like you stated, generating GUI events from the BackgroundWorker. If the thread does not need to update the display or generate events for the main GUI thread, then it can be a simple thread.

close vs shutdown socket?

linux: shutdown() causes listener thread select() to awake and produce error. shutdown(); close(); will lead to endless wait.

winsock: vice versa - shutdown() has no effect, while close() is successfully catched.

Jboss server error : Failed to start service jboss.deployment.unit."jbpm-console.war"

I had the exact same problem, found that I was missing

<mdb>  
  <resource-adapter-ref resource-adapter-name="hornetq-ra"/>  
  <bean-instance-pool-ref pool-name="mdb-strict-max-pool"/>  
</mdb>  

under

<subsystem xmlns="urn:jboss:domain:ejb3:1.2">  

in standalone/configuration/standalone.xml

Add a column to existing table and uniquely number them on MS SQL Server

Just using an ALTER TABLE should work. Add the column with the proper type and an IDENTITY flag and it should do the trick

Check out this MSDN article http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx on the ALTER TABLE syntax

Check orientation on Android phone

The Android SDK can tell you this just fine:

getResources().getConfiguration().orientation

How to fast get Hardware-ID in C#?

We use a combination of the processor id number (ProcessorID) from Win32_processor and the universally unique identifier (UUID) from Win32_ComputerSystemProduct:

ManagementObjectCollection mbsList = null;
ManagementObjectSearcher mos = new ManagementObjectSearcher("Select ProcessorID From Win32_processor");
mbsList = mos.Get();
string processorId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    processorId = mo["ProcessorID"] as string;
}

mos = new ManagementObjectSearcher("SELECT UUID FROM Win32_ComputerSystemProduct");
mbsList = mos.Get();
string systemId = string.Empty;
foreach (ManagementBaseObject mo in mbsList)
{
    systemId = mo["UUID"] as string;
}

var compIdStr = $"{processorId}{systemId}";

Previously, we used a combination: processor ID ("Select ProcessorID From Win32_processor") and the motherboard serial number ("SELECT SerialNumber FROM Win32_BaseBoard"), but then we found out that the serial number of the motherboard may not be filled in, or it may be filled in with uniform values:

  • To be filled by O.E.M.
  • None
  • Default string

Therefore, it is worth considering this situation.

Also keep in mind that the ProcessorID number may be the same on different computers.

Git credential helper - update password

Just cd in the directory where you have installed git-credential-winstore. If you don't know where, just run this in Git Bash:

cat ~/.gitconfig

It should print something looking like:

[credential]
    helper = !'C:\\ProgramFile\\GitCredStore\\git-credential-winstore.exe'

In this case, you repository is C:\ProgramFile\GitCredStore. Once you are inside this folder using Git Bash or the Windows command, just type:

git-credential-winstore.exe erase
host=github.com
protocol=https

Don't forget to press Enter twice after protocol=https.

How to enumerate an enum

There are two ways to iterate an Enum:

1. var values =  Enum.GetValues(typeof(myenum))
2. var values =  Enum.GetNames(typeof(myenum))

The first will give you values in form on an array of **object**s, and the second will give you values in form of an array of **String**s.

Use it in a foreach loop as below:

foreach(var value in values)
{
    // Do operations here
}

Selecting the first "n" items with jQuery

You probably want to read up on slice. Your code will look something like this:

$("a").slice(0,20)

Call async/await functions in parallel

TL;DR

Use Promise.all for the parallel function calls, the answer behaviors not correctly when the error occurs.


First, execute all the asynchronous calls at once and obtain all the Promise objects. Second, use await on the Promise objects. This way, while you wait for the first Promise to resolve the other asynchronous calls are still progressing. Overall, you will only wait for as long as the slowest asynchronous call. For example:

// Begin first call and store promise without waiting
const someResult = someCall();

// Begin second call and store promise without waiting
const anotherResult = anotherCall();

// Now we await for both results, whose async processes have already been started
const finalResult = [await someResult, await anotherResult];

// At this point all calls have been resolved
// Now when accessing someResult| anotherResult,
// you will have a value instead of a promise

JSbin example: http://jsbin.com/xerifanima/edit?js,console

Caveat: It doesn't matter if the await calls are on the same line or on different lines, so long as the first await call happens after all of the asynchronous calls. See JohnnyHK's comment.


Update: this answer has a different timing in error handling according to the @bergi's answer, it does NOT throw out the error as the error occurs but after all the promises are executed. I compare the result with @jonny's tip: [result1, result2] = Promise.all([async1(), async2()]), check the following code snippet

_x000D_
_x000D_
const correctAsync500ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 500, 'correct500msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const correctAsync100ms = () => {_x000D_
  return new Promise(resolve => {_x000D_
    setTimeout(resolve, 100, 'correct100msResult');_x000D_
  });_x000D_
};_x000D_
_x000D_
const rejectAsync100ms = () => {_x000D_
  return new Promise((resolve, reject) => {_x000D_
    setTimeout(reject, 100, 'reject100msError');_x000D_
  });_x000D_
};_x000D_
_x000D_
const asyncInArray = async (fun1, fun2) => {_x000D_
  const label = 'test async functions in array';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    const p1 = fun1();_x000D_
    const p2 = fun2();_x000D_
    const result = [await p1, await p2];_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
const asyncInPromiseAll = async (fun1, fun2) => {_x000D_
  const label = 'test async functions with Promise.all';_x000D_
  try {_x000D_
    console.time(label);_x000D_
    let [value1, value2] = await Promise.all([fun1(), fun2()]);_x000D_
    console.timeEnd(label);_x000D_
  } catch (e) {_x000D_
    console.error('error is', e);_x000D_
    console.timeEnd(label);_x000D_
  }_x000D_
};_x000D_
_x000D_
(async () => {_x000D_
  console.group('async functions without error');_x000D_
  console.log('async functions without error: start')_x000D_
  await asyncInArray(correctAsync500ms, correctAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, correctAsync100ms);_x000D_
  console.groupEnd();_x000D_
_x000D_
  console.group('async functions with error');_x000D_
  console.log('async functions with error: start')_x000D_
  await asyncInArray(correctAsync500ms, rejectAsync100ms);_x000D_
  await asyncInPromiseAll(correctAsync500ms, rejectAsync100ms);_x000D_
  console.groupEnd();_x000D_
})();
_x000D_
_x000D_
_x000D_

Parse a URI String into Name-Value Collection

Just an update to the Java 8 version

public Map<String, List<String>> splitQuery(URL url) {
    if (Strings.isNullOrEmpty(url.getQuery())) {
        return Collections.emptyMap();
    }
    return Arrays.stream(url.getQuery().split("&"))
            .map(this::splitQueryParameter)
            .collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, **Collectors**.mapping(Map.Entry::getValue, **Collectors**.toList())));
}

mapping and toList() methods have to be used with Collectors which was not mentioned in the top answer. Otherwise it would throw compilation error in IDE

How do I convert date/time from 24-hour format to 12-hour AM/PM?

Use smaller h

// 24 hrs 
H:i 
// output 14:20

// 12 hrs 
h:i 
// output 2:20

Localhost not working in chrome and firefox

Finally I found the solution ... It's very easy

  1. Go to the LAN settings (In Chrome : Tools -> Options -> Under the hood -> Change Proxy setting -> LAN Setting)

  2. There will be a checkbox for "Bypass proxy server for local address"

  3. Tick the checkbox.

Done!

On Mac/Apple: Chrome uses system preferences for localhost exclusion:

  1. Go to System Preferences -> Network -> advanced -> Proxy settings

  2. Add 'localhost' at the bottom where it says: 'ignore proxy settings for these hosts and domains' (Exceptions are separated by a comma)

VBA paste range

This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:

'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Sub CopyLayout(TargetRange As Range, typee As Integer)
    Application.ScreenUpdating = False
        Dim ncolumn As Integer
        Dim nrow As Integer

        SheetLayout.Activate
    If (typee = 1) Then 'is installation
        Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    ElseIf (typee = 2) Then 'is package
        Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    End If

    Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@

    If typee = 1 Then
       nrow = SheetLayout.Range("installationlayout").Rows.Count
       ncolumn = SheetLayout.Range("installationlayout").Columns.Count

       Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    ElseIf typee = 2 Then
       nrow = SheetLayout.Range("PackageLayout").Rows.Count
       ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
       Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    End If
    Range("A1").Select 'Deselect the created table

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
    Dim R As Long, C As Long

    For R = 1 To RowCount
        PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
        If R >= 2 And R < RowCount Then
            PastedTable.Rows(R).Group 'Main group of the table
        End If
        If R = 2 Then
            PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
        ElseIf (R = 4 And typee = 1) Then
            PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
        End If
    Next R

    For C = 1 To ColumnCount
        PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
    Next C
End Function



Sub test ()
    Call CopyLayout(Sheet2.Range("A18"), 2)
end sub

Using intents to pass data between activities

In FirstActivity:

Intent sendDataToSecondActivity = new Intent(FirstActivity.this, SecondActivity.class);
sendDataToSecondActivity.putExtra("USERNAME",userNameEditText.getText().toString());
sendDataToSecondActivity.putExtra("PASSWORD",passwordEditText.getText().toString());
startActivity(sendDataToSecondActivity);

In SecondActivity

In onCreate()

String userName = getIntent().getStringExtra("USERNAME");
String passWord = getIntent().getStringExtra("PASSWORD");

Java: String - add character n-times

 String toAdd = "toAdd";
 StringBuilder s = new StringBuilder();
 for(int count = 0; count < MAX; count++) {
     s.append(toAdd);
  }
  String output = s.toString();

How to run the sftp command with a password from Bash script?

You can use lftp interactively in a shell script so the password not saved in .bash_history or similar by doing the following:

vi test_script.sh

Add the following to your file:

#!/bin/sh
HOST=<yourhostname>
USER=<someusername>
PASSWD=<yourpasswd>

cd <base directory for your put file>

lftp<<END_SCRIPT
open sftp://$HOST
user $USER $PASSWD
put local-file.name
bye
END_SCRIPT

And write/quit the vi editor after you edit the host, user, pass, and directory for your put file typing :wq .Then make your script executable chmod +x test_script.sh and execute it ./test_script.sh.

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

Abstract methods in Java

If you use the java keyword abstract you cannot provide an implementation.

Sometimes this idea comes from having a background in C++ and mistaking the virtual keyword in C++ as being "almost the same" as the abstract keyword in Java.

In C++ virtual indicates that a method can be overridden and polymorphism will follow, but abstract in Java is not the same thing. In Java abstract is more like a pure virtual method, or one where the implementation must be provided by a subclass. Since Java supports polymorphism without the need to declare it, all methods are virtual from a C++ point of view. So if you want to provide a method that might be overridden, just write it as a "normal" method.

Now to protect a method from being overridden, Java uses the keyword final in coordination with the method declaration to indicate that subclasses cannot override the method.

Check if a string has white space

A few others have posted answers. There are some obvious problems, like it returns false when the Regex passes, and the ^ and $ operators indicate start/end, whereas the question is looking for has (any) whitespace, and not: only contains whitespace (which the regex is checking).

Besides that, the issue is just a typo.

Change this...

var reWhiteSpace = new RegExp("/^\s+$/");

To this...

var reWhiteSpace = new RegExp("\\s+");

When using a regex within RegExp(), you must do the two following things...

  • Omit starting and ending / brackets.
  • Double-escape all sequences code, i.e., \\s in place of \s, etc.

Full working demo from source code....

_x000D_
_x000D_
$(document).ready(function(e) { function hasWhiteSpace(s) {
        var reWhiteSpace = new RegExp("\\s+");
    
        // Check for white space
        if (reWhiteSpace.test(s)) {
            //alert("Please Check Your Fields For Spaces");
            return 'true';
        }
    
        return 'false';
    }
  
  $('#whitespace1').html(hasWhiteSpace(' '));
  $('#whitespace2').html(hasWhiteSpace('123'));
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
" ": <span id="whitespace1"></span><br>
"123": <span id="whitespace2"></span>
_x000D_
_x000D_
_x000D_

How to perform a for-each loop over all the files under a specified path?

More compact version working with spaces and newlines in the file name:

find . -iname '*.txt' -exec sh -c 'echo "{}" ; ls -l "{}"' \;

SQL SERVER: Check if variable is null and then assign statement for Where Clause

Isnull() syntax is built in for this kind of thing.

declare @Int int = null;

declare @Values table ( id int, def varchar(8) )

insert into @Values values (8, 'I am 8');

-- fails
select *
from @Values
where id = @Int

-- works fine
select *
from @Values
where id = isnull(@Int, 8);

For your example keep in mind you can change scope to be yet another where predicate off of a different variable for complex boolean logic. Only caveat is you need to cast it differently if you need to examine for a different data type. So if I add another row but wish to specify int of 8 AND also the reference of text similar to 'repeat' I can do that with a reference again back to the 'isnull' of the first variable yet return an entirely different result data type for a different reference to a different field.

declare @Int int = null;

declare @Values table ( id int, def varchar(16) )

insert into @Values values (8, 'I am 8'), (8, 'I am 8 repeat');

select *
from @Values
where id = isnull(@Int, 8)
and def like isnull(cast(@Int as varchar), '%repeat%')

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

This is the simplest solution to solve horisontal scrolling in Safari.

html, body {
  position:relative;
  overflow-x:hidden;
}

Copy array by value

Primitive values are always pass by its value (copied). Compound values however are passed by reference.

So how do we copy this arr?

let arr = [1,2,3,4,5];

Copy an Array in ES6

let arrCopy = [...arr]; 

Copy n Array in ES5

let arrCopy = arr.slice(); 
let arrCopy = [].concat(arr);

Why `let arrCopy = arr` is not passing by value?

Passing one varible to another on Compound values such as Object/Array behave difrently. Using asign operator on copand values we pass reference to an object. This is why the value of both arrays are changing when removing/adding arr elements.

Exceptions:

arrCopy[1] = 'adding new value this way will unreference';

When you assign a new value to the variable, you are changing the reference itself and it doesn’t affect the original Object/Array.

read more

What is the difference between Python and IPython?

There are few differences between Python and IPython but they are only the interpretation of few syntax like the few mentioned by @Ryan Chase but deep inside the true flavor of Python is maintained even in the Ipython.

The best part of the IPython is the IPython notebook. You can put all your work into a notebook like script, image files, etc. But with base Python, you can only make the script in a file and execute it.

At start, you need to understand that the IPython is developed with the intention of supporting rich media and Python script in a single integrated container.

What is the difference between instanceof and Class.isAssignableFrom(...)?

Talking in terms of performance :

TL;DR

Use isInstance or instanceof which have similar performance. isAssignableFrom is slightly slower.

Sorted by performance:

  1. isInstance
  2. instanceof (+ 0.5%)
  3. isAssignableFrom (+ 2.7%)

Based on a benchmark of 2000 iterations on JAVA 8 Windows x64, with 20 warmup iterations.

In theory

Using a soft like bytecode viewer we can translate each operator into bytecode.

In the context of:

package foo;

public class Benchmark
{
  public static final Object a = new A();
  public static final Object b = new B();

  ...

}

JAVA:

b instanceof A;

Bytecode:

getstatic foo/Benchmark.b:java.lang.Object
instanceof foo/A

JAVA:

A.class.isInstance(b);

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Class isInstance((Ljava/lang/Object;)Z);

JAVA:

A.class.isAssignableFrom(b.getClass());

Bytecode:

ldc Lfoo/A; (org.objectweb.asm.Type)
getstatic foo/Benchmark.b:java.lang.Object
invokevirtual java/lang/Object getClass(()Ljava/lang/Class;);
invokevirtual java/lang/Class isAssignableFrom((Ljava/lang/Class;)Z);

Measuring how many bytecode instructions are used by each operator, we could expect instanceof and isInstance to be faster than isAssignableFrom. However, the actual performance is NOT determined by the bytecode but by the machine code (which is platform dependent). Let's do a micro benchmark for each of the operators.

The benchmark

Credit: As advised by @aleksandr-dubinsky, and thanks to @yura for providing the base code, here is a JMH benchmark (see this tuning guide):

class A {}
class B extends A {}

public class Benchmark {

    public static final Object a = new A();
    public static final Object b = new B();

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testInstanceOf()
    {
        return b instanceof A;
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsInstance()
    {
        return A.class.isInstance(b);
    }

    @Benchmark
    @BenchmarkMode(Mode.Throughput)
    @OutputTimeUnit(TimeUnit.MICROSECONDS)
    public boolean testIsAssignableFrom()
    {
        return A.class.isAssignableFrom(b.getClass());
    }

    public static void main(String[] args) throws RunnerException {
        Options opt = new OptionsBuilder()
                .include(TestPerf2.class.getSimpleName())
                .warmupIterations(20)
                .measurementIterations(2000)
                .forks(1)
                .build();

        new Runner(opt).run();
    }
}

Gave the following results (score is a number of operations in a time unit, so the higher the score the better):

Benchmark                       Mode   Cnt    Score   Error   Units
Benchmark.testIsInstance        thrpt  2000  373,061 ± 0,115  ops/us
Benchmark.testInstanceOf        thrpt  2000  371,047 ± 0,131  ops/us
Benchmark.testIsAssignableFrom  thrpt  2000  363,648 ± 0,289  ops/us

Warning

  • the benchmark is JVM and platform dependent. Since there are no significant differences between each operation, it might be possible to get a different result (and maybe different order!) on a different JAVA version and/or platforms like Solaris, Mac or Linux.
  • the benchmark compares the performance of "is B an instance of A" when "B extends A" directly. If the class hierarchy is deeper and more complex (like B extends X which extends Y which extends Z which extends A), results might be different.
  • it is usually advised to write the code first picking one of the operators (the most convenient) and then profile your code to check if there are a performance bottleneck. Maybe this operator is negligible in the context of your code, or maybe...
  • in relation to the previous point, instanceof in the context of your code might get optimized more easily than an isInstance for example...

To give you an example, take the following loop:

class A{}
class B extends A{}

A b = new B();

boolean execute(){
  return A.class.isAssignableFrom(b.getClass());
  // return A.class.isInstance(b);
  // return b instanceof A;
}

// Warmup the code
for (int i = 0; i < 100; ++i)
  execute();

// Time it
int count = 100000;
final long start = System.nanoTime();
for(int i=0; i<count; i++){
   execute();
}
final long elapsed = System.nanoTime() - start;

Thanks to the JIT, the code is optimized at some point and we get:

  • instanceof: 6ms
  • isInstance: 12ms
  • isAssignableFrom : 15ms

Note

Originally this post was doing its own benchmark using a for loop in raw JAVA, which gave unreliable results as some optimization like Just In Time can eliminate the loop. So it was mostly measuring how long did the JIT compiler take to optimize the loop: see Performance test independent of the number of iterations for more details

Related questions

Fatal error: Call to a member function bind_param() on boolean

You should always try as much as possible to always put your statements in a try catch block ... it will always help in situations like this and will let you know whats wrong. Perhaps the table name or column name is wrong.

How do I improve ASP.NET MVC application performance?

In addition to all the great information on optimising your application on the server side I'd say you should take a look at YSlow. It's a superb resource for improving site performance on the client side.

This applies to all sites, not just ASP.NET MVC.

Multi-character constant warnings

Simplest C/C++ any compiler/standard compliant solution, was mentioned by @leftaroundabout in comments above:

int x = *(int*)"abcd";

Or a bit more specific:

int x = *(int32_t*)"abcd";

One more solution, also compliant with C/C++ compiler/standard since C99 (except clang++, which has a known bug):

int x = ((union {char s[5]; int number;}){"abcd"}).number;

/* just a demo check: */
printf("x=%d stored %s byte first\n", x, x==0x61626364 ? "MSB":"LSB");

Here anonymous union is used to give a nice symbol-name to the desired numeric result, "abcd" string is used to initialize the lvalue of compound literal (C99).

Sending Windows key using SendKeys

Alt+F4 is working only in brackets

SendKeys.SendWait("(%{F4})");

DateDiff to output hours and minutes

Try this query

select
    *,
    Days          = datediff(dd,0,DateDif),
    Hours         = datepart(hour,DateDif),
    Minutes       = datepart(minute,DateDif),
    Seconds       = datepart(second,DateDif),
    MS            = datepart(ms,DateDif)
from
    (select
         DateDif = EndDate-StartDate,
         aa.*
     from
         (  -- Test Data
          Select
              StartDate = convert(datetime,'20090213 02:44:37.923'),
              EndDate   = convert(datetime,'20090715 13:24:45.837')) aa
    ) a

Output

DateDif                  StartDate                EndDate                 Days Hours Minutes Seconds MS
-----------------------  -----------------------  ----------------------- ---- ----- ------- ------- ---
1900-06-02 10:40:07.913  2009-02-13 02:44:37.923  2009-07-15 13:24:45.837 152  10    40      7       913

(1 row(s) affected)

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

If the id column has no default value, but has NOT NULL constraint, then you have to provide a value yourself

INSERT INTO dbo.role (id, name, created) VALUES ('something', 'Content Coordinator', GETDATE()), ('Content Viewer', GETDATE())

How do I limit the number of returned items?

I am a bit lazy, so I like simple things:

let users = await Users.find({}, null, {limit: 50});

Disable password authentication for SSH

The one-liner to disable SSH password authentication:

sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart

Java program to get the current date without timestamp

The accepted answer by Jesper is correct but now outdated. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them.

java.time

Instead use the java.time framework, built into Java 8 and later, back-ported to Java 6 & 7 and further adapted to Android.

Table of all date-time types in Java, both modern and legacy.png

If you truly do not care about time-of-day and time zones, use LocalDate in the java.time framework ().

LocalDate localDate = LocalDate.of( 2014 , 5 , 6 );

Today

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If you want to use the JVM’s current default time zone, make your intention clear by calling ZoneId.systemDefault(). If critical, confirm the zone with your user.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.
LocalDate today = LocalDate.now( z ) ;

Moment

If you care about specific moments, specific points on the timeline, do not use LocalDate. If you care about the date as seen through the wall-clock time used by the people of a certain region, do not use LocalDate.

Be aware that if you have any chance of needing to deal with other time zones or UTC, this is the wrong way to go. Naïve programmers tend to think they do not need time zones when in fact they do.

Strings

Call toString to generate a string in standard ISO 8601 format.

String output = localDate.toString();

2014-05-06

For other formats, search Stack Overflow for DateTimeFormatter class.

Joda-Time

Though now supplanted by java.time, you can use the similar LocalDate class in the Joda-Time library (the inspiration for java.time).

LocalDate localDate = new LocalDate( 2014, 5, 6 );

How do I make a <div> move up and down when I'm scrolling the page?

Just for a more animated and cute solution:

$(window).scroll(function(){
  $("#div").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});

And a pen for those who want to see: http://codepen.io/think123/full/mAxlb, and fork: http://codepen.io/think123/pen/mAxlb

Update: and a non-animated jQuery solution:

$(window).scroll(function(){
  $("#div").css({"margin-top": ($(window).scrollTop()) + "px", "margin-left":($(window).scrollLeft()) + "px"});
});

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

Using Lambda:

    new AlertDialog.Builder(this).setMessage(getString(R.string.exit_msg))
        .setTitle(getString(R.string.info))
        .setPositiveButton(getString(R.string.yes), (arg0, arg1) -> {
            moveTaskToBack(true);
            finish();
        })
        .setNegativeButton(getString(R.string.no), (arg0, arg1) -> {
        })
        .show();

You also need to set level language to support java 8 in your gradle.build:

compileOptions {
       targetCompatibility 1.8
       sourceCompatibility 1.8
}

Multiple Image Upload PHP form with one input

$total = count($_FILES['txt_gallery']['name']);
            $filename_arr = [];
            $filename_arr1 = [];
            for( $i=0 ; $i < $total ; $i++ ) {
              $tmpFilePath = $_FILES['txt_gallery']['tmp_name'][$i];
              if ($tmpFilePath != ""){
                $newFilePath = "../uploaded/" .date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                $newFilePath1 = date('Ymdhis').$i.$_FILES['txt_gallery']['name'][$i];
                if(move_uploaded_file($tmpFilePath, $newFilePath)) {
                  $filename_arr[] = $newFilePath;
                  $filename_arr1[] = $newFilePath1;

                }
              }
            }
            $file_names = implode(',', $filename_arr1);
            var_dump($file_names); exit;

How do I fix 'ImportError: cannot import name IncompleteRead'?

While this previous answer might be the reason, this snipped worked for me as a solution (in Ubuntu 14.04):

First remove the package from the package manager:

# apt-get remove python-pip

And then install the latest version by side:

# easy_install pip

(thanks to @Aufziehvogel, @JunchaoGu)

MongoDB - admin user not authorized

You can try: Using the --authenticationDatabase flag helps.

mongo --port 27017 -u "admin" -p "password" --authenticationDatabase "admin"

regular expression for anything but an empty string

You can do one of two things:

  • match against ^\s*$; a match means the string is "empty"
    • ^, $ are the beginning and end of string anchors respectively
    • \s is a whitespace character
    • * is zero-or-more repetition of
  • find a \S; an occurrence means the string is NOT "empty"
    • \S is the negated version of \s (note the case difference)
    • \S therefore matches any non-whitespace character

References

Related questions

Saving results with headers in Sql Server Management Studio

At least in SQL Server 2012, you can right click in the query window and select Query Options. From there you can select Include Headers for grid and/or text and have the Save As work the way you want it without restarting SSMS.

You'll still need to change it in Tools->Options in the menu bar to have new query windows use those settings by default.

Convert time span value to format "hh:mm Am/Pm" using C#

You can add the TimeSpan to a DateTime, for example:

TimeSpan span = TimeSpan.FromHours(16);
DateTime time = DateTime.Today + span;
String result = time.ToString("hh:mm tt");

Demo: http://ideone.com/veJ6tT

04:00 PM

Standard Date and Time Format Strings

How to rotate x-axis tick labels in Pandas barplot

Pass param rot=0 to rotate the xticks:

import matplotlib
matplotlib.style.use('ggplot')
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ 'celltype':["foo","bar","qux","woz"], 's1':[5,9,1,7], 's2':[12,90,13,87]})
df = df[["celltype","s1","s2"]]
df.set_index(["celltype"],inplace=True)
df.plot(kind='bar',alpha=0.75, rot=0)
plt.xlabel("")
plt.show()

yields plot:

enter image description here

Age from birthdate in python

import datetime

def age(date_of_birth):
    if date_of_birth > datetime.date.today().replace(year = date_of_birth.year):
        return datetime.date.today().year - date_of_birth.year - 1
    else:
        return datetime.date.today().year - date_of_birth.year

In your case:

import datetime

# your model
def age(self):
    if self.birthdate > datetime.date.today().replace(year = self.birthdate.year):
        return datetime.date.today().year - self.birthdate.year - 1
    else:
        return datetime.date.today().year - self.birthdate.year

What is the reason for a red exclamation mark next to my project in Eclipse?

In my case this is incorrect/improper dependency

Markers > Problems is highlighting spring/.gradle/cache/httpcomponents.......pom is not valid archive

I removed

compile group: 'org.apache.httpcomponents', name: 'httpcomponents-client', version: '4.5.6', ext: 'pom'

changed to

compile group: 'org.apache.httpcomponents', name: 'httpclient', version: '4.5.6'