Programs & Examples On #Jsr170

JSR 170 specifies a standard API to access content repositories in Java. The detailed description is here: http://jcp.org/en/jsr/detail?id=170

Background color of text in SVG

The solution I have used is:

_x000D_
_x000D_
<svg>
  <line x1="100" y1="100" x2="500" y2="100" style="stroke:black; stroke-width: 2"/>    
  <text x="150" y="105" style="stroke:white; stroke-width:0.6em">Hello World!</text>
  <text x="150" y="105" style="fill:black">Hello World!</text>  
</svg>
_x000D_
_x000D_
_x000D_

A duplicate text item is being placed, with stroke and stroke-width attributes. The stroke should match the background colour, and the stroke-width should be just big enough to create a "splodge" on which to write the actual text.

A bit of a hack and there are potential issues, but works for me!

Convert True/False value read from file to boolean

If your data is from json, you can do that

import json

json.loads('true')

True

How can I add a key/value pair to a JavaScript object?

Best way to achieve same is stated below:

function getKey(key) {
  return `${key}`;
}

var obj = {key1: "value1", key2: "value2", [getKey('key3')]: "value3"};

//console.log(obj);

How to get screen dimensions as pixels in Android

I have tried all possible "solutions" unsuccessfully and I noticed that Elliott Hughes' "Dalvik Explorer" app always shows correct dimension on any Android device/OS version. I ended up looking at his open source project that can be found here: https://code.google.com/p/enh/

Here's all the relevant code:

WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
try {
    // used when 17 > SDK_INT >= 14; includes window decorations (statusbar bar/menu bar)
    widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
    heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
try {
    // used when SDK_INT >= 17; includes window decorations (statusbar bar/menu bar)
    Point realSize = new Point();
    Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
    widthPixels = realSize.x;
    heightPixels = realSize.y;
} catch (Exception ignored) {
}

EDIT: slightly improved version (avoid firing exceptions on non-supported OS version):

WindowManager w = activity.getWindowManager();
Display d = w.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
d.getMetrics(metrics);
// since SDK_INT = 1;
widthPixels = metrics.widthPixels;
heightPixels = metrics.heightPixels;
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 14 && Build.VERSION.SDK_INT < 17)
try {
    widthPixels = (Integer) Display.class.getMethod("getRawWidth").invoke(d);
    heightPixels = (Integer) Display.class.getMethod("getRawHeight").invoke(d);
} catch (Exception ignored) {
}
// includes window decorations (statusbar bar/menu bar)
if (Build.VERSION.SDK_INT >= 17)
try {
    Point realSize = new Point();
    Display.class.getMethod("getRealSize", Point.class).invoke(d, realSize);
    widthPixels = realSize.x;
    heightPixels = realSize.y;
} catch (Exception ignored) {
}

ASP.NET MVC ActionLink and post method

Calling $.post() won't work as it is Ajax based. So a hybrid method needs to be used for this purpose.

Following is the solution which is working for me.

Steps: 1. Create URL for href which calls the a method with url and parameter 2. Call normal POST using JavaScript method

Solution:

In .cshtml:

<a href="javascript:(function(){$.postGo( '@Url.Action("View")', { 'id': @receipt.ReceiptId  } );})()">View</a>

Note: the anonymous method should be wrapped in (....)() i.e.

(function() {
    //code...
})();

postGo is defined as below in JavaScript. Rest are simple..

@Url.Action("View") creates url for the call

{ 'id': @receipt.ReceiptId } creates parameters as object which is in-turn converted to POST fields in postGo method. This can be any parameter as you require

In JavaScript:

(function ($) {
    $.extend({
        getGo: function (url, params) {
            document.location = url + '?' + $.param(params);
        },
        postGo: function (url, params) {
            var $form = $("<form>")
                .attr("method", "post")
                .attr("action", url);
            $.each(params, function (name, value) {
                $("<input type='hidden'>")
                    .attr("name", name)
                    .attr("value", value)
                    .appendTo($form);
            });
            $form.appendTo("body");
            $form.submit();
        }
    });
})(jQuery);

Reference URLs which I have used for postGo

Non-ajax GET/POST using jQuery (plugin?)

http://nuonical.com/jquery-postgo-plugin/

newline character in c# string

A great way of handling this is with regular expressions.

string modifiedString = Regex.Replace(originalString, @"(\r\n)|\n|\r", "<br/>");


This will replace any of the 3 legal types of newline with the html tag.

Copy row but with new id

Let us say your table has following fields:

( pk_id int not null auto_increment primary key,
  col1 int,
  col2 varchar(10)
)

then, to copy values from one row to the other row with new key value, following query may help

insert into my_table( col1, col2 ) select col1, col2 from my_table where pk_id=?;

This will generate a new value for pk_id field and copy values from col1, and col2 of the selected row.

You can extend this sample to apply for more fields in the table.

UPDATE:
In due respect to the comments from JohnP and Martin -

We can use temporary table to buffer first from main table and use it to copy to main table again. Mere update of pk reference field in temp table will not help as it might already be present in the main table. Instead we can drop the pk field from the temp table and copy all other to the main table.

With reference to the answer by Tim Ruehsen in the referred posting:

CREATE TEMPORARY TABLE tmp SELECT * from my_table WHERE ...;
ALTER TABLE tmp drop pk_id; # drop autoincrement field
# UPDATE tmp SET ...; # just needed to change other unique keys
INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
DROP TEMPORARY TABLE tmp;

Hope this helps.

How to Rotate a UIImage 90 degrees?

Here is a Swift extension to UIImage that rotates the image by any arbitrary angle. Use it like this: let rotatedImage = image.rotated(byDegrees: degree). I used the Objective-C code in one of the other answers and removed a few lines that we incorrect (rotated box stuff) and turned it into an extension for UIImage.

extension UIImage {

func rotate(byDegrees degree: Double) -> UIImage {
    let radians = CGFloat(degree*M_PI)/180.0 as CGFloat
    let rotatedSize = self.size
    let scale = UIScreen.mainScreen().scale
    UIGraphicsBeginImageContextWithOptions(rotatedSize, false, scale)
    let bitmap = UIGraphicsGetCurrentContext()
    CGContextTranslateCTM(bitmap, rotatedSize.width / 2, rotatedSize.height / 2);
    CGContextRotateCTM(bitmap, radians);
    CGContextScaleCTM(bitmap, 1.0, -1.0);
    CGContextDrawImage(bitmap, CGRectMake(-self.size.width / 2, -self.size.height / 2 , self.size.width, self.size.height), self.CGImage );
    let newImage = UIGraphicsGetImageFromCurrentImageContext()

    return newImage
}
}

Can't bind to 'ngIf' since it isn't a known property of 'div'

If you are using RC5 then import this:

import { CommonModule } from '@angular/common';  
import { BrowserModule } from '@angular/platform-browser';

and be sure to import CommonModule from the module that is providing your component.

 @NgModule({
    imports: [CommonModule],
    declarations: [MyComponent]
  ...
})
class MyComponentModule {}

How can I update the current line in a C# Windows Console App?

The SetCursorPosition method works in multi-threading scenario, where the other two methods don't

Exporting the values in List to excel

Fast way - ArrayToExcel (github)

byte[] excel = myList.ToExcel();
File.WriteAllBytes("result.xlsx", excel);

How to find out if an item is present in a std::vector?

Use the STL find function.

Keep in mind that there is also a find_if function, which you can use if your search is more complex, i.e. if you're not just looking for an element, but, for example, want see if there is an element that fulfills a certain condition, for example, a string that starts with "abc". (find_if would give you an iterator that points to the first such element).

How to find the path of Flutter SDK

All you need to do is to find a folder called "flutter" (lowecase), which is located inside a folder called "Flutter" (uppercase), select it, and browse it.

In my case it is located at:

C:\Users\Administrator\Flutter\flutter_windows_v1.12.13+hotfix.5-stable\flutter

enter image description here

Also make sure that your Flutter and Dart are of the latest version. If they are not, upgrade them and re-start the IDE.

Renaming branches remotely in Git

If you really just want to rename branches remotely, without renaming any local branches at the same time, you can do this with a single command:

git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

I wrote this script (git-rename-remote-branch) which provides a handy shortcut to do the above easily.

As a bash function:

git-rename-remote-branch(){
  if [ $# -ne 3 ]; then
    echo "Rationale : Rename a branch on the server without checking it out."
    echo "Usage     : ${FUNCNAME[0]} <remote> <old name> <new name>"
    echo "Example   : ${FUNCNAME[0]} origin master release"
    return 1 
  fi

  git push $1 $1/$2\:refs/heads/$3 :$2
}

To integrate @ksrb's comment: What this basically does is two pushes in a single command, first git push <remote> <remote>/<old_name>:refs/heads/<new_name> to push a new remote branch based on the old remote tracking branch and then git push <remote> :<old_name> to delete the old remote branch.

Load image from url

Based on this answer i write my own loader.

With Loading effect and Appear effect :

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;

import java.io.InputStream;

/**
 * Created by Sergey Shustikov ([email protected]) at 2015.
 */
public class DownloadImageTask extends AsyncTask<String, Void, Bitmap>
{
    public static final int ANIMATION_DURATION = 250;
    private final ImageView mDestination, mFakeForError;
    private final String mUrl;
    private final ProgressBar mProgressBar;
    private Animation.AnimationListener mOutAnimationListener = new Animation.AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation)
        {

        }

        @Override
        public void onAnimationEnd(Animation animation)
        {
            mProgressBar.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationRepeat(Animation animation)
        {

        }
    };
    private Animation.AnimationListener mInAnimationListener = new Animation.AnimationListener()
    {
        @Override
        public void onAnimationStart(Animation animation)
        {
            if (isBitmapSet)
                mDestination.setVisibility(View.VISIBLE);
            else
                mFakeForError.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animation animation)
        {

        }

        @Override
        public void onAnimationRepeat(Animation animation)
        {

        }
    };
    private boolean isBitmapSet;

    public DownloadImageTask(Context context, ImageView destination, String url)
    {
        mDestination = destination;
        mUrl = url;
        ViewGroup parent = (ViewGroup) destination.getParent();
        mFakeForError = new ImageView(context);
        destination.setVisibility(View.GONE);
        FrameLayout layout = new FrameLayout(context);
        mProgressBar = new ProgressBar(context);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        params.gravity = Gravity.CENTER;
        mProgressBar.setLayoutParams(params);
        FrameLayout.LayoutParams copy = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        copy.gravity = Gravity.CENTER;
        copy.width = dpToPx(48);
        copy.height = dpToPx(48);
        mFakeForError.setLayoutParams(copy);
        mFakeForError.setVisibility(View.GONE);
        mFakeForError.setImageResource(android.R.drawable.ic_menu_close_clear_cancel);
        layout.addView(mProgressBar);
        layout.addView(mFakeForError);
        mProgressBar.setIndeterminate(true);
        parent.addView(layout, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
    }

    protected Bitmap doInBackground(String... urls)
    {
        String urlDisplay = mUrl;
        Bitmap bitmap = null;
        try {
            InputStream in = new java.net.URL(urlDisplay).openStream();
            bitmap = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return bitmap;
    }

    protected void onPostExecute(Bitmap result)
    {
        AlphaAnimation in = new AlphaAnimation(0f, 1f);
        AlphaAnimation out = new AlphaAnimation(1f, 0f);
        in.setDuration(ANIMATION_DURATION * 2);
        out.setDuration(ANIMATION_DURATION);
        out.setAnimationListener(mOutAnimationListener);
        in.setAnimationListener(mInAnimationListener);
        in.setStartOffset(ANIMATION_DURATION);
        if (result != null) {
            mDestination.setImageBitmap(result);
            isBitmapSet = true;
            mDestination.startAnimation(in);
        } else {
            mFakeForError.startAnimation(in);
        }
        mProgressBar.startAnimation(out);
    }
    public int dpToPx(int dp) {
        DisplayMetrics displayMetrics = mDestination.getContext().getResources().getDisplayMetrics();
        int px = Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
        return px;
    }
}

Add permission

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

And execute :

 new DownloadImageTask(context, imageViewToLoad, urlToImage).execute();

Access key value from Web.config in Razor View-MVC3 ASP.NET

@System.Configuration.ConfigurationManager.AppSettings["myKey"]

Get current URL from IFRAME

For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:

document.getElementById("iframe_id").contentWindow.location.href

If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.

See also answers to a similar question.

Setting a WebRequest's body data

With HttpWebRequest.GetRequestStream

Code example from http://msdn.microsoft.com/en-us/library/d4cek6cc.aspx

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

From one of my own code:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}

Determine if two rectangles overlap each other?

struct rect
{
    int x;
    int y;
    int width;
    int height;
};

bool valueInRange(int value, int min, int max)
{ return (value >= min) && (value <= max); }

bool rectOverlap(rect A, rect B)
{
    bool xOverlap = valueInRange(A.x, B.x, B.x + B.width) ||
                    valueInRange(B.x, A.x, A.x + A.width);

    bool yOverlap = valueInRange(A.y, B.y, B.y + B.height) ||
                    valueInRange(B.y, A.y, A.y + A.height);

    return xOverlap && yOverlap;
}

Can you require two form fields to match with HTML5?

As has been mentioned in other answers, there is no pure HTML5 way to do this.

If you are already using JQuery, then this should do what you need:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#ourForm').submit(function(e){_x000D_
      var form = this;_x000D_
      e.preventDefault();_x000D_
      // Check Passwords are the same_x000D_
      if( $('#pass1').val()==$('#pass2').val() ) {_x000D_
          // Submit Form_x000D_
          alert('Passwords Match, submitting form');_x000D_
          form.submit();_x000D_
      } else {_x000D_
          // Complain bitterly_x000D_
          alert('Password Mismatch');_x000D_
          return false;_x000D_
      }_x000D_
  });_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form id="ourForm">_x000D_
    <input type="password" name="password" id="pass1" placeholder="Password" required>_x000D_
    <input type="password" name="password" id="pass2" placeholder="Repeat Password" required>_x000D_
    <input type="submit" value="Go">_x000D_
</form>
_x000D_
_x000D_
_x000D_

How do you see the entire command history in interactive Python?

Rehash of Doogle's answer that doesn't printline numbers, but does allow specifying the number of lines to print.

def history(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(readline.get_history_item(r))
    else:
        for r in range(1, -lastn + 1):
            print(readline.get_history_item(r))

jQuery attr() change img src

  1. Function imageMorph will create a new img element therefore the id is removed. Changed to

    $("#wrapper > img")

  2. You should use live() function for click event if you want you rocket lanch again.

Updated demo: http://jsfiddle.net/ynhat/QQRsW/4/

Capturing standard out and error with Start-Process

Here's a kludgy way to get the output from another powershell process:

start-process -wait -nonewwindow powershell 'ps | Export-Clixml out.xml'; import-clixml out.xml

Load vs. Stress testing

-> Testing the app with maximum number of user and input is defined as load testing. While testing the app with more than maximum number of user and input is defined as stress testing.

->In Load testing we measure the system performance based on a volume of users. While in Stress testing we measure the breakpoint of a system.

->Load Testing is testing the application for a given load requirements which may include any of the following criteria:

 .Total number of users.

 .Response Time

 .Through Put

Some parameters to check State of servers/application.

-> While stress testing is testing the application for unexpected load. It includes

 .Vusers

 .Think-Time

Example:

If an app is build for 500 users, then for load testing we check up to 500 users and for stress testing we check greater than 500.

How to include Authorization header in cURL POST HTTP Request in PHP?

You have most of the code…

CURLOPT_HTTPHEADER for curl_setopt() takes an array with each header as an element. You have one element with multiple headers.

You also need to add the Authorization header to your $header array.

$header = array();
$header[] = 'Content-length: 0';
$header[] = 'Content-type: application/json';
$header[] = 'Authorization: OAuth SomeHugeOAuthaccess_tokenThatIReceivedAsAString';

What's a concise way to check that environment variables are set in a Unix shell script?

None of the above solutions worked for my purposes, in part because I checking the environment for an open-ended list of variables that need to be set before starting a lengthy process. I ended up with this:

mapfile -t arr < variables.txt

EXITCODE=0

for i in "${arr[@]}"
do
   ISSET=$(env | grep ^${i}= | wc -l)
   if [ "${ISSET}" = "0" ];
   then
      EXITCODE=-1
      echo "ENV variable $i is required."
   fi
done

exit ${EXITCODE}

"git checkout <commit id>" is changing branch to "no branch"

If you checkout a commit sha directly, it puts you into a "detached head" state, which basically just means that the current sha that your working copy has checked out, doesn't have a branch pointing at it.

If you haven't made any commits yet, you can leave detached head state by simply checking out whichever branch you were on before checking out the commit sha:

git checkout <branch>

If you did make commits while you were in the detached head state, you can save your work by simply attaching a branch before or while you leave detached head state:

# Checkout a new branch at current detached head state:
git checkout -b newBranch

You can read more about detached head state at the official Linux Kernel Git docs for checkout.

Plotting a list of (x, y) coordinates in python matplotlib

If you want to plot a single line connecting all the points in the list

plt.plot(li[:])

plt.show()

This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.

Merge two HTML table cells

Set the colspan attribute to 2.

...but please don't use tables for layout.

z-index issue with twitter bootstrap dropdown menu

This fixed it for me:

.navbar-wrapper {
  z-index: 11;
}

NullInjectorError: No provider for AngularFirestore

import angularFirebaseStore 

in app.module.ts and set it as a provider like service

How to disable spring security for particular url

I have a better way:

http
    .authorizeRequests()
    .antMatchers("/api/v1/signup/**").permitAll()
    .anyRequest().authenticated()

Using Notepad++ to validate XML against an XSD

  1. In Notepad++ go to Plugins > Plugin manager > Show Plugin Manager then find Xml Tools plugin. Tick the box and click Install

    enter image description here

  2. Open XML document you want to validate and click Ctrl+Shift+Alt+M (Or use Menu if this is your preference Plugins > XML Tools > Validate Now).
    Following dialog will open: enter image description here

  3. Click on .... Point to XSD file and I am pretty sure you'll be able to handle things from here.

Hope this saves you some time.

EDIT: Plugin manager was not included in some versions of Notepad++ because many users didn't like commercials that it used to show. If you want to keep an older version, however still want plugin manager, you can get it on github, and install it by extracting the archive and copying contents to plugins and updates folder.
In version 7.7.1 plugin manager is back under a different guise... Plugin Admin so now you can simply update notepad++ and have it back.

enter image description here

How to easily import multiple sql files into a MySQL database?

You could also a for loop to do so:

#!/bin/bash
for i in *.sql
do
    echo "Importing: $i"
    mysql your_db_name < $i
    wait
done 

Source

XML Carriage return encoding

xml:space="preserve" has to work for all compliant XML parsers.

However, note that in HTML the line break is just whitespace and NOT a line break (this is represented with the <br /> (X)HTML tag, maybe this is the problem which you are facing.

You can also add &#10; and/or &#13; to insert CR/LF characters.

Inject service in app.config

A solution very easy to do it

Note : it's only for an asynchrone call, because service isn't initialized on config execution.

You can use run() method. Example :

  1. Your service is called "MyService"
  2. You want to use it for an asynchrone execution on a provider "MyProvider"

Your code :

(function () { //To isolate code TO NEVER HAVE A GLOBAL VARIABLE!

    //Store your service into an internal variable
    //It's an internal variable because you have wrapped this code with a (function () { --- })();
    var theServiceToInject = null;

    //Declare your application
    var myApp = angular.module("MyApplication", []);

    //Set configuration
    myApp.config(['MyProvider', function (MyProvider) {
        MyProvider.callMyMethod(function () {
            theServiceToInject.methodOnService();
        });
    }]);

    //When application is initialized inject your service
    myApp.run(['MyService', function (MyService) {
        theServiceToInject = MyService;
    }]);
});

Multiple Buttons' OnClickListener() android

No need of if else's or switch, Let's start: In your every Button or whatever it is (I am using ImageView), Add this attribute android:onClick="DoSomeThing"

In your Activity:

public void DoSomeThing(View v){
    ImageView img1= (ImageView) v; //you have to cast the view i.e. if it's button, it must be cast to Button like below line

    Button b1= (Button) v;

    img1.setImageBitmap(imageBitmap); //or anything you want to do with your view, This will work for all

    b1.setText("Some Text");
 

}

Split string into list in jinja?

After coming back to my own question after 5 year and seeing so many people found this useful, a little update.

A string variable can be split into a list by using the split function (it can contain similar values, set is for the assignment) . I haven't found this function in the official documentation but it works similar to normal Python. The items can be called via an index, used in a loop or like Dave suggested if you know the values, it can set variables like a tuple.

{% set list1 = variable1.split(';') %}
The grass is {{ list1[0] }} and the boat is {{ list1[1] }}

or

{% set list1 = variable1.split(';') %}
{% for item in list1 %}
    <p>{{ item }}<p/>
{% endfor %} 

or

{% set item1, item2 = variable1.split(';') %}
The grass is {{ item1 }} and the boat is {{ item2 }}

How many characters can a Java String have?

Java9 uses byte[] to store String.value, so you can only get about 1GB Strings in Java9. Java8 on the other hand can have 2GB Strings.

By character I mean "char"s, some character is not representable in BMP(like some of the emojis), so it will take more(currently 2) chars.

How to get raw text from pdf file using java

Hi we can extract the pdf files using Apache Tika

The Example is :

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.metadata.TikaCoreProperties;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.sax.BodyContentHandler;

public class WebPagePdfExtractor {

    public Map<String, Object> processRecord(String url) {
        DefaultHttpClient httpclient = new DefaultHttpClient();
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            HttpGet httpGet = new HttpGet(url);
            HttpResponse response = httpclient.execute(httpGet);
            HttpEntity entity = response.getEntity();
            InputStream input = null;
            if (entity != null) {
                try {
                    input = entity.getContent();
                    BodyContentHandler handler = new BodyContentHandler();
                    Metadata metadata = new Metadata();
                    AutoDetectParser parser = new AutoDetectParser();
                    ParseContext parseContext = new ParseContext();
                    parser.parse(input, handler, metadata, parseContext);
                    map.put("text", handler.toString().replaceAll("\n|\r|\t", " "));
                    map.put("title", metadata.get(TikaCoreProperties.TITLE));
                    map.put("pageCount", metadata.get("xmpTPg:NPages"));
                    map.put("status_code", response.getStatusLine().getStatusCode() + "");
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (input != null) {
                        try {
                            input.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return map;
    }

    public static void main(String arg[]) {
        WebPagePdfExtractor webPagePdfExtractor = new WebPagePdfExtractor();
        Map<String, Object> extractedMap = webPagePdfExtractor.processRecord("http://math.about.com/library/q20.pdf");
        System.out.println(extractedMap.get("text"));
    }

}

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Same Problem I had... I was writing all the script in a seperate file and was adding it through tag into the end of the HTML file after body tag. After moving the the tag inside the body tag it works fine. before :

</body>
<script>require('../script/viewLog.js')</script>

after :

<script>require('../script/viewLog.js')</script>
</body>

Finding the layers and layer sizes for each Docker image

In my opinion, docker history <image> is sufficient. This returns the size of each layer:

$ docker history jenkinsci-jnlp-slave:2019-1-9c
IMAGE        CREATED    CREATED BY                                    SIZE  COMMENT
93f48953d298 42 min ago /bin/sh -c #(nop)  USER jenkins               0B
6305b07d4650 42 min ago /bin/sh -c chown jenkins:jenkins -R /home/je… 1.45GB

Callback function for JSONP with jQuery AJAX

delete this line:

jsonp: 'jsonp_callback',

Or replace this line:

url: 'http://url.of.my.server/submit?callback=json_callback',

because currently you are asking jQuery to create a random callback function name with callback=? and then telling jQuery that you want to use jsonp_callback instead.

Convert java.util.Date to java.time.LocalDate

You can convert in one line :

public static LocalDate getLocalDateFromDate(Date date){
   return LocalDate.from(Instant.ofEpochMilli(date.getTime()).atZone(ZoneId.systemDefault()));
}

accessing a docker container from another container

You will have to access db through the ip of host machine, or if you want to access it via localhost:1521, then run webserver like -

docker run --net=host --name oracle-wls wls-image:latest

See here

Entity Framework Join 3 Tables

I think it will be easier using syntax-based query:

var entryPoint = (from ep in dbContext.tbl_EntryPoint
                 join e in dbContext.tbl_Entry on ep.EID equals e.EID
                 join t in dbContext.tbl_Title on e.TID equals t.TID
                 where e.OwnerID == user.UID
                 select new {
                     UID = e.OwnerID,
                     TID = e.TID,
                     Title = t.Title,
                     EID = e.EID
                 }).Take(10);

And you should probably add orderby clause, to make sure Top(10) returns correct top ten items.

How can I generate UUID in C#

Here is a client side "sequential guid" solution.

http://www.pinvoke.net/default.aspx/rpcrt4.uuidcreate

using System;
using System.Runtime.InteropServices;


namespace MyCompany.MyTechnology.Framework.CrossDomain.GuidExtend
{
    public static class Guid
    {

        /*

        Original Reference for Code:
        http://www.pinvoke.net/default.aspx/rpcrt4/UuidCreateSequential.html

        */


        [DllImport("rpcrt4.dll", SetLastError = true)]
        static extern int UuidCreateSequential(out System.Guid guid);

        public static System.Guid NewGuid()
        {
            return CreateSequentialUuid();
        }


        public static System.Guid CreateSequentialUuid()
        {
            const int RPC_S_OK = 0;
            System.Guid g;
            int hr = UuidCreateSequential(out g);
            if (hr != RPC_S_OK)
                throw new ApplicationException("UuidCreateSequential failed: " + hr);
            return g;
        }


        /*

        Text From URL above:

        UuidCreateSequential (rpcrt4)

        Type a page name and press Enter. You'll jump to the page if it exists, or you can create it if it doesn't.
        To create a page in a module other than rpcrt4, prefix the name with the module name and a period.
        . Summary
        Creates a new UUID 
        C# Signature:
        [DllImport("rpcrt4.dll", SetLastError=true)]
        static extern int UuidCreateSequential(out Guid guid);


        VB Signature:
        Declare Function UuidCreateSequential Lib "rpcrt4.dll" (ByRef id As Guid) As Integer


        User-Defined Types:
        None.

        Notes:
        Microsoft changed the UuidCreate function so it no longer uses the machine's MAC address as part of the UUID. Since CoCreateGuid calls UuidCreate to get its GUID, its output also changed. If you still like the GUIDs to be generated in sequential order (helpful for keeping a related group of GUIDs together in the system registry), you can use the UuidCreateSequential function.

        CoCreateGuid generates random-looking GUIDs like these:

        92E60A8A-2A99-4F53-9A71-AC69BD7E4D75
        BB88FD63-DAC2-4B15-8ADF-1D502E64B92F
        28F8800C-C804-4F0F-B6F1-24BFC4D4EE80
        EBD133A6-6CF3-4ADA-B723-A8177B70D268
        B10A35C0-F012-4EC1-9D24-3CC91D2B7122



        UuidCreateSequential generates sequential GUIDs like these:

        19F287B4-8830-11D9-8BFC-000CF1ADC5B7
        19F287B5-8830-11D9-8BFC-000CF1ADC5B7
        19F287B6-8830-11D9-8BFC-000CF1ADC5B7
        19F287B7-8830-11D9-8BFC-000CF1ADC5B7
        19F287B8-8830-11D9-8BFC-000CF1ADC5B7



        Here is a summary of the differences in the output of UuidCreateSequential:

        The last six bytes reveal your MAC address 
        Several GUIDs generated in a row are sequential 
        Tips & Tricks:
        Please add some!

        Sample Code in C#:
        static Guid UuidCreateSequential()
        {
           const int RPC_S_OK = 0;
           Guid g;
           int hr = UuidCreateSequential(out g);
           if (hr != RPC_S_OK)
             throw new ApplicationException
               ("UuidCreateSequential failed: " + hr);
           return g;
        }



        Sample Code in VB:
        Sub Main()
           Dim myId As Guid
           Dim code As Integer
           code = UuidCreateSequential(myId)
           If code <> 0 Then
             Console.WriteLine("UuidCreateSequential failed: {0}", code)
           Else
             Console.WriteLine(myId)
           End If
        End Sub




        */








    }
}

Keywords: CreateSequentialUUID SequentialUUID

How to get the parent dir location

A simple way can be:

import os
current_dir =  os.path.abspath(os.path.dirname(__file__))
parent_dir = os.path.abspath(current_dir + "/../")
print parent_dir

Doing a join across two databases with different collations on SQL Server and getting an error

A general purpose way is to coerce the collation to DATABASE_DEFAULT. This removes hardcoding the collation name which could change.

It's also useful for temp table and table variables, and where you may not know the server collation (eg you are a vendor placing your system on the customer's server)

select
    sone_field collate DATABASE_DEFAULT
from
    table_1
    inner join
    table_2 on table_1.field collate DATABASE_DEFAULT = table_2.field
where whatever

Export database schema into SQL file

You can generate scripts to a file via SQL Server Management Studio, here are the steps:

  1. Right click the database you want to generate scripts for (not the table) and select tasks - generate scripts
  2. Next, select the requested table/tables, views, stored procedures, etc (from select specific database objects)
  3. Click advanced - select the types of data to script
  4. Click Next and finish

MSDN Generate Scripts

When generating the scripts, there is an area that will allow you to script, constraints, keys, etc. From SQL Server 2008 R2 there is an Advanced Option under scripting:

enter image description here

How to hide element label by element id in CSS?

This is worked for me.

#_account_id{
        display: none;
    }
    label[for="_account_id"] { display: none !important; }

How to use Bootstrap modal using the anchor tag for Register?

You will have to modify the below line:

<li><a href="#" data-toggle="modal" data-target="modalRegister">Register</a></li>

modalRegister is the ID and hence requires a preceding # for ID reference in html.

So, the modified html code snippet would be as follows:

<li><a href="#" data-toggle="modal" data-target="#modalRegister">Register</a></li>

How to calculate distance from Wifi router using Signal Strength?

FSPL depends on two parameters: First is the frequency of radio signals;Second is the wireless transmission distance. The following formula can reflect the relationship between them.

FSPL (dB) = 20log10(d) + 20log10(f) + K

d = distance
f = frequency
K= constant that depends on the units used for d and f
If d is measured in kilometers, f in MHz, the formula is:

FSPL (dB) = 20log10(d)+ 20log10(f) + 32.44

From the Fade Margin equation, Free Space Path Loss can be computed with the following equation.

Free Space Path Loss=Tx Power-Tx Cable Loss+Tx Antenna Gain+Rx Antenna Gain - Rx Cable Loss - Rx Sensitivity - Fade Margin

With the above two Free Space Path Loss equations, we can find out the Distance in km.

Distance (km) = 10(Free Space Path Loss – 32.44 – 20log10(f))/20

The Fresnel Zone is the area around the visual line-of-sight that radio waves spread out into after they leave the antenna. You want a clear line of sight to maintain strength, especially for 2.4GHz wireless systems. This is because 2.4GHz waves are absorbed by water, like the water found in trees. The rule of thumb is that 60% of Fresnel Zone must be clear of obstacles. Typically, 20% Fresnel Zone blockage introduces little signal loss to the link. Beyond 40% blockage the signal loss will become significant.

FSPLr=17.32*v(d/4f)

d = distance [km]
f = frequency [GHz]
r = radius [m]

Source : http://www.tp-link.com/en/support/calculator/

How to append one DataTable to another DataTable

Consider a solution that will neatly handle arbitrarily many tables.

//ASSUMPTION: All tables must have the same columns
var tables = new List<DataTable>();
tables.Add(oneTableToRuleThemAll);
tables.Add(oneTableToFindThem);
tables.Add(oneTableToBringThemAll);
tables.Add(andInTheDarknessBindThem);
//Or in the real world, you might be getting a collection of tables from some abstracted data source.

//behold, a table too great and terrible to imagine
var theOneTable = tables.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();

Encapsulated into a helper for future reuse:

public static DataTable CombineDataTables(params DataTable[] args)
{
    return args.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();
}

Just have a few tables declared in code?

var combined = CombineDataTables(dt1,dt2,dt3);

Want to combine into one of the existing tables instead of creating a new one?

dt1 = CombineDataTables(dt1,dt2,dt3);

Already have a collection of tables, instead of declared one by one?

//Pretend variable tables already exists
var tables = new[] { dt1, dt2, dt3 };
var combined = CombineDataTables(tables);

WebView link click open default browser

you can use Intent for this:

Intent browserIntent = new Intent("android.intent.action.VIEW", Uri.parse("your Url"));
startActivity(browserIntent);

How do DATETIME values work in SQLite?

For practically all date and time matters I prefer to simplify things, very, very simple... Down to seconds stored in integers.

Integers will always be supported as integers in databases, flat files, etc. You do a little math and cast it into another type and you can format the date anyway you want.

Doing it this way, you don't have to worry when [insert current favorite database here] is replaced with [future favorite database] which coincidentally didn't use the date format you chose today.

It's just a little math overhead (eg. methods--takes two seconds, I'll post a gist if necessary) and simplifies things for a lot of operations regarding date/time later.

OS X Framework Library not loaded: 'Image not found'

I ran into the same issue but the accepted solution did not work for me. Instead the solution was to modify the framework's install name.

The error in the original post is:

dyld: Library not loaded: /Library/Frameworks/TestMacFramework.framework/Versions/A/TestMacFramework
  Referenced from: /Users/samharman/Library/Developer/Xcode/DerivedData/TestMacContainer-dzabuelobzfknafuhmgooqhqrgzl/Build/Products/Debug/TestMacContainer.app/Contents/MacOS/TestMacContainer
  Reason: image not found

Note the first path after Library not loaded. The framework is being loaded from an absolute path. This path comes from the framework's install name (sometimes called rpath), which can be examined using:

otool -D MyFramework.framework/MyFramework

When a framework is embedded into an app this path should be relative and of this form: @rpath/MyFramework.framework/MyFramework. If your framework's install name is an absolute path it may not be loaded at runtime and an error similar to the one above will be produced.

The solution is to modify the install name:

install_name_tool -id "@rpath/MyFramework.framework/MyFramework" MyFramework.framework/MyFramework 

With this change I no longer get the error

Iterate through a C array

I think you should store the size somewhere.

The null-terminated-string kind of model for determining array length is a bad idea. For instance, getting the size of the array will be O(N) when it could very easily have been O(1) otherwise.

Having that said, a good solution might be glib's Arrays, they have the added advantage of expanding automatically if you need to add more items.

P.S. to be completely honest, I haven't used much of glib, but I think it's a (very) reputable library.

ORA-30926: unable to get a stable set of rows in the source tables

A further clarification to the use of DISTINCT to resolve error ORA-30926 in the general case:

You need to ensure that the set of data specified by the USING() clause has no duplicate values of the join columns, i.e. the columns in the ON() clause.

In OP's example where the USING clause only selects a key, it was sufficient to add DISTINCT to the USING clause. However, in the general case the USING clause may select a combination of key columns to match on and attribute columns to be used in the UPDATE ... SET clause. Therefore in the general case, adding DISTINCT to the USING clause will still allow different update rows for the same keys, in which case you will still get the ORA-30926 error.

This is an elaboration of DCookie's answer and point 3.1 in Tagar's answer, which from my experience may not be immediately obvious.

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.

What is Teredo Tunneling Pseudo-Interface?

Is to do with IPv6

All the gory details here: http://www.microsoft.com/technet/network/ipv6/teredo.mspx

Some people have had issues with it, and disabled it, but as a general rule, if it aint broke...

Compare if BigDecimal is greater than zero

This works too:

value > BigDecimal.ZERO

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

Ruby: Easiest Way to Filter Hash Keys?

As for bonus question:

  1. If you have output from #select method like this (list of 2-element arrays):

    [[:choice1, "Oh look, another one"], [:choice2, "Even more strings"], [:choice3, "But wait"]]
    

    then simply take this result and execute:

    filtered_params.join("\t")
    # or if you want only values instead of pairs key-value
    filtered_params.map(&:last).join("\t")
    
  2. If you have output from #delete_if method like this (hash):

    {:choice1=>"Oh look, another one", :choice2=>"Even more strings", :choice3=>"But wait"}
    

    then:

    filtered_params.to_a.join("\t")
    # or
    filtered_params.values.join("\t")
    

What is an uber jar?

ubar jar is also known as fat jar i.e. jar with dependencies.
There are three common methods for constructing an uber jar:

  1. Unshaded: Unpack all JAR files, then repack them into a single JAR. Works with Java's default class loader. Tools maven-assembly-plugin
  2. Shaded: Same as unshaded, but rename (i.e., "shade") all packages of all dependencies. Works with Java's default class loader. Avoids some (not all) dependency version clashes. Tools maven-shade-plugin
  3. JAR of JARs: The final JAR file contains the other JAR files embedded within. Avoids dependency version clashes. All resource files are preserved. Tools: Eclipse JAR File Exporter

for more

VS2010 How to include files in project, to copy them to build output directory automatically during build or publish

In my case, setting Copy to Output Directory to Copy Always and Build did not do the trick, while Rebuild did.

Hope this helps someone!

How to disable scientific notation?

format(99999999,scientific = F)

gives

99999999

How to format a Java string with leading zero?

You can use this:

org.apache.commons.lang.StringUtils.leftPad("Apple", 8, "0")

What is android:weightSum in android, and how does it work?

Per documentation, android:weightSum defines the maximum weight sum, and is calculated as the sum of the layout_weight of all the children if not specified explicitly.

Let's consider an example with a LinearLayout with horizontal orientation and 3 ImageViews inside it. Now we want these ImageViews always to take equal space. To acheive this, you can set the layout_weight of each ImageView to 1 and the weightSum will be calculated to be equal to 3 as shown in the comment.

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    <!-- android:weightSum="3" -->
    android:orientation="horizontal"
    android:layout_gravity="center">

   <ImageView
       android:layout_height="wrap_content"       
       android:layout_weight="1"
       android:layout_width="0dp"/>
  .....

weightSum is useful for having the layout rendered correctly for any device, which will not happen if you set width and height directly.

css with background image without repeating the image

Try this

padding:8px;
overflow: hidden;
zoom: 1;
text-align: left;
font-size: 13px;
font-family: "Trebuchet MS",Arial,Sans;
line-height: 24px;
color: black;
border-bottom: solid 1px #BBB;
background:url('images/checked.gif') white no-repeat;

This is full css.. Why you use padding:0 8px, then override it with paddings? This is what you need...

How to test if a double is zero?

Numeric primitives in class scope are initialized to zero when not explicitly initialized.

Numeric primitives in local scope (variables in methods) must be explicitly initialized.

If you are only worried about division by zero exceptions, checking that your double is not exactly zero works great.

if(value != 0)
    //divide by value is safe when value is not exactly zero.

Otherwise when checking if a floating point value like double or float is 0, an error threshold is used to detect if the value is near 0, but not quite 0.

public boolean isZero(double value, double threshold){
    return value >= -threshold && value <= threshold;
}

What is base 64 encoding used for?

From http://en.wikipedia.org/wiki/Base64

The term Base64 refers to a specific MIME content transfer encoding. It is also used as a generic term for any similar encoding scheme that encodes binary data by treating it numerically and translating it into a base 64 representation. The particular choice of base is due to the history of character set encoding: one can choose a set of 64 characters that is both part of the subset common to most encodings, and also printable. This combination leaves the data unlikely to be modified in transit through systems, such as email, which were traditionally not 8-bit clean.

Base64 can be used in a variety of contexts:

  • Evolution and Thunderbird use Base64 to obfuscate e-mail passwords[1]
  • Base64 can be used to transmit and store text that might otherwise cause delimiter collision
  • Base64 is often used as a quick but insecure shortcut to obscure secrets without incurring the overhead of cryptographic key management

  • Spammers use Base64 to evade basic anti-spamming tools, which often do not decode Base64 and therefore cannot detect keywords in encoded messages.

  • Base64 is used to encode character strings in LDIF files
  • Base64 is sometimes used to embed binary data in an XML file, using a syntax similar to ...... e.g. Firefox's bookmarks.html.
  • Base64 is also used when communicating with government Fiscal Signature printing devices (usually, over serial or parallel ports) to minimize the delay when transferring receipt characters for signing.
  • Base64 is used to encode binary files such as images within scripts, to avoid depending on external files.
  • Can be used to embed raw image data into a CSS property such as background-image.

HRESULT: 0x800A03EC on Worksheet.range

Not being able to reply to/endorse this answer, so posting here:

Indeed, the format of the source/destination ranges when moving data from one range to another might cause this error as well.

In my case, the range I wanted to copy contained a date formatted column, and the column contained one cell with an invalid date value (it was not even formatted due to its value, which was a negative integer). So the copy operation between the two ranges was halting at the said cell yielding the very error message discussed here.

The solution in my case was to use Range.Value2 instead of Range.Value, which caused Excel to bypass formatting the cell as a date (more details here). However, this will render your date and time columns to display as integers and decimals. You will, however, be able to change the formats to the desired ones if you know where to expect the date and time values by setting their Range/Column/Cell.NumberFormat property accordingly.

How to automatically generate getters and setters in Android Studio

Using Alt+ Insert or Right-click and choose "Generate..." You may easily generate getter and setter or Override methods in Android Studio. This has the same effect as using the Menu Bar Code -> Generate...

enter image description here enter image description here

Laravel - Pass more than one variable to view

with function and single parameters:

    $ms = Person::where('name', 'Foo Bar');
    $persons = Person::order_by('list_order', 'ASC')->get();
    return $view->with(compact('ms', 'persons'));

with function and array parameter:

    $ms = Person::where('name', 'Foo Bar');
    $persons = Person::order_by('list_order', 'ASC')->get();
    $array = ['ms' => $ms, 'persons' => $persons];
    return $view->with($array);

UILabel is not auto-shrinking text to fit label size

I think you can write bellow code after alloc init Label

UILabel* lbl = [[UILabel alloc]initWithFrame:CGRectMake(0, 10, 280, 50)];
lbl.text = @"vbdsbfdshfisdhfidshufidhsufhdsf dhdsfhdksbf hfsdh fksdfidsf sdfhsd fhdsf sdhfh sdifsdkf ksdhfkds fhdsf dsfkdsfkjdhsfkjdhskfjhsdk fdhsf ";
[lbl setMinimumFontSize:8.0];
[lbl setNumberOfLines:0];
[lbl setFont:[UIFont systemFontOfSize:10.0]];
lbl.lineBreakMode = UILineBreakModeWordWrap;
lbl.backgroundColor = [UIColor redColor];
[lbl sizeToFit];
[self.view addSubview:lbl];

It is working with me fine Use it

Callback after all asynchronous forEach callbacks are completed

My solution without Promise (this ensures that every action is ended before the next one begins):

_x000D_
_x000D_
Array.prototype.forEachAsync = function (callback, end) {_x000D_
        var self = this;_x000D_
    _x000D_
        function task(index) {_x000D_
            var x = self[index];_x000D_
            if (index >= self.length) {_x000D_
                end()_x000D_
            }_x000D_
            else {_x000D_
                callback(self[index], index, self, function () {_x000D_
                    task(index + 1);_x000D_
                });_x000D_
            }_x000D_
        }_x000D_
    _x000D_
        task(0);_x000D_
    };_x000D_
    _x000D_
    _x000D_
    var i = 0;_x000D_
    var myArray = Array.apply(null, Array(10)).map(function(item) { return i++; });_x000D_
    console.log(JSON.stringify(myArray));_x000D_
    myArray.forEachAsync(function(item, index, arr, next){_x000D_
      setTimeout(function(){_x000D_
        $(".toto").append("<div>item index " + item + " done</div>");_x000D_
        console.log("action " + item + " done");_x000D_
        next();_x000D_
      }, 300);_x000D_
    }, function(){_x000D_
        $(".toto").append("<div>ALL ACTIONS ARE DONE</div>");_x000D_
        console.log("ALL ACTIONS ARE DONE");_x000D_
    });
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="toto">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

ImportError: No module named scipy

For windows users:

I found this solution after days. Firstly which python version you want to install?

If you want for Python 2.7 version:

STEP 1:

scipy-0.19.0-cp27-cp27m-win32.whl

scipy-0.19.0-cp27-cp27m-win_amd64.whl

numpy-1.11.3+mkl-cp27-cp27m-win32.whl

numpy-1.11.3+mkl-cp27-cp27m-win_amd64.whl

If you want for Python 3.4 version:

scipy-0.19.0-cp34-cp34m-win32.whl

scipy-0.19.0-cp34-cp34m-win_amd64.whl

numpy-1.11.3+mkl-cp34-cp34m-win32.whl

numpy-1.11.3+mkl-cp34-cp34m-win_amd64.whl

If you want for Python 3.5 version:

scipy-0.19.0-cp35-cp35m-win32.whl

scipy-0.19.0-cp35-cp35m-win_amd64.whl

numpy-1.11.3+mkl-cp35-cp35m-win32.whl

numpy-1.11.3+mkl-cp35-cp35m-win_amd64.whl

If you want for Python 3.6 version:

scipy-0.19.0-cp36-cp36m-win32.whl

scipy-0.19.0-cp36-cp36m-win_amd64.whl

numpy-1.11.3+mkl-cp36-cp36m-win32.whl

numpy-1.11.3+mkl-cp36-cp36m-win_amd64.whl

Link: [click[1]

Once finish installation, go to your directory.

For example my directory:

cd C:\Users\asus\AppData\Local\Programs\Python\Python35\Scripts>
pip install [where/is/your/downloaded/scipy_whl.]

STEP 2:

Numpy+MKL

From same web site based on python version again:

After that use same thing again in Script folder

cd C:\Users\asus\AppData\Local\Programs\Python\Python35\Scripts>
pip3 install [where/is/your/downloaded/numpy_whl.]

And test it in python folder.

Python35>python 
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:18:55) [MSC v.1900 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. 
>>>import scipy

AngularJS : Factory and Service?

$provide service

They are technically the same thing, it's actually a different notation of using the provider function of the $provide service.

  • If you're using a class: you could use the service notation.
  • If you're using an object: you could use the factory notation.

The only difference between the service and the factory notation is that the service is new-ed and the factory is not. But for everything else they both look, smell and behave the same. Again, it's just a shorthand for the $provide.provider function.

// Factory

angular.module('myApp').factory('myFactory', function() {

  var _myPrivateValue = 123;

  return {
    privateValue: function() { return _myPrivateValue; }
  };

});

// Service

function MyService() {
  this._myPrivateValue = 123;
}

MyService.prototype.privateValue = function() {
  return this._myPrivateValue;
};

angular.module('myApp').service('MyService', MyService);

What is the default Precision and Scale for a Number in Oracle?

The NUMBER type can be specified in different styles:

                Resulting  Resulting  Precision
Specification   Precision  Scale      Check      Comment
-------------------------------------------------------------------------------
NUMBER          NULL       NULL       NO         'maximum range and precision',
                                                 values are stored 'as given'
NUMBER(P, S)    P          S          YES        Error code: ORA-01438
NUMBER(P)       P          0          YES        Error code: ORA-01438
NUMBER(*, S)    38         S          NO

Where the precision is the total number of digits and scale is the number of digits right or left (negative scale) of the decimal point.

Oracle specifies ORA-01438 as

value larger than specified precision allowed for this column

As noted in the table, this integrity check is only active if the precision is explicitly specified. Otherwise Oracle silently rounds the inserted or updated value using some unspecified method.

Windows shell command to get the full path to the current directory?

Use cd with no arguments if you're using the shell directly, or %cd% if you want to use it in a batch file (it behaves like an environment variable).

Highlight Bash/shell code in Markdown files

It depends on the Markdown rendering engine and the Markdown flavour. There is no standard for this. If you mean GitHub flavoured Markdown for example, shell should work fine. Aliases are sh, bash or zsh. You can find the list of available syntax lexers here.

How to return a result from a VBA function

VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:

test = 1

Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.

Keyboard shortcut for Jump to Previous View Location (Navigate back/forward) in IntelliJ IDEA

Using the following ways using only two keys will be the easier:

control + Tab

or

Alt + Left/Right

Detecting Back Button/Hash Change in URL

I do the following, if you want to use it then paste it in some where and set your handler code in locationHashChanged(qs) where commented, and then call changeHashValue(hashQuery) every time you load an ajax request. Its not a quick-fix answer and there are none, so you will need to think about it and pass sensible hashQuery args (ie a=1&b=2) to changeHashValue(hashQuery) and then cater for each combination of said args in your locationHashChanged(qs) callback ...

// Add code below ...
function locationHashChanged(qs)
{
  var q = parseQs(qs);
  // ADD SOME CODE HERE TO LOAD YOUR PAGE ELEMS AS PER q !!
  // YOU SHOULD CATER FOR EACH hashQuery ATTRS COMBINATION
  //  THAT IS PASSED TO changeHashValue(hashQuery)
}

// CALL THIS FROM YOUR AJAX LOAD CODE EACH LOAD ...
function changeHashValue(hashQuery)
{
  stopHashListener();
  hashValue     = hashQuery;
  location.hash = hashQuery;
  startHashListener();
}

// AND DONT WORRY ABOUT ANYTHING BELOW ...
function checkIfHashChanged()
{
  var hashQuery = getHashQuery();
  if (hashQuery == hashValue)
    return;
  hashValue = hashQuery;
  locationHashChanged(hashQuery);
}

function parseQs(qs)
{
  var q = {};
  var pairs = qs.split('&');
  for (var idx in pairs) {
    var arg = pairs[idx].split('=');
    q[arg[0]] = arg[1];
  }
  return q;
}

function startHashListener()
{
  hashListener = setInterval(checkIfHashChanged, 1000);
}

function stopHashListener()
{
  if (hashListener != null)
    clearInterval(hashListener);
  hashListener = null;
}

function getHashQuery()
{
  return location.hash.replace(/^#/, '');
}

var hashListener = null;
var hashValue    = '';//getHashQuery();
startHashListener();

Object creation on the stack/heap?

Actually, neither statement says anything about heap or stack. The code

Object o;

creates one of the following, depending on its context:

  • a local variable with automatic storage,
  • a static variable at namespace or file scope,
  • a member variable that designates the subobject of another object.

This means that the storage location is determined by the context in which the object is defined. In addition, the C++ standard does not talk about stack vs heap storage. Instead, it talks about storage duration, which can be either automatic, dynamic, static or thread-local. However, most implementations implement automatic storage via the call stack, and dynamic storage via the heap.

Local variables, which have automatic storage, are thus created on the stack. Static (and thread-local) objects are generally allocated in their own memory regions, neither on the stack nor on the heap. And member variables are allocated wherever the object they belong to is allocated. They have their containing object’s storage duration.

To illustrate this with an example:

struct Foo {
    Object o;
};

Foo foo;

int main() {
    Foo f;
    Foo* p = new Foo;
    Foo* pf = &f;
}

Now where is the object Foo::o (that is, the subobject o of an object of class Foo) created? It depends:

  • foo.o has static storage because foo has static storage, and therefore lives neither on the stack nor on the heap.
  • f.o has automatic storage since f has automatic storage (= it lives on the stack).
  • p->o has dynamic storage since *p has dynamic storage (= it lives on the heap).
  • pf->o is the same object as f.o because pf points to f.

In fact, both p and pf in the above have automatic storage. A pointer’s storage is indistinguishable from any other object’s, it is determined by context. Furthermore, the initialising expression has no effect on the pointer storage.

The pointee (= what the pointer points to) is a completely different matter, and could refer to any kind of storage: *p is dynamic, whereas *pf is automatic.

How to position absolute inside a div?

  1. First all block level elements are postioned static to the 'document'. The default positioning for all elements is position: static, which means the element is not positioned and occurs where it normally would in the document. Normally you wouldn't specify this unless you needed to override a positioning that had been previously set.
  2. Relative position: If you specify position: relative, then you can use top or bottom, and left or right to move the element relative to where it would normally occur in the document.
  3. When you specify position: absolute, the element is removed from the document and placed exactly where you tell it to go.

So in regard to your question you should position the containing block relative, i.e:

#parent {
  position: relative;
}

And the child element you should position absolute to the parent element like this:

#child {
  position: absolute;
}

See: Learn CSS Positioning in Ten Steps

How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

Convert varchar to float IF ISNUMERIC

You can't cast to float and keep the string in the same column. You can do like this to get null when isnumeric returns 0.

SELECT CASE ISNUMERIC(QTY) WHEN 1 THEN CAST(QTY AS float) ELSE null END

Concatenating date with a string in Excel

You can do it this simple way :

A1 = Mahi
A2 = NULL(blank)

Select A2 Right click on cell --> Format cells --> change to TEXT

Then put the date in A2 (A2 =31/07/1990)

Then concatenate it will work. No need of any formulae.

=CONCATENATE(A1,A2)

mahi31/07/1990

(This works on the empty cells ie.,Before entering the DATE value to cell you need to make it as TEXT).

How to select an item from a dropdown list using Selenium WebDriver with java?

Google "select item selenium webdriver" brings up How do I set an option as selected using Selenium WebDriver (selenium 2.0) client in ruby as first result. This is not Java, but you should be able to translate it without too much work. https://sqa.stackexchange.com/questions/1355/what-is-the-correct-way-to-select-an-option-using-seleniums-python-webdriver is in the top 5, again not Java but the API is very similar.

How to overcome TypeError: unhashable type: 'list'

The TypeError is happening because k is a list, since it is created using a slice from another list with the line k = list[0:j]. This should probably be something like k = ' '.join(list[0:j]), so you have a string instead.

In addition to this, your if statement is incorrect as noted by Jesse's answer, which should read if k not in d or if not k in d (I prefer the latter).

You are also clearing your dictionary on each iteration since you have d = {} inside of your for loop.

Note that you should also not be using list or file as variable names, since you will be masking builtins.

Here is how I would rewrite your code:

d = {}
with open("filename.txt", "r") as input_file:
    for line in input_file:
        fields = line.split()
        j = fields.index("x")
        k = " ".join(fields[:j])
        d.setdefault(k, []).append(" ".join(fields[j+1:]))

The dict.setdefault() method above replaces the if k not in d logic from your code.

GridView VS GridLayout in Android Apps

A GridView is a ViewGroup that displays items in two-dimensional scrolling grid. The items in the grid come from the ListAdapter associated with this view.

This is what you'd want to use (keep using). Because a GridView gets its data from a ListAdapter, the only data loaded in memory will be the one displayed on screen. GridViews, much like ListViews reuse and recycle their views for better performance.

Whereas a GridLayout is a layout that places its children in a rectangular grid.

It was introduced in API level 14, and was recently backported in the Support Library. Its main purpose is to solve alignment and performance problems in other layouts. Check out this tutorial if you want to learn more about GridLayout.

AngularJS - Attribute directive input value change

To watch out the runtime changes in value of a custom directive, use $observe method of attrs object, instead of putting $watch inside a custom directive. Here is the documentation for the same ... $observe docs

Get records with max value for each group of grouped SQL results

Improving axiac's solution to avoid selecting multiple rows per group while also allowing for use of indexes

SELECT o.*
FROM `Persons` o 
  LEFT JOIN `Persons` b 
      ON o.Group = b.Group AND o.Age < b.Age
  LEFT JOIN `Persons` c 
      ON o.Group = c.Group AND o.Age = c.Age and o.id < c.id
WHERE b.Age is NULL and c.id is null

What are database constraints?

constraints are conditions, that can validate specific condition. Constraints related with database are Domain integrity, Entity integrity, Referential Integrity, User Defined Integrity constraints etc.

How to set an environment variable in a running docker container

here is how to update a docker container config permanently

  1. stop container: docker stop <container name>
  2. edit container config: docker run -it -v /var/lib/docker:/var/lib/docker alpine vi $(docker inspect --format='/var/lib/docker/containers/{{.Id}}/config.v2.json' <container name>)
  3. restart docker

CSS text-overflow: ellipsis; not working?

Add display: block; or display: inline-block; to your #User_Apps_Content .DLD_App a

demo

How to round double to nearest whole number and then convert to a float?

float b = (float)Math.ceil(a); or float b = (float)Math.round(a);

Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).

Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.

Android Notification Sound

// set notification audio (Tested upto android 10)

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);

converting numbers in to words C#

When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:

{1, "one"}
{2, "two"}
{30, "thirty"}

You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.

After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.

pinpointing "conditional jump or move depends on uninitialized value(s)" valgrind message

What this means is that you are trying to print out/output a value which is at least partially uninitialized. Can you narrow it down so that you know exactly what value that is? After that, trace through your code to see where it is being initialized. Chances are, you will see that it is not being fully initialized.

If you need more help, posting the relevant sections of source code might allow someone to offer more guidance.

EDIT

I see you've found the problem. Note that valgrind watches for Conditional jump or move based on unitialized variables. What that means is that it will only give out a warning if the execution of the program is altered due to the uninitialized value (ie. the program takes a different branch in an if statement, for example). Since the actual arithmetic did not involve a conditional jump or move, valgrind did not warn you of that. Instead, it propagated the "uninitialized" status to the result of the statement that used it.

It may seem counterintuitive that it does not warn you immediately, but as mark4o pointed out, it does this because uninitialized values get used in C all the time (examples: padding in structures, the realloc() call, etc.) so those warnings would not be very useful due to the false positive frequency.

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

TIP:

comment out pid and socket file, if you can't connect to server.. mysql could be connecting with incorrect pid and/or socket file, so when you try to connect to server trough command-line it "looks" at the incorrect pid/socket file...

### comment out pid and socket file, if you can't connect to server..
#pid-file=/var/run/mysql/mysqld.pid #socket=/var/lib/mysql/mysql.sock

Change the Right Margin of a View Programmatically?

EDIT: A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):

public static void setMargins (View v, int l, int t, int r, int b) {
    if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
        p.setMargins(l, t, r, b);
        v.requestLayout();
    }
}

You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:

TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);

I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.

NOTE

Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams

Simplest way to wait some asynchronous tasks complete, in Javascript?

With deferred (another promise/deferred implementation) you can do:

// Setup 'pdrop', promise version of 'drop' method
var deferred = require('deferred');
mongoose.Collection.prototype.pdrop =
    deferred.promisify(mongoose.Collection.prototype.drop);

// Drop collections:
deferred.map(['aaa','bbb','ccc'], function(name){
    return conn.collection(name).pdrop()(function () {
      console.log("dropped");
    });
}).end(function () {
    console.log("all dropped");
}, null);

Vuejs: v-model array in multiple input

If you were asking how to do it in vue2 and make options to insert and delete it, please, have a look an js fiddle

_x000D_
_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  data: {_x000D_
    finds: [] _x000D_
  },_x000D_
  methods: {_x000D_
    addFind: function () {_x000D_
      this.finds.push({ value: 'def' });_x000D_
    },_x000D_
    deleteFind: function (index) {_x000D_
      console.log(index);_x000D_
      console.log(this.finds);_x000D_
      this.finds.splice(index, 1);_x000D_
    }_x000D_
  }_x000D_
});
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <h1>Finds</h1>_x000D_
  <div v-for="(find, index) in finds">_x000D_
    <input v-model="find.value">_x000D_
    <button @click="deleteFind(index)">_x000D_
      delete_x000D_
    </button>_x000D_
  </div>_x000D_
  _x000D_
  <button @click="addFind">_x000D_
    New Find_x000D_
  </button>_x000D_
  _x000D_
  <pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
_x000D_
_x000D_

error: ORA-65096: invalid common user or role name in oracle

99.9% of the time the error ORA-65096: invalid common user or role name means you are logged into the CDB when you should be logged into a PDB.

But if you insist on creating users the wrong way, follow the steps below.

DANGER

Setting undocumented parameters like this (as indicated by the leading underscore) should only be done under the direction of Oracle Support. Changing such parameters without such guidance may invalidate your support contract. So do this at your own risk.

Specifically, if you set "_ORACLE_SCRIPT"=true, some data dictionary changes will be made with the column ORACLE_MAINTAINED set to 'Y'. Those users and objects will be incorrectly excluded from some DBA scripts. And they may be incorrectly included in some system scripts.

If you are OK with the above risks, and don't want to create common users the correct way, use the below answer.


Before creating the user run:

alter session set "_ORACLE_SCRIPT"=true;  

I found the answer here

How can I find which tables reference a given table in Oracle SQL Developer?

SELECT DISTINCT table_name, 
                constraint_name, 
                column_name, 
                r_table_name, 
                position, 
                constraint_type 
FROM   (SELECT uc.table_name, 
               uc.constraint_name, 
               cols.column_name, 
               (SELECT table_name 
                FROM   user_constraints 
                WHERE  constraint_name = uc.r_constraint_name) r_table_name, 
               (SELECT column_name 
                FROM   user_cons_columns 
                WHERE  constraint_name = uc.r_constraint_name 
                       AND position = cols.position)           r_column_name, 
               cols.position, 
               uc.constraint_type 
        FROM   user_constraints uc 
               inner join user_cons_columns cols 
                       ON uc.constraint_name = cols.constraint_name 
        WHERE  constraint_type != 'C') 
START WITH table_name = '&&tableName' 
           AND column_name = '&&columnName' 
CONNECT BY NOCYCLE PRIOR table_name = r_table_name 
                         AND PRIOR column_name = r_column_name; 

Using NULL in C++?

Assuming that you don't have a library or system header that defines NULL as for example (void*)0 or (char*)0 it's fine. I always tend to use 0 myself as it is by definition the null pointer. In c++0x you'll have nullptr available so the question won't matter as much anymore.

How to change font in ipython notebook

In JupyterNotebook cell, Simply you can use:

%%html
<style type='text/css'>
.CodeMirror{
font-size: 17px;
</style>

Not able to launch IE browser using Selenium2 (Webdriver) with Java

For NighwatchJS use:

"ie" : {
  "desiredCapabilities": {
    "browserName": "internet explorer",
    "javascriptEnabled": true,
    "acceptSslCerts": true,
    "allowBlockedContent": true,
    "ignoreProtectedModeSettings": true
  }
},

What is the difference between 'typedef' and 'using' in C++11?

They are essentially the same but using provides alias templates which is quite useful. One good example I could find is as follows:

namespace std {
 template<typename T> using add_const_t = typename add_const<T>::type;
}

So, we can use std::add_const_t<T> instead of typename std::add_const<T>::type

The forked VM terminated without saying properly goodbye. VM crash or System.exit called

I had the same problem and solved by adding:

<argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>

The whole plugin element is:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-surefire-plugin</artifactId>
  <configuration>
    <forkCount>3</forkCount>
    <reuseForks>true</reuseForks>
    <argLine>-Xmx1024m -XX:MaxPermSize=256m</argLine>
  </configuration>
</plugin>

Not Equal to This OR That in Lua

x ~= 0 or 1 is the same as ((x ~= 0) or 1)

x ~=(0 or 1) is the same as (x ~= 0).

try something like this instead.

function isNot0Or1(x)
    return (x ~= 0 and x ~= 1)
end

print( isNot0Or1(-1) == true )
print( isNot0Or1(0) == false )
print( isNot0Or1(1) == false )

How do I draw a set of vertical lines in gnuplot?

You can use the grid feature for the second unused axis x2, which is the most natural way of drawing a set of regular spaced lines.

set grid x2tics
set x2tics 10 format "" scale 0

In general, the grid is drawn at the same position as the tics on the axis. In case the position of the lines does not correspond to the tics position, gnuplot provides an additional set of tics, called x2tics. format "" and scale 0 hides the x2tics so you only see the grid lines.

You can style the lines as usual with linewith, linecolor.

Maven Error: Could not find or load main class

The first thing i would suggest is to use the correct configuration for predefined descriptors.

<project>
  [...]
  <build>
    [...]
    <plugins>
      <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <version>2.5.3</version>
        <configuration>
          <descriptorRefs>
            <descriptorRef>jar-with-dependencies</descriptorRef>
          </descriptorRefs>
        </configuration>
        [...]
</project>

To configure the main class you need to know the package and name of the class you would like to use which should be given into <mainClass>...</mainClass> parameter.

Furthermore i recommend to stop using Maven 2 and move to Maven 3 instead.

Python function to convert seconds into minutes, hours, and days

At first glance, I figured divmod would be faster since it's a single statement and a built-in function, but timeit seems to show otherwise. Consider this little example I came up with when I was trying to figure out the fastest method for use in a loop that continuously runs in a gobject idle_add splitting a seconds counter into a human readable time for updating a progress bar label.

import timeit

def test1(x,y, dropy):
    while x > 0:
        y -= dropy
        x -= 1

        # the test
        minutes = (y-x) / 60
        seconds = (y-x) % 60.0

def test2(x,y, dropy):
    while x > 0:
        y -= dropy
        x -= 1

        # the test
        minutes, seconds = divmod((y-x), 60)

x = 55     # litte number, also number of tests
y = 10000  # make y > x by factor of drop
dropy = 7 # y is reduced this much each iteration, for variation

print "division and modulus:", timeit.timeit( lambda: test1(x,y,dropy) )
print "divmod function:",      timeit.timeit( lambda: test2(x,y,dropy) )

The built-in divmod function seems incredibly slower compared to using the simple division and modulus.

division and modulus: 12.5737669468
divmod function: 17.2861430645

How to use ArgumentCaptor for stubbing?

The line

when(someObject.doSomething(argumentCaptor.capture())).thenReturn(true);

would do the same as

when(someObject.doSomething(Matchers.any())).thenReturn(true);

So, using argumentCaptor.capture() when stubbing has no added value. Using Matchers.any() shows better what really happens and therefor is better for readability. With argumentCaptor.capture(), you can't read what arguments are really matched. And instead of using any(), you can use more specific matchers when you have more information (class of the expected argument), to improve your test.

And another problem: If using argumentCaptor.capture() when stubbing it becomes unclear how many values you should expect to be captured after verification. We want to capture a value during verification, not during stubbing because at that point there is no value to capture yet. So what does the argument captors capture method capture during stubbing? It capture anything because there is nothing to be captured yet. I consider it to be undefined behavior and I don't want to use undefined behavior.

Setting equal heights for div's with jQuery

// Select and loop the container element of the elements you want to equalise
        $('.equal').each(function(){  

          // Cache the highest
          var highestBox = 0;

          // Select and loop the elements you want to equalise
          $('.col-lg-4', this).each(function(){

            // If this box is higher than the cached highest then store it
            if($(this).height() > highestBox) {
              highestBox = $(this).height(); 
            }

          });  

          // Set the height of all those children to whichever was highest 
          $('.col-lg-4',this).height(highestBox);

        }); 

    });

What does the "yield" keyword do?

For those who prefer a minimal working example, meditate on this interactive Python session:

>>> def f():
...   yield 1
...   yield 2
...   yield 3
... 
>>> g = f()
>>> for i in g:
...   print(i)
... 
1
2
3
>>> for i in g:
...   print(i)
... 
>>> # Note that this time nothing was printed

URL encoding in Android

For android, I would use String android.net.Uri.encode(String s)

Encodes characters in the given string as '%'-escaped octets using the UTF-8 scheme. Leaves letters ("A-Z", "a-z"), numbers ("0-9"), and unreserved characters ("_-!.~'()*") intact. Encodes all other characters.

Ex/

String urlEncoded = "http://stackoverflow.com/search?q=" + Uri.encode(query);

How to clear exisiting dropdownlist items when its content changes?

Please use the following

ddlCity.Items.Clear();

Sending files using POST with HttpURLConnection

I haven't tested this, but you might try using PipedInputStream and PipedOutputStream. It might look something like:

final Bitmap bmp = … // your bitmap

// Set up Piped streams
final PipedOutputStream pos = new PipedOutputStream(new ByteArrayOutputStream());
final PipedInputStream pis = new PipedInputStream(pos);

// Send bitmap data to the PipedOutputStream in a separate thread
new Thread() {
    public void run() {
        bmp.compress(Bitmap.CompressFormat.PNG, 100, pos);
    }
}.start();

// Send POST request
try {
    // Construct InputStreamEntity that feeds off of the PipedInputStream
    InputStreamEntity reqEntity = new InputStreamEntity(pis, -1);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    reqEntity.setContentType("binary/octet-stream");
    reqEntity.setChunked(true);
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
} catch (Exception e) {
    e.printStackTrace()
}

Is there a way to get a collection of all the Models in your Rails app?

ActiveRecord::Base.connection.tables.map do |model|
  model.capitalize.singularize.camelize
end

will return

["Article", "MenuItem", "Post", "ZebraStripePerson"]

Additional information If you want to call a method on the object name without model:string unknown method or variable errors use this

model.classify.constantize.attribute_names

connect to host localhost port 22: Connection refused

If you're certain that you have installed ssh, then it's possible that ssh and/or sshd has been terminated or the server service hasn't been started. To check whether these processes are running use:

//this tells you whether your ssh instance is active/inactive
sudo service ssh status

OR

//this list all running processes whose names contain the string "ssh"
sudo ps -A | grep ssh

It's likely that ssh would be active and running but sshd would not. To enable them:

sudo service ssh start

NB; - some systems have a restart option but mine didn't

Android replace the current fragment with another fragment

Then provided your button is showing and the click event is being fired you can call the following in your click event:

final FragmentTransaction ft = getFragmentManager().beginTransaction(); 
ft.replace(R.id.details, new NewFragmentToReplace(), "NewFragmentTag"); 
ft.commit(); 

and if you want to go back to the DetailsFragment on clicking back ensure you add the above transaction to the back stack, i.e.

ft.addToBackStack(null);

Or am I missing something? Alternatively some people suggest that your activity gets the click event for the button and it has responsibility for replacing the fragments in your details pane.

IIS7 Permissions Overview - ApplicationPoolIdentity

Just to add to the confusion, the (Windows Explorer) Effective Permissions dialog doesn't work for these logins. I have a site "Umbo4" using pass-through authentication, and looked at the user's Effective Permissions in the site root folder. The Check Names test resolved the name "IIS AppPool\Umbo4", but the Effective Permissions shows that the user had no permissions at all on the folder (all checkboxes unchecked).

I then excluded this user from the folder explicitly, using the Explorer Security tab. This resulted in the site failing with a HTTP 500.19 error, as expected. The Effective Permissions however looked exactly as before.

Why does Maven have such a bad rep?

Any Java developer can easily become an expert ANT user, but not even an expert Java developer can't become a beginner level MAVEN user.

Maven will make your developers scared s***less for doing anything related to Build and Deployment.

They will start respecting Maven more than the War file or Ear file!! which is bad bad bad!

Then you will be left at the mercy of online forums, where fan-boys will berate you for not doing things the "Maven way".

MySQL - Make an existing Field Unique

The easiest and fastest way would be with phpmyadmin structure table.

USE PHPMYADMIN ADMIN PANEL!

There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.

How to make MySQL table primary key auto increment with some prefix

If you really need this you can achieve your goal with help of separate table for sequencing (if you don't mind) and a trigger.

Tables

CREATE TABLE table1_seq
(
  id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
);
CREATE TABLE table1
(
  id VARCHAR(7) NOT NULL PRIMARY KEY DEFAULT '0', name VARCHAR(30)
);

Now the trigger

DELIMITER $$
CREATE TRIGGER tg_table1_insert
BEFORE INSERT ON table1
FOR EACH ROW
BEGIN
  INSERT INTO table1_seq VALUES (NULL);
  SET NEW.id = CONCAT('LHPL', LPAD(LAST_INSERT_ID(), 3, '0'));
END$$
DELIMITER ;

Then you just insert rows to table1

INSERT INTO Table1 (name) 
VALUES ('Jhon'), ('Mark');

And you'll have

|      ID | NAME |
------------------
| LHPL001 | Jhon |
| LHPL002 | Mark |

Here is SQLFiddle demo

How to refresh an IFrame using Javascript?

Resetting the src attribute directly:

iframe.src = iframe.src;

Resetting the src with a time stamp for cache busting:

iframe.src =  iframe.src.split("?")[0] + "?_=" + new Date().getTime();

Clearing the src when query strings option is not possible (Data URI):

var wasSrc = iframe.src

iframe.onload = function() {
    iframe.onload = undefined;
    iframe.src = wasSrc;
}

MySQL DISTINCT on a GROUP_CONCAT()

You can simply add DISTINCT in front.

SELECT GROUP_CONCAT(DISTINCT categories SEPARATOR ' ')

if you want to sort,

SELECT GROUP_CONCAT(DISTINCT categories ORDER BY categories ASC SEPARATOR ' ')

iOS 7 - Status bar overlaps the view

-(UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

-(void)viewWillLayoutSubviews{

 if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 7) 
  {
    self.view.clipsToBounds = YES;
    CGRect screenRect = [[UIScreen mainScreen] bounds];
    CGFloat screenHeight = 0.0;
    if(UIDeviceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]))
        screenHeight = screenRect.size.height;
    else
        screenHeight = screenRect.size.width;
    CGRect screenFrame = CGRectMake(0, 20, self.view.frame.size.width,screenHeight-20);
    CGRect viewFrame1 = [self.view convertRect:self.view.frame toView:nil];
    if (!CGRectEqualToRect(screenFrame, viewFrame1))
    {
        self.view.frame = screenFrame;
        self.view.bounds = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);
    }
  }
}

Add Key in plist--- View controller-based status bar appearance : NO

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

Node.js/Windows error: ENOENT, stat 'C:\Users\RT\AppData\Roaming\npm'

I ran into the same problem while installing a package via npm.

After creating the npm folder manually in C:\Users\UserName\AppData\Roaming\ that particular error was gone, but it gave similar multiple errors as it tried to create additional directories in the npm folder and failed. The issue was resolved after running the command prompt as an administrator.

How do I put an already-running process under nohup?

This worked for me on Ubuntu linux while in tcshell.

  1. CtrlZ to pause it

  2. bg to run in background

  3. jobs to get its job number

  4. nohup %n where n is the job number

HTML "overlay" which allows clicks to fall through to elements behind it

Add pointer-events: none; to the overlay.


Original answer: My suggestion would be that you could capture the click event with the overlay, hide the overlay, then refire the click event, then display the overlay again. I'm not sure if you'd get a flicker effect though.

[Update] Exactly this problem and exactly my solution just appeared in this post: "Forwarding Mouse Events Through Layers". I know its probably a little late for the OP, but for the sake of somebody having this problem in the future, I though I would include it.

Insert data into hive table

You can insert new data into table by two ways.

  1. Load the data of a file into table using load command.

    LOAD DATA [LOCAL] INPATH 'filepath' [OVERWRITE] INTO TABLE tablename.
    
  2. You can insert new data into table by using select query.

    INSERT INTO table tablename1 select columnlist FROM secondtable;
    

NameError: name 'python' is not defined

When you run the Windows Command Prompt, and type in python, it starts the Python interpreter.

Typing it again tries to interpret python as a variable, which doesn't exist and thus won't work:

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line

C:\Users\USER>

If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python is interpreted as a variable, which you have not defined.

ToList()-- does it create a new list?

I think that this is equivalent to asking if ToList does a deep or shallow copy. As ToList has no way to clone MyObject, it must do a shallow copy, so the created list contains the same references as the original one, so the code returns 5.

What is the difference between MySQL, MySQLi and PDO?

Specifically, the MySQLi extension provides the following extremely useful benefits over the old MySQL extension..

OOP Interface (in addition to procedural) Prepared Statement Support Transaction + Stored Procedure Support Nicer Syntax Speed Improvements Enhanced Debugging

PDO Extension

PHP Data Objects extension is a Database Abstraction Layer. Specifically, this is not a MySQL interface, as it provides drivers for many database engines (of course including MYSQL).

PDO aims to provide a consistent API that means when a database engine is changed, the code changes to reflect this should be minimal. When using PDO, your code will normally "just work" across many database engines, simply by changing the driver you're using.

In addition to being cross-database compatible, PDO also supports prepared statements, stored procedures and more, whilst using the MySQL Driver.

How to store Configuration file and read it using React

If you used Create React App, you can set an environment variable using a .env file. The documentation is here:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

Basically do something like this in the .env file at the project root.

REACT_APP_NOT_SECRET_CODE=abcdef

Note that the variable name must start with REACT_APP_

You can access it from your component with

process.env.REACT_APP_NOT_SECRET_CODE

How to create a new component in Angular 4 using CLI

If you want to create new component without .spec file, you can use

ng g c component-name --spec false

You can find these options using ng g c --help

Parameter in like clause JPQL

Use JpaRepository or CrudRepository as repository interface:

@Repository
public interface CustomerRepository extends JpaRepository<Customer, Integer> {

    @Query("SELECT t from Customer t where LOWER(t.name) LIKE %:name%")
    public List<Customer> findByName(@Param("name") String name);

}


@Service(value="customerService")
public class CustomerServiceImpl implements CustomerService {

    private CustomerRepository customerRepository;
    
    //...

    @Override
    public List<Customer> pattern(String text) throws Exception {
        return customerRepository.findByName(text.toLowerCase());
    }
}

Android: How to stretch an image to the screen width while maintaining aspect ratio?

ScaleType.CENTER_CROP will do what you want: stretch to full width, and scale the height accordingly. if the scaled height exceeds the screen limits, the image will be cropped.

What character represents a new line in a text area

Talking specifically about textareas in web forms, for all textareas, on all platforms, \r\n will work.

If you use anything else you will cause issues with cut and paste on Windows platforms.

The line breaks will be canonicalised by windows browsers when the form is submitted, but if you send the form down to the browser with \n linebreaks, you will find that the text will not copy and paste correctly between for example notepad and the textarea.

Interestingly, in spite of the Unix line end convention being \n, the standard in most text-based network protocols including HTTP, SMTP, POP3, IMAP, and so on is still \r\n. Yes, it may not make a lot of sense, but that's history and evolving standards for you!

Counting Line Numbers in Eclipse

I think if you have MyEclipse, it adds a label to the Project Properties page which contains the total number of source code lines. Might not help you as MyEclipse is not free though.

Unfortunately, that wasn't enough in my case so I wrote a source analyzer to gather statistics not gathered by other solutions (for example the metrics mentioned by AlbertoPL).

Return from lambda forEach() in java

You can also throw an exception:

Note:

For the sake of readability each step of stream should be listed in new line.

players.stream()
       .filter(player -> player.getName().contains(name))
       .findFirst()
       .orElseThrow(MyCustomRuntimeException::new);

if your logic is loosely "exception driven" such as there is one place in your code that catches all exceptions and decides what to do next. Only use exception driven development when you can avoid littering your code base with multiples try-catch and throwing these exceptions are for very special cases that you expect them and can be handled properly.)

css label width not taking effect

Do display: inline-block:

#report-upload-form label {
    padding-left:26px;
    width:125px;
    text-transform: uppercase;
    display:inline-block
}

http://jsfiddle.net/aqMN4/

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Angular 2 two way binding using ngModel is not working

Add below code to following files.

app.component.ts

<input type="text" [(ngModel)]="fname" >
{{fname}}
export class appcomponent {
fname:any;
}

app.module.ts

import {FormsModule} from '@angular/forms';
@NgModule({
imports: [ BrowserModule,FormsModule ],
declarations: [ AppComponent],
bootstrap:    [ AppComponent ]
})

Hope this helps

How to set IE11 Document mode to edge as default?

I've come across this problem myself. In my case, resetting IE was the quickest solution to the problem:

http://support.microsoft.com/kb/923737

Splitting a string into chunks of a certain size

Based around other posters answers, along with some samples of useage:

public static string FormatSortCode(string sortCode)
{
    return ChunkString(sortCode, 2, "-");
}
public static string FormatIBAN(string iban)
{
    return ChunkString(iban, 4, "&nbsp;&nbsp;");
}

private static string ChunkString(string str, int chunkSize, string separator)
{
    var b = new StringBuilder();
    var stringLength = str.Length;
    for (var i = 0; i < stringLength; i += chunkSize)
    {
        if (i + chunkSize > stringLength) chunkSize = stringLength - i;
        b.Append(str.Substring(i, chunkSize));
        if (i+chunkSize != stringLength)
            b.Append(separator);
    }
    return b.ToString();
}

Tracking changes in Windows registry

When using a VM, I use these steps to inspect changes to the registry:

  1. Using 7-Zip, open the vdi/vhd/vmdk file and extract the folder C:\Windows\System32\config
  2. Run OfflineRegistryView to convert the registry to plaintext
    • Set the 'Config Folder' to the folder you extracted
    • Set the 'Base Key' to HKLM\SYSTEM or HKLM\SOFTWARE
    • Set the 'Subkey Depth' to 'Unlimited'
    • Press the 'Go' button

Now use your favourite diff program to compare the 'before' and 'after' snapshots.

Is there a Google Chrome-only CSS hack?

Sure is:

@media screen and (-webkit-min-device-pixel-ratio:0)
{ 
    #element { properties:value; } 
}

And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/

Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.

Also, these hacks may not be future proof.

Calculate the mean by group

2015 update with dplyr:

df %>% group_by(dive) %>% summarise(percentage = mean(speed))
Source: local data frame [2 x 2]

   dive percentage
1 dive1  0.4777462
2 dive2  0.6726483

video as site background? HTML 5

First, your HTML markup looks like this:

<video id="awesome_video" src="first_video.mp4" autoplay />

Second, your JavaScript code will look like this:

<script type="text/javascript">
  var index = 1,
      playlist = ['first_video.mp4', 'second_video.mp4', 'third_video.mp4'],
      video = document.getElementById('awesome_video');

  video.addEventListener('ended', rotate_video, false);

  function rotate_video() {
    video.setAttribute('src', playlist[index]);
    video.load();
    index++;
    if (index >= playlist.length) { index = 0; }
  }
</script>

And last but not least, your CSS:

#awesome_video { position: absolute; top: 0; left: 0; width: 100%; height: 100%; }

This will create a video element on your page that starts playing the first video right away, then iterates through the playlist defined by the JavaScript variable. Your mileage with the CSS may vary depending on the CSS for the rest of the site, but 100% width/height should do it on a basic page.

Node.js: printing to console without a trailing newline?

None of these solutions work for me, process.stdout.write('ok\033[0G') and just using '\r' just create a new line but don't overwrite on Mac OSX 10.9.2.

EDIT: I had to use this to replace the current line:

process.stdout.write('\033[0G');
process.stdout.write('newstuff');

Calculate the number of business days between two dates?

 public enum NonWorkingDays { SaturdaySunday = 0, FridaySaturday = 1 };
        public int getBusinessDates(DateTime dateSt, DateTime dateNd, NonWorkingDays nonWorkingDays = NonWorkingDays.SaturdaySunday)
        {
            List<DateTime> datelist = new List<DateTime>();
            while (dateSt.Date < dateNd.Date)
            {
                datelist.Add((dateSt = dateSt.AddDays(1)));
            }
            if (nonWorkingDays == NonWorkingDays.SaturdaySunday)
            {
                return datelist.Count(d => d.DayOfWeek != DayOfWeek.Saturday &&
                       d.DayOfWeek != DayOfWeek.Friday);
            }
            else
            {
                return datelist.Count(d => d.DayOfWeek != DayOfWeek.Friday &&
                       d.DayOfWeek != DayOfWeek.Saturday);
            }
        }

How to convert a time string to seconds?

import time
from datetime import datetime

t1 = datetime.now().replace(microsecond=0)
time.sleep(3)
now = datetime.now().replace(microsecond=0)
print((now - t1).total_seconds())

result: 3.0

AssertionError: View function mapping is overwriting an existing endpoint function: main

If you think you have unique endpoint names and still this error is given then probably you are facing issue. Same was the case with me.

This issue is with flask 0.10 in case you have same version then do following to get rid of this:

sudo pip uninstall flask
sudo pip install flask=0.9

Run PowerShell command from command prompt (no ps1 script)

Maybe powershell -Command "Get-AppLockerFileInformation....."

Take a look at powershell /?

Deleting an object in java?

//Just use a List
//create the list
public final List<Object> myObjects;

//instantiate the list
myObjects = new ArrayList<Object>();

//add objects to the list
Object object = myObject;
myObjects.add(object);

//remove the object calling this method if you have more than 1 objects still works with 1
//object too.

private void removeObject(){
int len = myObjects.size();
for(int i = 0;i<len; i++){
Objects object = myObjects.get(i);
myObjects.remove(object);
}
}

Eclipse: Enable autocomplete / content assist

For me, it helped after I changed the theme to 'mac' since I am running on a MacOSX.

Eclipse: >Preferences > General > Appearance > Choose 'Mac' from the menu.

React onClick function fires on render

JSX is used with ReactJS as it is very similar to HTML and it gives programmers feel of using HTML whereas it ultimately transpiles to a javascript file.

Writing a for-loop and specifying function as {this.props.removeTaskFunction(todo)} will execute the functions whenever the loop is triggered .

To stop this behaviour we need to return the function to onClick.

The fat arrow function has a hidden return statement along with the bind property. Thus it returns the function to OnClick as Javascript can return functions too !!!!!

Use -

onClick={() => { this.props.removeTaskFunction(todo) }}

which means-

var onClick = function() {
  return this.props.removeTaskFunction(todo);
}.bind(this);

How can I pass an argument to a PowerShell script?

Tested as working:

#Must be the first statement in your script (not coutning comments)
param([Int32]$step=30) 

$iTunes = New-Object -ComObject iTunes.Application

if ($iTunes.playerstate -eq 1)
{
  $iTunes.PlayerPosition = $iTunes.PlayerPosition + $step
}

Call it with

powershell.exe -file itunesForward.ps1 -step 15

Multiple parameters syntax (comments are optional, but allowed):

<#
    Script description.

    Some notes.
#>
param (
    # height of largest column without top bar
    [int]$h = 4000,
    
    # name of the output image
    [string]$image = 'out.png'
)

Clear the form field after successful submission of php form

I was just trying to fix same error, I finally fixed it, so I will copy to you part of the code, maybe it helps you.

<input type="text" name="usu" id="usu" value="<?php echo $usu;?>" ></input>
<input type="text" name="pass" id="pass" value="<?php echo $varpass;?>"></input>  

those are the inputs I wanted to clean after pressing my button.

And here php code:

$query= "INSERT INTO usuarios (tipo, usuario, password) VALUES ('".$vartipo."', '".$usu."', '".$varpass."')";


        if (!mysqli_query($conexion,$query)){

            die('Error: ' . mysqli_error($conexion));
        }

        else{


            $usu = '';  
            $varpass= '';   

            $result = '<div class="result_ok">El usuario se ha registrado con éxito! <div>';        


        }

$usu = '';
$varpass= '';

those are the lines that cleans the inputs :D

Xcode 10, Command CodeSign failed with a nonzero exit code

May sound stupid, but, try with no password, when it asked.

How do I get a specific range of numbers from rand()?

I think the following does it semi right. It's been awhile since I've touched C. The idea is to use division since modulus doesn't always give random results. I added 1 to RAND_MAX since there are that many possible values coming from rand including 0. And since the range is also 0 inclusive, I added 1 there too. I think the math is arranged correctly avoid integer math problems.

#define MK_DIVISOR(max) ((int)((unsigned int)RAND_MAX+1/(max+1)))

num = rand()/MK_DIVISOR(65);

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

The microsoft telnet.exe is not scriptable without using another script (which needs keyboard focus), as shown in another answer to this question, but there is a free

Telnet Scripting Tool v.1.0 by Albert Yale

that you can google for and which is both scriptable and loggable and can be launched from a batch file without needing keyboard focus.

The problem with telnet.exe and a second script when keyboard focus is being used is that if someone is using the computer at the time the script runs, then it is highly likely that the script will fail due to mouse clicks and keyboard use at that moment in time.

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

What's the Use of '\r' escape sequence?

The program is printing "Hey this is my first hello world ", then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.

Why is MySQL InnoDB insert so slow?

InnoDB doesn't cope well with 'random' primary keys. Try a sequential key or auto-increment, and I believe you'll see better performance. Your 'real' key field could still be indexed, but for a bulk insert you might be better off dropping and recreating that index in one hit after the insert in complete. Would be interested to see your benchmarks for that!

Some related questions

MySQL Workbench not opening on Windows

it might be due to running of xampp or wampp server stop all services running and try to open mysql command line

Javascript string replace with regex to strip off illegal characters

You need to wrap them all in a character class. The current version means replace this sequence of characters with an empty string. When wrapped in square brackets it means replace any of these characters with an empty string.

var cleanString = dirtyString.replace(/[\|&;\$%@"<>\(\)\+,]/g, "");

How to increase the clickable area of a <a> tag button?

Big thanks to the contributors to the answers here, it pointed me in the right direction.

For the Bootstrap4 users out there, this worked for me. Sets the a link (tap target) to correct size to pass the Lighthouse Site Audit on mobiles.

    <span class="small">
         <a class="d-inline position-relative p-3 m-n3" style="z-index: 1;" href="/AdvancedSearch" title="Advanced Site Search using extra optional filters">Advanced Site Search</a>
    </span>

Receiving login prompt using integrated windows authentication

Have you tried logging in with your domain prefix, e.g. DOMAIN\Username? IIS 6 defaults to using the host computer as the default domain so specifying the domain at logon may solve the problem.

How to make a class JSON serializable

This class can do the trick, it converts object to standard json .

import json


class Serializer(object):
    @staticmethod
    def serialize(object):
        return json.dumps(object, default=lambda o: o.__dict__.values()[0])

usage:

Serializer.serialize(my_object)

working in python2.7 and python3.

Add 2 hours to current time in MySQL?

The DATE_ADD() function will do the trick. (You can also use the ADDTIME() function if you're running at least v4.1.1.)

For your query, this would be:

SELECT * 
FROM courses 
WHERE DATE_ADD(now(), INTERVAL 2 HOUR) > start_time

Or,

SELECT * 
FROM courses 
WHERE ADDTIME(now(), '02:00:00') > start_time

android - How to get view from context?

In your broadcast receiver you could access a view via inflation a root layout from XML resource and then find all your views from this root layout with findViewByid():

View view = View.inflate(context, R.layout.ROOT_LAYOUT, null);

Now you can access your views via 'view' and cast them to your view type:

myImage = (ImageView) view.findViewById(R.id.my_image);

Where does npm install packages?

In earlier versions of NPM modules were always placed in /usr/local/lib/node or wherever you specified the npm root within the .npmrc file. However, in NPM 1.0+ modules are installed in two places. You can have modules installed local to your application in /.node_modules or you can have them installed globally which will use the above.

More information can be found at https://github.com/isaacs/npm/blob/master/doc/install.md

How to get week number of the month from the date in sql server 2008

WeekMonth = CASE WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 22 THEN '5' 
                 WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 15 THEN '4' 
                 WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 8 THEN '3'
                 WHEN (DATEPART(day,TestDate) - datepart(dw,TestDate))>= 1 THEN '2' 
                 ELSE '1'
             END 

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

 protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            //foreach (var relationship in modelBuilder.Model.GetEntityTypes().SelectMany(e => e.GetForeignKeys()))
            //    relationship.DeleteBehavior = DeleteBehavior.Restrict;

            modelBuilder.Entity<User>().ToTable("Users");

            modelBuilder.Entity<IdentityRole<string>>().ToTable("Roles");
            modelBuilder.Entity<IdentityUserToken<string>>().ToTable("UserTokens");
            modelBuilder.Entity<IdentityUserClaim<string>>().ToTable("UserClaims");
            modelBuilder.Entity<IdentityUserLogin<string>>().ToTable("UserLogins");
            modelBuilder.Entity<IdentityRoleClaim<string>>().ToTable("RoleClaims");
            modelBuilder.Entity<IdentityUserRole<string>>().ToTable("UserRoles");

        }
    }

How to set back button text in Swift

Swift 4

In my case the solution was to clear the navigation item of the Master View Controller before move to the Child View Controller. And set it again if it is shown again

MasterController

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    navigationItem.title = "Master Title"
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    navigationItem.title = ""
}

And this is how I push a UIViewController and clear the back bar button item in the child controller:

MasterController

let childController = ChildController(collectionViewLayout: UICollectionViewFlowLayout())
childController.navigationItem.backBarButtonItem?.title = ""
navigationController?.pushViewController(childController, animated: true)

Stretch background image css?

Just paste this into your line of codes:

<meta http-equiv="X-UA-Compatible" content="IE=Edge" />

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

I had another case that caused an ERR_HTTP2_PROTOCOL_ERROR that hasn't been mentioned here yet. I had created a cross reference in IOC (Unity), where I had class A referencing class B (through a couple of layers), and class B referencing class A. Bad design on my part really. But I created a new interface/class for the method in class A that I was calling from class B, and that cleared it up.

remove space between paragraph and unordered list

I ended up using a definition list with an unordered list inside it. It solves the issue of the unwanted space above the list without needing to change every paragraph tag.

<dl><dt>Text</dt>
<dd><ul><li>First item</li>
<li>Second item</li></ul></dd></dl>

How to install npm peer dependencies automatically?

The automatic install of peer dependencies was explicitly removed with npm 3, as it cause more problems than it tried to solve. You can read about it here for example:

So no, for the reasons given, you cannot install them automatically with npm 3 upwards.

NPM V7

NPM v7 has reintroduced the automatic peerDependencies installation. They had made some changes to fix old problems as version compatibility across multiple dependants. You can see the discussion here and the announcement here

Now in V7, as in versions before V3, you only need to do an npm i and all peerDependences should be automatically installed.

Passing in class names to react components

As other have stated, use an interpreted expression with curly braces.

But do not forget to set a default.
Others has suggested using a OR statement to set a empty string if undefined.

But it would be even better to declare your Props.

Full example:

import React, { Component } from 'react';
import PropTypes from 'prop-types';

class Pill extends Component {

  render() {

    return (
      <button className={`pill ${ this.props.className }`}>{this.props.children}</button>
    );
  }

}

Pill.propTypes = {
  className: PropTypes.string,
};

Pill.defaultProps = {
  className: '',
};

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

A quick solution to get me going was to uncheck the "Sign the ClickOnce manifests" in: Project -> (project name)Properties -> Signing Tab

How can you float: right in React Native?

why does the Text take up the full space of the View, instead of just the space for "Hello"?

Because the View is a flex container and by default has flexDirection: 'column' and alignItems: 'stretch', which means that its children should be stretched out to fill its width.

(Note, per the docs, that all components in React Native are display: 'flex' by default and that display: 'inline' does not exist at all. In this way, the default behaviour of a Text within a View in React Native differs from the default behaviour of span within a div on the web; in the latter case, the span would not fill the width of the div because a span is an inline element by default. There is no such concept in React Native.)

How can the Text be floated / aligned to the right?

The float property doesn't exist in React Native, but there are loads of options available to you (with slightly different behaviours) that will let you right-align your text. Here are the ones I can think of:

1. Use textAlign: 'right' on the Text element

<View>
  <Text style={{textAlign: 'right'}}>Hello, World!</Text>
</View>

(This approach doesn't change the fact that the Text fills the entire width of the View; it just right-aligns the text within the Text.)

2. Use alignSelf: 'flex-end' on the Text

<View>
  <Text style={{alignSelf: 'flex-end'}}>Hello, World!</Text>
</View>

This shrinks the Text element to the size required to hold its content and puts it at the end of the cross direction (the horizontal direction, by default) of the View.

3. Use alignItems: 'flex-end' on the View

<View style={{alignItems: 'flex-end'}}>
  <Text>Hello, World!</Text>
</View>

This is equivalent to setting alignSelf: 'flex-end' on all the View's children.

4. Use flexDirection: 'row' and justifyContent: 'flex-end' on the View

<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
  <Text>Hello, World!</Text>
</View>

flexDirection: 'row' sets the main direction of layout to be horizontal instead of vertical; justifyContent is just like alignItems, but controls alignment in the main direction instead of the cross direction.

5. Use flexDirection: 'row' on the View and marginLeft: 'auto' on the Text

<View style={{flexDirection: 'row'}}>
  <Text style={{marginLeft: 'auto'}}>Hello, World!</Text>
</View>

This approach is demonstrated, in the context of the web and real CSS, at https://stackoverflow.com/a/34063808/1709587.

6. Use position: 'absolute' and right: 0 on the Text:

<View>
  <Text style={{position: 'absolute', right: 0}}>Hello, World!</Text>
</View>

Like in real CSS, this takes the Text "out of flow", meaning that its siblings will be able to overlap it and its vertical position will be at the top of the View by default (although you can explicitly set a distance from the top of the View using the top style property).


Naturally, which of these various approaches you want to use - and whether the choice between them even matters at all - will depend upon your precise circumstances.

Prevent flicker on webkit-transition of webkit-transform

Trigger hardware accelerated rendering for the problematic element. I would advice to not do this on *, body or html tags for performance.

.problem{
  -webkit-transform:translate3d(0,0,0);
}

How to resize an image with OpenCV2.0 and Python2.6

If you wish to use CV2, you need to use the resize function.

For example, this will resize both axes by half:

small = cv2.resize(image, (0,0), fx=0.5, fy=0.5) 

and this will resize the image to have 100 cols (width) and 50 rows (height):

resized_image = cv2.resize(image, (100, 50)) 

Another option is to use scipy module, by using:

small = scipy.misc.imresize(image, 0.5)

There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).


Update:
According to the SciPy documentation:

imresize is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use skimage.transform.resize instead.

Note that if you're looking to resize by a factor, you may actually want skimage.transform.rescale.

Benefits of EBS vs. instance-store (and vice-versa)

99% of our AWS setup is recyclable. So for me it doesn't really matter if I terminate an instance -- nothing is lost ever. E.g. my application is automatically deployed on an instance from SVN, our logs are written to a central syslog server.

The only benefit of instance storage that I see are cost-savings. Otherwise EBS-backed instances win. Eric mentioned all the advantages.


[2012-07-16] I would phrase this answer a lot different today.

I haven't had any good experience with EBS-backed instances in the past year or so. The last downtimes on AWS pretty much wrecked EBS as well.

I am guessing that a service like RDS uses some kind of EBS as well and that seems to work for the most part. On the instances we manage ourselves, we have got rid off EBS where possible.

Getting rid to an extend where we moved a database cluster back to iron (= real hardware). The only remaining piece in our infrastructure is a DB server where we stripe multiple EBS volumes into a software RAID and backup twice a day. Whatever would be lost in between backups, we can live with.

EBS is a somewhat flakey technology since it's essentially a network volume: a volume attached to your server from remote. I am not negating the work done with it – it is an amazing product since essentially unlimited persistent storage is just an API call away. But it's hardly fit for scenarios where I/O performance is key.

And in addition to how network storage behaves, all network is shared on EC2 instances. The smaller an instance (e.g. t1.micro, m1.small) the worse it gets because your network interfaces on the actual host system are shared among multiple VMs (= your EC2 instance) which run on top of it.

The larger instance you get, the better it gets of course. Better here means within reason.

When persistence is required, I would always advice people to use something like S3 to centralize between instances. S3 is a very stable service. Then automate your instance setup to a point where you can boot a new server and it gets ready by itself. Then there is no need to have network storage which lives longer than the instance.

So all in all, I see no benefit to EBS-backed instances what so ever. I rather add a minute to bootstrap, then run with a potential SPOF.

List comprehension on a nested list?

Here is how you would do this with a nested list comprehension:

[[float(y) for y in x] for x in l]

This would give you a list of lists, similar to what you started with except with floats instead of strings. If you want one flat list then you would use [float(y) for x in l for y in x].

AndroidStudio: Failed to sync Install build tools

based on your screenshot I can see you have BuildTools ver 23.0.0 rc2 installed. So to get it right open up your gradle build file "build.gradle(Module:app)" and edit buildToolsVersion part like that:

android {
    compileSdkVersion 22
    buildToolsVersion "23.0.0 rc2"
}

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

Here are a couple links for reference.

HEAD and ORIG_HEAD in Git

From git reset

"pull" or "merge" always leaves the original tip of the current branch in ORIG_HEAD.

git reset --hard ORIG_HEAD

Resetting hard to it brings your index file and the working tree back to that state, and resets the tip of the branch to that commit.

git reset --merge ORIG_HEAD

After inspecting the result of the merge, you may find that the change in the other branch is unsatisfactory. Running "git reset --hard ORIG_HEAD" will let you go back to where you were, but it will discard your local changes, which you do not want. "git reset --merge" keeps your local changes.


Before any patches are applied, ORIG_HEAD is set to the tip of the current branch.
This is useful if you have problems with multiple commits, like running 'git am' on the wrong branch or an error in the commits that is more easily fixed by changing the mailbox (e.g. +errors in the "From:" lines).

In addition, merge always sets '.git/ORIG_HEAD' to the original state of HEAD so a problematic merge can be removed by using 'git reset ORIG_HEAD'.


Note: from here

HEAD is a moving pointer. Sometimes it means the current branch, sometimes it doesn't.

So HEAD is NOT a synonym for "current branch" everywhere already.

HEAD means "current" everywhere in git, but it does not necessarily mean "current branch" (i.e. detached HEAD).

But it almost always means the "current commit".
It is the commit "git commit" builds on top of, and "git diff --cached" and "git status" compare against.
It means the current branch only in very limited contexts (exactly when we want a branch name to operate on --- resetting and growing the branch tip via commit/rebase/etc.).

Reflog is a vehicle to go back in time and time machines have interesting interaction with the notion of "current".

HEAD@{5.minutes.ago} could mean "dereference HEAD symref to find out what branch we are on RIGHT NOW, and then find out where the tip of that branch was 5 minutes ago".
Alternatively it could mean "what is the commit I would have referred to as HEAD 5 minutes ago, e.g. if I did "git show HEAD" back then".


git1.8.4 (July 2013) introduces introduced a new notation!
(Actually, it will be for 1.8.5, Q4 2013: reintroduced with commit 9ba89f4), by Felipe Contreras.

Instead of typing four capital letters "HEAD", you can say "@" now,
e.g. "git log @".

See commit cdfd948

Typing 'HEAD' is tedious, especially when we can use '@' instead.

The reason for choosing '@' is that it follows naturally from the ref@op syntax (e.g. HEAD@{u}), except we have no ref, and no operation, and when we don't have those, it makes sens to assume 'HEAD'.

So now we can use 'git show @~1', and all that goody goodness.

Until now '@' was a valid name, but it conflicts with this idea, so let's make it invalid. Probably very few people, if any, used this name.