Programs & Examples On #Facebook sharer

The Facebook Share button lets people add a personalized message to links before sharing on their timeline, in groups, or to their friends via a Facebook Message

How to pass a parameter like title, summary and image in a Facebook sharer URL

I've used the below before, and it has worked. It isn't very pretty, but you can alter it to suit your needs.

The following JavaScript function grabs the location.href & document.title for the sharer, and you can ultimately change these.

function fbs_click() {
        u=location.href;
        t=document.title;
window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),
                'sharer',
                'toolbar=0,status=0,width=626,height=436');

            return false;
        }

Usage:

<a rel="nofollow" href="http://www.facebook.com/share.php?u=<;url>" onclick="return fbs_click()" target="_blank">
    Share on Facebook
</a>

It looks like this is what you could possibly be looking for: Facebook sharer title / desc....

How does Facebook Sharer select Images and other metadata when sharing my URL?

Old way, no longer works:

<link rel="image_src" href="http://yoururl/yourimage"/>

Reported new way, also does not work:

<meta property="og:image" content="http://yoururl/yourimage"/>

It randomly worked off and on during the first day I implemented it, hasn't worked at all since.

The Facebook linter page, a utility that inspects your page, reports that everything is correct and does display the thumbnail I selected... just that the share.php page itself doesn't seem to be functioning. Has to be a bug over at Facebook, one they apparently don't care to fix as every bug report regarding this issue I've seen in their system all say resolved or fixed.

Facebook share link without JavaScript

For those that wish to use javascript but do not want to use the Facebook javascript library:

<a id="shareFB" href="https://www.facebook.com/sharer/sharer.php?u=URLENCODED_URL&t=TITLE"
   onclick="javascript:window.open(this.href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,height=300,width=600');return false;"   target="_blank" title="Share on Facebook">Share on Facebook</a>
<script type="text/javascript">document.getElementById("shareFB").setAttribute("href", "https://www.facebook.com/sharer/sharer.php?u=" + document.URL);</script>

Works even if javascript is disabled, but gives you a popup window with share preview if javascript is enabled.

Saves one needles click while not using any Facebook js spyware :)

Want custom title / image / description in facebook share link from a flash app

I actually have a similar problem. I have a page with multiple radio buttons; each button will set the title and description meta tags of the page, via JavaScript upon change.

For example, if users select the first button, the meta tags will say:

<meta name="title" content="First Title">
<meta name="description" content="First Description">

If the user select the second button, this changes the meta tags to:

<meta name="title" content="Second Title">
<meta name="description" content="Second Description">

... and so on. I have confirmed that the code is working fine via Firebug (i.e. I can see that those two tags were properly changed).

Apparently, Facebook Share only pulls in the title and description meta tags that are available upon page load. The changes to those two tags post page load are completely ignored.

Does anybody have any ideas on how to solve this? That is, to force Facebook to get the latest values that are change after the page loads.

Facebook key hash does not match any stored key hashes

This is a case that could have possibly occurred and what solved my error:

In the https://developers.facebook.com/quickstarts after you run

OSX/Linux:

keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64

Windows:

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%\.android\debug.keystore | openssl sha1 -binary | openssl base64

When Enter keystore password: is asked you may have accidentally typed a wrong password, the default password is "android". Typing any other password will give you a different/wrong hash key. Paste the correct hash key in the Key Hashes field on your app page

This solved my problem, hope this helps whoever made this particular error that I made

Task.Run with Parameter(s)?

From now you can also :

Action<int> action = (o) => Thread.Sleep(o);
int param = 10;
await new TaskFactory().StartNew(action, param)

Typescript Date Type?

Every class or interface can be used as a type in TypeScript.

 const date = new Date();

will already know about the date type definition as Date is an internal TypeScript object referenced by the DateConstructor interface.

And for the constructor you used, it is defined as:

interface DateConstructor {
    new(): Date;
    ...
}

To make it more explicit, you can use:

 const date: Date = new Date();

You might be missing the type definitions though, the Date is coming for my example from the ES6 lib, and in my tsconfig.json I have defined:

"compilerOptions": {
    "target": "ES6",
    "lib": [
        "es6",
        "dom"
    ],

You might adapt these settings to target your wanted version of JavaScript.


The Date is by the way an Interface from lib.es6.d.ts:

/** Enables basic storage and retrieval of dates and times. */
interface Date {
    /** Returns a string representation of a date. The format of the string depends on the locale. */
    toString(): string;
    /** Returns a date as a string value. */
    toDateString(): string;
    /** Returns a time as a string value. */
    toTimeString(): string;
    /** Returns a value as a string value appropriate to the host environment's current locale. */
    toLocaleString(): string;
    /** Returns a date as a string value appropriate to the host environment's current locale. */
    toLocaleDateString(): string;
    /** Returns a time as a string value appropriate to the host environment's current locale. */
    toLocaleTimeString(): string;
    /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
    valueOf(): number;
    /** Gets the time value in milliseconds. */
    getTime(): number;
    /** Gets the year, using local time. */
    getFullYear(): number;
    /** Gets the year using Universal Coordinated Time (UTC). */
    getUTCFullYear(): number;
    /** Gets the month, using local time. */
    getMonth(): number;
    /** Gets the month of a Date object using Universal Coordinated Time (UTC). */
    getUTCMonth(): number;
    /** Gets the day-of-the-month, using local time. */
    getDate(): number;
    /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
    getUTCDate(): number;
    /** Gets the day of the week, using local time. */
    getDay(): number;
    /** Gets the day of the week using Universal Coordinated Time (UTC). */
    getUTCDay(): number;
    /** Gets the hours in a date, using local time. */
    getHours(): number;
    /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
    getUTCHours(): number;
    /** Gets the minutes of a Date object, using local time. */
    getMinutes(): number;
    /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
    getUTCMinutes(): number;
    /** Gets the seconds of a Date object, using local time. */
    getSeconds(): number;
    /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
    getUTCSeconds(): number;
    /** Gets the milliseconds of a Date, using local time. */
    getMilliseconds(): number;
    /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
    getUTCMilliseconds(): number;
    /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
    getTimezoneOffset(): number;
    /**
      * Sets the date and time value in the Date object.
      * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
      */
    setTime(time: number): number;
    /**
      * Sets the milliseconds value in the Date object using local time.
      * @param ms A numeric value equal to the millisecond value.
      */
    setMilliseconds(ms: number): number;
    /**
      * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
      * @param ms A numeric value equal to the millisecond value.
      */
    setUTCMilliseconds(ms: number): number;

    /**
      * Sets the seconds value in the Date object using local time.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setSeconds(sec: number, ms?: number): number;
    /**
      * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCSeconds(sec: number, ms?: number): number;
    /**
      * Sets the minutes value in the Date object using local time.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setMinutes(min: number, sec?: number, ms?: number): number;
    /**
      * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCMinutes(min: number, sec?: number, ms?: number): number;
    /**
      * Sets the hour value in the Date object using local time.
      * @param hours A numeric value equal to the hours value.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setHours(hours: number, min?: number, sec?: number, ms?: number): number;
    /**
      * Sets the hours value in the Date object using Universal Coordinated Time (UTC).
      * @param hours A numeric value equal to the hours value.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
    /**
      * Sets the numeric day-of-the-month value of the Date object using local time.
      * @param date A numeric value equal to the day of the month.
      */
    setDate(date: number): number;
    /**
      * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
      * @param date A numeric value equal to the day of the month.
      */
    setUTCDate(date: number): number;
    /**
      * Sets the month value in the Date object using local time.
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
      * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
      */
    setMonth(month: number, date?: number): number;
    /**
      * Sets the month value in the Date object using Universal Coordinated Time (UTC).
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
      * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
      */
    setUTCMonth(month: number, date?: number): number;
    /**
      * Sets the year of the Date object using local time.
      * @param year A numeric value for the year.
      * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
      * @param date A numeric value equal for the day of the month.
      */
    setFullYear(year: number, month?: number, date?: number): number;
    /**
      * Sets the year value in the Date object using Universal Coordinated Time (UTC).
      * @param year A numeric value equal to the year.
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
      * @param date A numeric value equal to the day of the month.
      */
    setUTCFullYear(year: number, month?: number, date?: number): number;
    /** Returns a date converted to a string using Universal Coordinated Time (UTC). */
    toUTCString(): string;
    /** Returns a date as a string value in ISO format. */
    toISOString(): string;
    /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
    toJSON(key?: any): string;
}

How do I remove the "extended attributes" on a file in Mac OS X?

Another recursive approach:

# change directory to target folder:
cd /Volumes/path/to/folder

# find all things of type "f" (file), 
# then pipe "|" each result as an argument (xargs -0) 
# to the "xattr -c" command:
find . -type f -print0 | xargs -0 xattr -c

# Sometimes you may have to use a star * instead of the dot.
# The dot just means "here" (whereever your cd'd to
find * -type f -print0 | xargs -0 xattr -c

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

I was getting similar error in VS2017 while trying to publish my solution to Azure.

This algorithm helped me to resolve it:

  1. Close VS2017
  2. Open C:\Users{your user name}\AppData\Local\Microsoft\VisualStudio\ folder
  3. Rename 15.0_08edcd83 folder
  4. Start VS
  5. Publish works fine!

Note that this will remove your Visual Studio's recent files / projects from it's history and also linking to MS account.

This method is slightly different from the Top answer. Here you don't have to delete other folders except renaming abovementioned one.

VB.NET - Remove a characters from a String

Function RemoveCharacter(ByVal stringToCleanUp, ByVal characterToRemove)
  ' replace the target with nothing
  ' Replace() returns a new String and does not modify the current one
  Return stringToCleanUp.Replace(characterToRemove, "")
End Function

Here's more information about VB's Replace function

HTTP requests and JSON parsing in Python

I recommend using the awesome requests library:

import requests

url = 'http://maps.googleapis.com/maps/api/directions/json'

params = dict(
    origin='Chicago,IL',
    destination='Los+Angeles,CA',
    waypoints='Joplin,MO|Oklahoma+City,OK',
    sensor='false'
)

resp = requests.get(url=url, params=params)
data = resp.json() # Check the JSON Response Content documentation below

JSON Response Content: https://requests.readthedocs.io/en/master/user/quickstart/#json-response-content

How do I use the nohup command without getting nohup.out?

The nohup command only writes to nohup.out if the output would otherwise go to the terminal. If you have redirected the output of the command somewhere else - including /dev/null - that's where it goes instead.

 nohup command >/dev/null 2>&1   # doesn't create nohup.out

If you're using nohup, that probably means you want to run the command in the background by putting another & on the end of the whole thing:

 nohup command >/dev/null 2>&1 & # runs in background, still doesn't create nohup.out

On Linux, running a job with nohup automatically closes its input as well. On other systems, notably BSD and macOS, that is not the case, so when running in the background, you might want to close input manually. While closing input has no effect on the creation or not of nohup.out, it avoids another problem: if a background process tries to read anything from standard input, it will pause, waiting for you to bring it back to the foreground and type something. So the extra-safe version looks like this:

nohup command </dev/null >/dev/null 2>&1 & # completely detached from terminal 

Note, however, that this does not prevent the command from accessing the terminal directly, nor does it remove it from your shell's process group. If you want to do the latter, and you are running bash, ksh, or zsh, you can do so by running disown with no argument as the next command. That will mean the background process is no longer associated with a shell "job" and will not have any signals forwarded to it from the shell. (Note the distinction: a disowned process gets no signals forwarded to it automatically by its parent shell - but without nohup, it will still receive a HUP signal sent via other means, such as a manual kill command. A nohup'ed process ignores any and all HUP signals, no matter how they are sent.)

Explanation:

In Unixy systems, every source of input or target of output has a number associated with it called a "file descriptor", or "fd" for short. Every running program ("process") has its own set of these, and when a new process starts up it has three of them already open: "standard input", which is fd 0, is open for the process to read from, while "standard output" (fd 1) and "standard error" (fd 2) are open for it to write to. If you just run a command in a terminal window, then by default, anything you type goes to its standard input, while both its standard output and standard error get sent to that window.

But you can ask the shell to change where any or all of those file descriptors point before launching the command; that's what the redirection (<, <<, >, >>) and pipe (|) operators do.

The pipe is the simplest of these... command1 | command2 arranges for the standard output of command1 to feed directly into the standard input of command2. This is a very handy arrangement that has led to a particular design pattern in UNIX tools (and explains the existence of standard error, which allows a program to send messages to the user even though its output is going into the next program in the pipeline). But you can only pipe standard output to standard input; you can't send any other file descriptors to a pipe without some juggling.

The redirection operators are friendlier in that they let you specify which file descriptor to redirect. So 0<infile reads standard input from the file named infile, while 2>>logfile appends standard error to the end of the file named logfile. If you don't specify a number, then input redirection defaults to fd 0 (< is the same as 0<), while output redirection defaults to fd 1 (> is the same as 1>).

Also, you can combine file descriptors together: 2>&1 means "send standard error wherever standard output is going". That means that you get a single stream of output that includes both standard out and standard error intermixed with no way to separate them anymore, but it also means that you can include standard error in a pipe.

So the sequence >/dev/null 2>&1 means "send standard output to /dev/null" (which is a special device that just throws away whatever you write to it) "and then send standard error to wherever standard output is going" (which we just made sure was /dev/null). Basically, "throw away whatever this command writes to either file descriptor".

When nohup detects that neither its standard error nor output is attached to a terminal, it doesn't bother to create nohup.out, but assumes that the output is already redirected where the user wants it to go.

The /dev/null device works for input, too; if you run a command with </dev/null, then any attempt by that command to read from standard input will instantly encounter end-of-file. Note that the merge syntax won't have the same effect here; it only works to point a file descriptor to another one that's open in the same direction (input or output). The shell will let you do >/dev/null <&1, but that winds up creating a process with an input file descriptor open on an output stream, so instead of just hitting end-of-file, any read attempt will trigger a fatal "invalid file descriptor" error.

Adding a rule in iptables in debian to open a new port

About your command line:

root@debian:/# sudo iptables -A INPUT -p tcp --dport 3306 --jump ACCEPT
root@debian:/# iptables-save
  • You are already authenticated as root so sudo is redundant there.

  • You are missing the -j or --jump just before the ACCEPT parameter (just tought that was a typo and you are inserting it correctly).

About yout question:

If you are inserting the iptables rule correctly as you pointed it in the question, maybe the issue is related to the hypervisor (virtual machine provider) you are using.

If you provide the hypervisor name (VirtualBox, VMWare?) I can further guide you on this but here are some suggestions you can try first:

check your vmachine network settings and:

  • if it is set to NAT, then you won't be able to connect from your base machine to the vmachine.

  • if it is set to Hosted, you have to configure first its network settings, it is usually to provide them an IP in the range 192.168.56.0/24, since is the default the hypervisors use for this.

  • if it is set to Bridge, same as Hosted but you can configure it whenever IP range makes sense for you configuration.

Hope this helps.

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Use this, works for me always.

Response.Redirect(Request.RawUrl, false);

Here, Response.Redirect(Request.RawUrl) simply redirects to the url of the current context, while the second parameter "false" indicates to either endResponse or not.

Read user input inside a loop

I have found this parameter -u with read.

"-u 1" means "read from stdin"

while read -r newline; do
    ((i++))
    read -u 1 -p "Doing $i""th file, called $newline. Write your answer and press Enter!"
    echo "Processing $newline with $REPLY" # united input from two different read commands.
done <<< $(ls)

How can a web application send push notifications to iOS devices?

While not yet supported on iOS (as of iOS 10), websites can send push notifications to Firefox and Chrome (Desktop/Android) with the Push API.

The Push API is used in conjunction with the older Web Notifications to display the message. The advantage is that the Push API allow the notification to be delivered even when the user is not surfing your website, because they are built upon Service Workers (scripts that are registered by the browser and can be executed in background at a later time even after your user has left your website).

The process of sending a notification involves the following:

  1. a user visits your website (must be secured over HTTPS): you ask permission to display push notifications and you register a service worker (a script that will be executed when a push notification is received)
  2. if the user has granted permission, you can read the device token (endpoint) which should be sent to the server and stored
  3. now you can send notifications to the user: your server makes an HTTP POST request to the endpoint (which is an URL that contains the device token). The server which receives the request is owned by the browser manufacturer (e.g. Google, Mozilla): the browser is constantly connected to it and can read the incoming notifications.
  4. when the user browser receives a notification executes the service worker, which is responsible for managing the event, retrieving the notification data from the server and displaying the notification to the user

The Push API is currently supported on desktop and Android by Chrome, Firefox and Opera.

You can also send push notifications to Apple / Safari desktop using APNs. The approach is similar, but with many complications (apple developer certificates, push packages, low-level TCP connection to APNs).

If you want to implement the push notifications by yourself start with these tutorials:

If you are looking for a drop in solution I would suggest Pushpad, which is a service I have built.

Update (September 2017): Apple has started developing the service workers for WebKit (status). Since the service workers are a fundamental technology for web push, this is a big step forward.

Sort an Array by keys based on another Array?

A bit late, but I couldn't find the way I implemented it, this version needs closure, php>=5.3, but could be altered not to:

$customer['address'] = '123 fake st';
$customer['name'] = 'Tim';
$customer['dob'] = '12/08/1986';
$customer['dontSortMe'] = 'this value doesnt need to be sorted';

$order = array('name', 'dob', 'address');

$keys= array_flip($order);
uksort($customer, function($a, $b)use($keys){
    return $keys[$a] - $keys[$b];
});
print_r($customer);

Of course 'dontSortMe' needs to be sorted out, and may appear first in the example

Replace transparency in PNG images with white background

This works for me:

convert -flatten img1.png img1-white.png

Documentation references:

Is there a way to use max-width and height for a background image?

As thirtydot said, you can use the CSS3 background-size syntax:

For example:

-o-background-size:35% auto;
-webkit-background-size:35% auto;
-moz-background-size:35% auto;
background-size:35% auto;

However, as also stated by thirtydot, this does not work in IE6, 7 and 8.

See the following links for more information about background-size: http://www.w3.org/TR/css3-background/#the-background-size

Method to find string inside of the text file. Then getting the following lines up to a certain limit

This will find "Mark Sagal" in Student.txt. Assuming Student.txt contains

Student.txt

Amir Amiri
Mark Sagal
Juan Delacruz

Main.java

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.ArrayList;

public class Main {
    public static void main(String[] args) {
        final String file = "Student.txt";
        String line = null;
        ArrayList<String> fileContents = new ArrayList<>();

        try {
            FileReader fReader = new FileReader(file);
            BufferedReader fileBuff = new BufferedReader(fReader);
            while ((line = fileBuff.readLine()) != null) {
                fileContents.add(line);
            }
            fileBuff.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
        System.out.println(fileContents.contains("Mark Sagal"));
    }
}

An error when I add a variable to a string

This problem also arise when we don't give the single or double quotes to the database value.

Wrong way:

$query ="INSERT INTO tabel_name VALUE ($value1,$value2)";

As database inserting values must be in quotes ' '/" "

Right way:

$query ="INSERT INTO STUDENT VALUE ('$roll_no','$name','$class')";

Stop Chrome Caching My JS Files

Things that did not work for me:

  • clicking the refresh icon (with or without shift)
  • SHIFT-F5, CTRL-F5
  • opening the page in an incognito window
  • F12 (to open Dev tools) / (Dev tools) Settings / Disable cache (while dev tools is open)

What I mean by not working is: In the file system the .js file has been updated, but Chrome does not pick up the change. It means the page script executes with the old logic, Dev tools Scripts / ... / Compiled / ... shows the old .js content.

What does work for me:

  • Close Chrome and re-open the page. After this Dev tools Scripts / ... / Compiled / ... shows updated .js content (matching the file system), and page scripts excute with updated logic.

Chrome version 86.0.4240.193 (Official Build) (64-bit)

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

What is the preferred syntax for defining enums in JavaScript?

IE8 does Not support freeze() method.
Source: http://kangax.github.io/compat-table/es5/, Click on "Show obsolete browsers?" on top, and check IE8 & freeze row col intersection.

In my current game project, I have used below, since few customers still use IE8:

var CONST_WILD_TYPES = {
    REGULAR: 'REGULAR',
    EXPANDING: 'EXPANDING',
    STICKY: 'STICKY',
    SHIFTING: 'SHIFTING'
};

We could also do:

var CONST_WILD_TYPES = {
    REGULAR: 'RE',
    EXPANDING: 'EX',
    STICKY: 'ST',
    SHIFTING: 'SH'
};

or even this:

var CONST_WILD_TYPES = {
    REGULAR: '1',
    EXPANDING: '2',
    STICKY: '3',
    SHIFTING: '4'
};

The last one, seems most efficient for string, it reduces your total bandwidth if you have server & client exchanging this data.
Of course, now it's your duty to make sure there are no conflicts in the data (RE, EX, etc. must be unique, also 1, 2, etc. should be unique). Note that you need to maintain these forever for backward compatibility.

Assignment:

var wildType = CONST_WILD_TYPES.REGULAR;

Comparision:

if (wildType === CONST_WILD_TYPES.REGULAR) {
    // do something here
}

Jquery UI tooltip does not support html content

To avoid placing HTML tags in the title attribute, another solution is to use markdown. For instance, you could use [br] to represent a line break, then perform a simple replace in the content function.

In title attribute:

"Sample Line 1[br][br]Sample Line 2"

In your content function:

content: function () {
    return $(this).attr('title').replace(/\[br\]/g,"<br />");
}

Using os.walk() to recursively traverse directories in Python

Do try this; easy one

 #!/usr/bin/python
 import os
 # Creating an empty list that will contain the already traversed paths
 donePaths = []
 def direct(path):
       for paths,dirs,files in os.walk(path):
             if paths not in donePaths:
                    count = paths.count('/')
                    if files:
                          for ele1 in files:
                                print '---------' * (count), ele1
                    if dirs:
                          for ele2 in dirs:
                                print '---------' * (count), ele2
                                absPath = os.path.join(paths,ele2)
              # recursively calling the direct function on each directory
                                direct(absPath)
                   # adding the paths to the list that got traversed 
                                donePaths.append(absPath)

 path = raw_input("Enter any path to get the following Dir Tree ...\n")
 direct(path)

========OUTPUT below========

 /home/test
 ------------------ b.txt
 ------------------ a.txt
 ------------------ a
 --------------------------- a1.txt
 ------------------ b
 --------------------------- b1.txt
 --------------------------- b2.txt
 --------------------------- cde
 ------------------------------------ cde.txt
 ------------------------------------ cdeDir
 --------------------------------------------- cdeDir.txt
 ------------------ c
 --------------------------- c.txt
 --------------------------- c1
 ------------------------------------ c1.txt
 ------------------------------------ c2.txt

WCF - How to Increase Message Size Quota

If you're still getting this error message while using the WCF Test Client, it's because the client has a separate MaxBufferSize setting.

To correct the issue:

  1. Right-Click on the Config File node at the bottom of the tree
  2. Select Edit with SvcConfigEditor

A list of editable settings will appear, including MaxBufferSize.

Note: Auto-generated proxy clients also set MaxBufferSize to 65536 by default.

How does Python's super() work with multiple inheritance?

In learningpythonthehardway I learn something called super() an in-built function if not mistaken. Calling super() function can help the inheritance to pass through the parent and 'siblings' and help you to see clearer. I am still a beginner but I love to share my experience on using this super() in python2.7.

If you have read through the comments in this page, you will hear of Method Resolution Order (MRO), the method being the function you wrote, MRO will be using Depth-First-Left-to-Right scheme to search and run. You can do more research on that.

By adding super() function

super(First, self).__init__() #example for class First.

You can connect multiple instances and 'families' with super(), by adding in each and everyone in them. And it will execute the methods, go through them and make sure you didn't miss out! However, adding them before or after does make a difference you will know if you have done the learningpythonthehardway exercise 44. Let the fun begins!!

Taking example below, you can copy & paste and try run it:

class First(object):
    def __init__(self):

        print("first")

class Second(First):
    def __init__(self):
        print("second (before)")
        super(Second, self).__init__()
        print("second (after)")

class Third(First):
    def __init__(self):
        print("third (before)")
        super(Third, self).__init__()
        print("third (after)")


class Fourth(First):
    def __init__(self):
        print("fourth (before)")
        super(Fourth, self).__init__()
        print("fourth (after)")


class Fifth(Second, Third, Fourth):
    def __init__(self):
        print("fifth (before)")
        super(Fifth, self).__init__()
        print("fifth (after)")

Fifth()

How does it run? The instance of fifth() will goes like this. Each step goes from class to class where the super function added.

1.) print("fifth (before)")
2.) super()>[Second, Third, Fourth] (Left to right)
3.) print("second (before)")
4.) super()> First (First is the Parent which inherit from object)

The parent was found and it will go continue to Third and Fourth!!

5.) print("third (before)")
6.) super()> First (Parent class)
7.) print ("Fourth (before)")
8.) super()> First (Parent class)

Now all the classes with super() have been accessed! The parent class has been found and executed and now it continues to unbox the function in the inheritances to finished the codes.

9.) print("first") (Parent)
10.) print ("Fourth (after)") (Class Fourth un-box)
11.) print("third (after)") (Class Third un-box)
12.) print("second (after)") (Class Second un-box)
13.) print("fifth (after)") (Class Fifth un-box)
14.) Fifth() executed

The outcome of the program above:

fifth (before)
second (before
third (before)
fourth (before)
first
fourth (after)
third (after)
second (after)
fifth (after)

For me by adding super() allows me to see clearer on how python would execute my coding and make sure the inheritance can access the method I intended.

iOS - Build fails with CocoaPods cannot find header files

I will update the below things in my Build settings and I did not get any errors. To check these are the things while updating your cocoapods.

Build Settings

Enable Bit code - YES(if you are using bitcode)

Macro preprocessor - $(inherited)

Other linker flag - objc, -lc++, $(inherited)

Build architecture only

Debug - Yes

Relese - No

Search Path

Framework search path - $(inherited) $(PROJECT_DIR)

Library search path - $(inherited)

Header search path - $(inherited)

HTML5 live streaming

Use ffmpeg + ffserver. It works!!! You can get a config file for ffserver from ffmpeg.org and accordingly set the values.

Is there a way to get the source code from an APK file?

I'll show you other way to decompile the .apk files.

You can follow the first 2 steps from "prankul garg". So you have another opportunities:

Step 3':

Download the "JD-GUI", thats easy to found this one. Open your .jar file in "jd-gui.exe". (File > Open file > 'found your .jar file'). After this procedure, you can save all resources in a .zip file.

So,

1st - You have to rename the .apk file to .zip

2nd - You have to decode .dex file (if you want, decode the .apk file to dex2jar, that's possible)

3rd - You have to decode .jar file with JD-GUI

Best way to detect when a user leaves a web page?

Mozilla Developer Network has a nice description and example of onbeforeunload.

If you want to warn the user before leaving the page if your page is dirty (i.e. if user has entered some data):

window.addEventListener('beforeunload', function(e) {
  var myPageIsDirty = ...; //you implement this logic...
  if(myPageIsDirty) {
    //following two lines will cause the browser to ask the user if they
    //want to leave. The text of this dialog is controlled by the browser.
    e.preventDefault(); //per the standard
    e.returnValue = ''; //required for Chrome
  }
  //else: user is allowed to leave without a warning dialog
});

Entity Framework : How do you refresh the model when the db changes?

Update CodeFirst Model is not possible automatically. I don't recommend either. Because one of the benefits of code first is you can work with POCO classes. If you changed this POCO classes you don't want some auto generated code to destroy your work.

But you can create some template solution add your updated/added entity to the new model. then collect and move your new cs file to your working project. this way you will not have a conflict if it is a new entity you can simply adding related cs file to the existing project. if it is an update just add a new property from the file. If you just adding some couple of columns to one or two of your tables you can manually add them to your POCO class you don't need any extra works and that is the beauty of Working with Code-First and POCO classes.

Play audio with Python

Take a look at Simpleaudio, which is a relatively recent and lightweight library for this purpose:

> pip install simpleaudio

Then:

import simpleaudio as sa

wave_obj = sa.WaveObject.from_wave_file("path/to/file.wav")
play_obj = wave_obj.play()
play_obj.wait_done()

Make sure to use uncompressed 16 bit PCM files.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Android studio doesn't list my phone under "Choose Device"

I face Same problem. In my case i solved this by following some steps.

  1. click attached debugger to android process (It located In android tools inside run button)

  2. if see adb not responding error dialog. then click restart of dialogue button.

  3. Now you can see which device is connected. now close this window.

  4. again press run button. Now you find your targeted device or emulator which is connected.

Hopefully it helps you.

Transposing a 1D NumPy array

numpy 1D array --> column/row matrix:

>>> a=np.array([1,2,4])
>>> a[:, None]    # col
array([[1],
       [2],
       [4]])
>>> a[None, :]    # row, or faster `a[None]`
array([[1, 2, 4]])

And as @joe-kington said, you can replace None with np.newaxis for readability.

How do I install soap extension?

For Windows

  1. Find extension=php_soap.dll or extension=soap in php.ini and remove the commenting semicolon at the beginning of the line. Eventually check for soap.ini under the conf.d directory.

  2. Restart your server.

For Linux

Ubuntu:

PHP7

Apache

sudo apt-get install php7.0-soap 
sudo systemctl restart apache2

PHP5

sudo apt-get install php-soap
sudo systemctl restart apache2

OpenSuse:

PHP7

Apache

sudo zypper in php7-soap
sudo systemctl restart apache2

Nginx

sudo zypper in php7-soap
sudo systemctl restart nginx

"Items collection must be empty before using ItemsSource."

I ran into this problem because one level of tag, <ListView.View> to be specirfic, was missing in my XAML.

This code produced this error.

<Grid>
    <ListView Margin="10" Name="lvDataBinding" >
        <GridView>
            <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
            <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
        </GridView>
    </ListView>
</Grid>

The following fixed it

<Grid>
    <ListView Margin="10" Name="lvDataBinding" >
        <ListView.View> <!-- This was missing in top! -->
            <GridView>
                <GridViewColumn Header="Name" Width="120" DisplayMemberBinding="{Binding Name}" />
                <GridViewColumn Header="Age" Width="50" DisplayMemberBinding="{Binding Age}" />
                <GridViewColumn Header="Mail" Width="150" DisplayMemberBinding="{Binding Mail}" />
            </GridView>
        </ListView.View>
    </ListView>
</Grid>

nodemon not found in npm

Try to install nodemon globally.

sudo npm install -g nodemon

Optional args in MATLAB functions

There are a few different options on how to do this. The most basic is to use varargin, and then use nargin, size etc. to determine whether the optional arguments have been passed to the function.

% Function that takes two arguments, X & Y, followed by a variable 
% number of additional arguments
function varlist(X,Y,varargin)
   fprintf('Total number of inputs = %d\n',nargin);

   nVarargs = length(varargin);
   fprintf('Inputs in varargin(%d):\n',nVarargs)
   for k = 1:nVarargs
      fprintf('   %d\n', varargin{k})
   end

A little more elegant looking solution is to use the inputParser class to define all the arguments expected by your function, both required and optional. inputParser also lets you perform type checking on all arguments.

Android List View Drag and Drop sort

The DragListView lib does this really neat with very nice support for custom animations such as elevation animations. It is also still maintained and updated on a regular basis.

Here is how you use it:

1: Add the lib to gradle first

dependencies {
    compile 'com.github.woxthebox:draglistview:1.2.1'
}

2: Add list from xml

<com.woxthebox.draglistview.DragListView
    android:id="@+id/draglistview"
    android:layout_width="match_parent"
    android:layout_height="match_parent"/>

3: Set the drag listener

mDragListView.setDragListListener(new DragListView.DragListListener() {
    @Override
    public void onItemDragStarted(int position) {
    }

    @Override
    public void onItemDragEnded(int fromPosition, int toPosition) {
    }
});

4: Create an adapter overridden from DragItemAdapter

public class ItemAdapter extends DragItemAdapter<Pair<Long, String>, ItemAdapter.ViewHolder>
    public ItemAdapter(ArrayList<Pair<Long, String>> list, int layoutId, int grabHandleId, boolean dragOnLongPress) {
        super(dragOnLongPress);
        mLayoutId = layoutId;
        mGrabHandleId = grabHandleId;
        setHasStableIds(true);
        setItemList(list);
}

5: Implement a viewholder that extends from DragItemAdapter.ViewHolder

public class ViewHolder extends DragItemAdapter.ViewHolder {
    public TextView mText;

    public ViewHolder(final View itemView) {
        super(itemView, mGrabHandleId);
        mText = (TextView) itemView.findViewById(R.id.text);
    }

    @Override
    public void onItemClicked(View view) {
    }

    @Override
    public boolean onItemLongClicked(View view) {
        return true;
    }
}

For more detailed info go to https://github.com/woxblom/DragListView

Oracle query to identify columns having special characters

They key is the backslash escape character will not work with the right square bracket inside of the character class square brackets (it is interpreted as a literal backslash inside the character class square brackets). Add the right square bracket with an OR at the end like this:

select EmpNo, SampleText
from test 
where NOT regexp_like(SampleText, '[ A-Za-z0-9.{}[]|]');

How to include a class in PHP

You can use either of the following:

include "class.twitter.php";

or

require "class.twitter.php";

Using require (or require_once if you want to ensure the class is only loaded once during execution) will cause a fatal error to be raised if the file doesn't exist, whereas include will only raise a warning. See http://php.net/require and http://php.net/include for more details

Android: How to programmatically access the device serial number shown in the AVD manager (API Version 8)

From Android P, defining the READ_PHONE_STATE permission in AndroidManifest only, will not work. We have to actually request for the permission. Below code works for me:

@RequiresApi(api = Build.VERSION_CODES.P)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 101);
    }
}

@RequiresApi(api = Build.VERSION_CODES.O)
@Override
protected void onResume() {
    super.onResume();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
        return;
    }
    Log.d(TAG,Build.getSerial());
}
@RequiresApi(api = Build.VERSION_CODES.O)
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    switch (requestCode) {
        case 101:
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
                return;
            }
        } else {
            //not granted
        }
        break;
        default:
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}

Add this permissions in AndroidManifest.xml

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

Hope this helps.

Thank You, MJ

Chrome extension: accessing localStorage in content script

Update 2016:

Google Chrome released the storage API: http://developer.chrome.com/extensions/storage.html

It is pretty easy to use like the other Chrome APIs and you can use it from any page context within Chrome.

    // Save it using the Chrome extension storage API.
    chrome.storage.sync.set({'foo': 'hello', 'bar': 'hi'}, function() {
      console.log('Settings saved');
    });

    // Read it using the storage API
    chrome.storage.sync.get(['foo', 'bar'], function(items) {
      message('Settings retrieved', items);
    });

To use it, make sure you define it in the manifest:

    "permissions": [
      "storage"
    ],

There are methods to "remove", "clear", "getBytesInUse", and an event listener to listen for changed storage "onChanged"

Using native localStorage (old reply from 2011)

Content scripts run in the context of webpages, not extension pages. Therefore, if you're accessing localStorage from your contentscript, it will be the storage from that webpage, not the extension page storage.

Now, to let your content script to read your extension storage (where you set them from your options page), you need to use extension message passing.

The first thing you do is tell your content script to send a request to your extension to fetch some data, and that data can be your extension localStorage:

contentscript.js

chrome.runtime.sendMessage({method: "getStatus"}, function(response) {
  console.log(response.status);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getStatus")
      sendResponse({status: localStorage['status']});
    else
      sendResponse({}); // snub them.
});

You can do an API around that to get generic localStorage data to your content script, or perhaps, get the whole localStorage array.

I hope that helped solve your problem.

To be fancy and generic ...

contentscript.js

chrome.runtime.sendMessage({method: "getLocalStorage", key: "status"}, function(response) {
  console.log(response.data);
});

background.js

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
    if (request.method == "getLocalStorage")
      sendResponse({data: localStorage[request.key]});
    else
      sendResponse({}); // snub them.
});

How to reload the current state?

Not sure why none of these seemed to work for me; the one that finally did it was:

$state.reload($state.current.name);

This was with Angular 1.4.0

Cast to generic type in C#

As mentioned, you cannot cast it directly. One possible solution is to have those generic types inherit from a non-generic interface, in which case you can still invoke methods on it without reflection. Using reflection, you can pass the mapped object to any method expecting it, then the cast will be performed for you. So if you have a method called Accept expecting a MessageProcessor as a parameter, then you can find it and invoke it dynamically.

Unknown URL content://downloads/my_downloads

For those who are getting Error Unknown URI: content://downloads/public_downloads. I managed to solve this by getting a hint given by @Commonsware in this answer. I found out the class FileUtils on GitHub. Here InputStream methods are used to fetch file from Download directory.

 // DownloadsProvider
            else if (isDownloadsDocument(uri)) {

                final String id = DocumentsContract.getDocumentId(uri);

                if (id != null && id.startsWith("raw:")) {
                    return id.substring(4);
                }

                String[] contentUriPrefixesToTry = new String[]{
                        "content://downloads/public_downloads",
                        "content://downloads/my_downloads",
                        "content://downloads/all_downloads"
                };

                for (String contentUriPrefix : contentUriPrefixesToTry) {
                    Uri contentUri = ContentUris.withAppendedId(Uri.parse(contentUriPrefix), Long.valueOf(id));
                    try {
                        String path = getDataColumn(context, contentUri, null, null);
                        if (path != null) {
                            return path;
                        }
                    } catch (Exception e) {}
                }

                // path could not be retrieved using ContentResolver, therefore copy file to accessible cache using streams
                String fileName = getFileName(context, uri);
                File cacheDir = getDocumentCacheDir(context);
                File file = generateFileName(fileName, cacheDir);
                String destinationPath = null;
                if (file != null) {
                    destinationPath = file.getAbsolutePath();
                    saveFileFromUri(context, uri, destinationPath);
                }

                return destinationPath;
            }

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

Why use pointers?

Regarding your second question, generally you don't need to use pointers while programming, however there is one exception to this and that is when you make a public API.

The problem with C++ constructs that people generally use to replace pointers are very dependent on the toolset that you use which is fine when you have all the control you need over the source code, however if you compile a static library with visual studio 2008 for instance and try to use it in a visual studio 2010 you will get a ton of linker errors because the new project is linked with a newer version of STL which is not backwards compatible. Things get even nastier if you compile a DLL and give an import library that people use in a different toolset because in that case your program will crash sooner or later for no apparent reason.

So for the purpose of moving large data sets from one library to another you could consider giving a pointer to an array to the function that is supposed to copy the data if you don't want to force others to use the same tools that you use. The good part about this is that it doesn't even have to be a C-style array, you can use a std::vector and give the pointer by giving the address of the first element &vector[0] for instance, and use the std::vector to manage the array internally.

Another good reason to use pointers in C++ again relates to libraries, consider having a dll that cannot be loaded when your program runs, so if you use an import library then the dependency isn't satisfied and the program crashes. This is the case for instance when you give a public api in a dll alongside your application and you want to access it from other applications. In this case in order to use the API you need to load the dll from its' location (usually it's in a registry key) and then you need to use a function pointer to be able to call functions inside the DLL. Sometimes the people that make the API are nice enough to give you a .h file that contain helper functions to automate this process and give you all the function pointers that you need, but if not you can use LoadLibrary and GetProcAddress on windows and dlopen and dlsym on unix to get them (considering that you know the entire signature of the function).

Close pre-existing figures in matplotlib when running from eclipse

Nothing works in my case using the scripts above but I was able to close these figures from eclipse console bar by clicking on Terminate ALL (two red nested squares icon).

Why does this AttributeError in python occur?

AttributeError is raised when attribute of the object is not available.

An attribute reference is a primary followed by a period and a name:

attributeref ::= primary "." identifier

To return a list of valid attributes for that object, use dir(), e.g.:

dir(scipy)

So probably you need to do simply: import scipy.sparse

Attach the Source in Eclipse of a jar

Go back in to where you added the jar. I believe its the libraries tab, I don't have Eclipse open but that sounds right. to the left of the jar file you added there should be an arrow pointing right, click that and 3 or 4 options expand, one of them being the source file of the library. Click on that and click edit(I think you can also double click it) then locate the file or folder on your hard disk, you probably have to click apply or okay and you're good to go, same with javadoc and i think the last one is native libraries. I don't pay much attention when I'm in there anymore if you couldn't tell. That's what you were asking, right?

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

What exactly does Double mean in java?

In a comment on @paxdiablo's answer, you asked:

"So basically, is it better to use Double than Float?"

That is a complicated question. I will deal with it in two parts


Deciding between double versus float

On the one hand, a double occupies 8 bytes versus 4 bytes for a float. If you have many of them, this may be significant, though it may also have no impact. (Consider the case where the values are in fields or local variables on a 64bit machine, and the JVM aligns them on 64 bit boundaries.) Additionally, floating point arithmetic with double values is typically slower than with float values ... though once again this is hardware dependent.

On the other hand, a double can represent larger (and smaller) numbers than a float and can represent them with more than twice the precision. For the details, refer to Wikipedia.

The tricky question is knowing whether you actually need the extra range and precision of a double. In some cases it is obvious that you need it. In others it is not so obvious. For instance if you are doing calculations such as inverting a matrix or calculating a standard deviation, the extra precision may be critical. On the other hand, in some cases not even double is going to give you enough precision. (And beware of the trap of expecting float and double to give you an exact representation. They won't and they can't!)

There is a branch of mathematics called Numerical Analysis that deals with the effects of rounding error, etc in practical numerical calculations. It used to be a standard part of computer science courses ... back in the 1970's.


Deciding between Double versus Float

For the Double versus Float case, the issues of precision and range are the same as for double versus float, but the relative performance measures will be slightly different.

  • A Double (on a 32 bit machine) typically takes 16 bytes + 4 bytes for the reference, compared with 12 + 4 bytes for a Float. Compare this to 8 bytes versus 4 bytes for the double versus float case. So the ratio is 5 to 4 versus 2 to 1.

  • Arithmetic involving Double and Float typically involves dereferencing the pointer and creating a new object to hold the result (depending on the circumstances). These extra overheads also affect the ratios in favor of the Double case.


Correctness

Having said all that, the most important thing is correctness, and this typically means getting the most accurate answer. And even if accuracy is not critical, it is usually not wrong to be "too accurate". So, the simple "rule of thumb" is to use double in preference to float, UNLESS there is an overriding performance requirement, AND you have solid evidence that using float will make a difference with respect to that requirement.

how to display variable value in alert box?

$(document).ready(function(){

//    alert("test");
$("#name").click(function(){
var content = document.getElementById("ghufran").innerHTML ;
   alert(content);
  });

 //var content = $('#one').text();

})

there u go buddy this code actually works

Best way to track onchange as-you-type in input type="text"?

there is a quite near solution (do not fix all Paste ways) but most of them:

It works for inputs as well as for textareas:

<input type="text" ... >
<textarea ... >...</textarea>

Do like this:

<input type="text" ... onkeyup="JavaScript: ControlChanges()" onmouseup="JavaScript: ControlChanges()" >
<textarea ... onkeyup="JavaScript: ControlChanges()" onmouseup="JavaScript: ControlChanges()" >...</textarea>

As i said, not all ways to Paste fire an event on all browsers... worst some do not fire any event at all, but Timers are horrible to be used for such.

But most of Paste ways are done with keyboard and/or mouse, so normally an onkeyup or onmouseup are fired after a paste, also onkeyup is fired when typing on keyboard.

Ensure yor check code does not take much time... otherwise user get a poor impresion.

Yes, the trick is to fire on key and on mouse... but beware both can be fired, so take in mind such!!!

Why Does OAuth v2 Have Both Access and Refresh Tokens?

Despite all the great answers above, I as a security master student and programmer who previously worked at eBay when I took a look into buyer protection and fraud, can say to separate access token and refresh token has its best balance between harassing user of frequent username/password input and keeping the authority in hand to revoke access to potential abuse of your service.

Think of a scenario like this. You issue user of an access token of 3600 seconds and refresh token much longer as one day.

  1. The user is a good user, he is at home and gets on/off your website shopping and searching on his iPhone. His IP address doesn't change and have a very low load on your server. Like 3-5 page requests every minute. When his 3600 seconds on the access token is over, he requires a new one with the refresh token. We, on the server side, check his activity history and IP address, think he is a human and behaves himself. We grant him a new access token to continue using our service. The user won't need to enter again the username/password until he has reached one day life-span of refresh token itself.

  2. The user is a careless user. He lives in New York, USA and got his virus program shutdown and was hacked by a hacker in Poland. When the hacker got the access token and refresh token, he tries to impersonate the user and use our service. But after the short-live access token expires, when the hacker tries to refresh the access token, we, on the server, has noticed a dramatic IP change in user behavior history (hey, this guy logins in USA and now refresh access in Poland after just 3600s ???). We terminate the refresh process, invalidate the refresh token itself and prompt to enter username/password again.

  3. The user is a malicious user. He is intended to abuse our service by calling 1000 times our API each minute using a robot. He can well doing so until 3600 seconds later, when he tries to refresh the access token, we noticed his behavior and think he might not be a human. We reject and terminate the refresh process and ask him to enter username/password again. This might potentially break his robot's automatic flow. At least makes him uncomfortable.

You can see the refresh token has acted perfectly when we try to balance our work, user experience and potential risk of a stolen token. Your watch dog on the server side can check more than IP change, frequency of api calls to determine whether the user shall be a good user or not.

Another word is you can also try to limit the damage control of stolen token/abuse of service by implementing on each api call the basic IP watch dog or any other measures. But this is expensive as you have to read and write record about the user and will slow down your server response.

remove space between paragraph and unordered list

p, ul{
     padding:0; 
     margin:0;
}

If that's not what your looking for you'll have to be more specific

How do I count unique visitors to my site?

for finding out that user is new or old , Get user IP .

create a table for IPs and their visits timestamp .

check IF IP does not exists OR time()-saved_timestamp > 60*60*24 (for 1 day) ,edit the IP's timestamp to time() (means now) and increase your view one .

else , do nothing .

FYI : user IP is stored in $_SERVER['REMOTE_ADDR'] variable

Get list from pandas DataFrame column headers

n = []
for i in my_dataframe.columns:
    n.append(i)
print n

how to align all my li on one line?

Here is what you want. In this case you do not want the list items to be treated as blocks that can wrap.

li{display:inline}
ul{overflow:hidden}

Find Active Tab using jQuery and Twitter Bootstrap

Here is the answer for those of you who need a Boostrap 3 solution.

In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line

// tab
$('#rowTab a:first').tab('show');

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
 console.log ( $(e.target).attr('id') );
});

How to make an anchor tag refer to nothing?

React no longer support using a function like this href="javascript:void(0)" in your anchor tag, but here is something that works pretty well.

<a href="#" onClick={() => null} >link</a>

How do I use jQuery to redirect?

Via Jquery:

$(location).attr('href','http://example.com/Registration/Success/');

C# equivalent of C++ map<string,double>

Dictionary is the most common, but you can use other types of collections, e.g. System.Collections.Generic.SynchronizedKeyedCollection, System.Collections.Hashtable, or any KeyValuePair collection

Console.log not working at all

As a complete new at javascript, I just had the same problem on my side here. The mistake I did, was that I used:

<script type="text.javascript">
  console.log("bla bla bla");
</script>

instead of:

<script>
  console.log("bla bla bla");
</script>

using the

type="text.javascript"

had the result of not producing the log in the console.

Checking Date format from a string in C#

Use an array of valid dates format, check docs:

string[] formats = { "d/MM/yyyy", "dd/MM/yyyy" };
DateTime parsedDate;
var isValidFormat= DateTime.TryParseExact(inputString, formats, new CultureInfo("en-US"), DateTimeStyles.None, out parsedDate);

if(isValidFormat)
{
    string.Format("{0:d/MM/yyyy}", parsedDate);
}
else
{
    // maybe throw an Exception
}

How to ignore whitespace in a regular expression subject string?

You can stick optional whitespace characters \s* in between every other character in your regex. Although granted, it will get a bit lengthy.

/cats/ -> /c\s*a\s*t\s*s/

SQL Order By Count

Below gives me opposite of what you have. (Notice Group column)

SELECT
    *
FROM
    myTable
GROUP BY
    Group_value,
    ID
ORDER BY
    count(Group_value)

Let me know if this is fine with you...

I am trying to get what you want too...

Switch firefox to use a different DNS than what is in the windows.host file

DNS resolving is usually done at the system level and not at the application level, so you can't normally have one program use one dns and another program use a different dns. I'm not aware of any firefox extensions that allow you to use a different dns.

Finding median of list in Python

median Function

def median(midlist):
    midlist.sort()
    lens = len(midlist)
    if lens % 2 != 0: 
        midl = (lens / 2)
        res = midlist[midl]
    else:
        odd = (lens / 2) -1
        ev = (lens / 2) 
        res = float(midlist[odd] + midlist[ev]) / float(2)
    return res

Twitter Bootstrap alert message close and open again

The problem is caused by using the style="display:none", you should hide the alert with Javascript or at least when showing it, remove the style attribute.

orderBy multiple fields in Angular

If you wants to sort on mulitple fields inside controller use this

$filter('orderBy')($scope.property_list, ['firstProp', 'secondProp']);

See also https://docs.angularjs.org/api/ng/filter/orderBy

In Java what is the syntax for commenting out multiple lines?

/* 
LINES I WANT COMMENTED 
LINES I WANT COMMENTED 
LINES I WANT COMMENTED 
*/

How to update single value inside specific array item in redux

Very late to the party but here is a generic solution that works with every index value.

  1. You create and spread new array from the old array up to the index you want to change.

  2. Add the data you want.

  3. Create and spread new array from the index you wanted to change to the end of the array

let index=1;// probabbly action.payload.id
case 'SOME_ACTION':
   return { 
       ...state, 
       contents: [
          ...state.contents.slice(0,index),
          {title: "some other title", text: "some other text"},
         ...state.contents.slice(index+1)
         ]
    }

Update:

I have made a small module to simplify the code, so you just need to call a function:

case 'SOME_ACTION':
   return {
       ...state,
       contents: insertIntoArray(state.contents,index, {title: "some title", text: "some text"})
    }

For more examples, take a look at the repository

function signature:

insertIntoArray(originalArray,insertionIndex,newData)

How to insert tab character when expandtab option is on in Vim

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V<Tab>. See also :retab and ins-expandtab.
This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.

JPA : How to convert a native query result set to POJO class collection

Unwrap procedure can be performed to assign results to non-entity(which is Beans/POJO). The procedure is as following.

List<JobDTO> dtoList = entityManager.createNativeQuery(sql)
        .setParameter("userId", userId)
        .unwrap(org.hibernate.Query.class).setResultTransformer(Transformers.aliasToBean(JobDTO.class)).list();

The usage is for JPA-Hibernate implementation.

How to open maximized window with Javascript?

Checkout this jquery window plugin: http://fstoke.me/jquery/window/

// create a window
sampleWnd = $.window({
   .....
});

// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);

Split string into string array of single characters

Simple!!
one line:

 var res = test.Select(x => new string(x, 1)).ToArray();

How do I convert between ISO-8859-1 and UTF-8 in Java?

The easiest way to convert an ISO-8859-1 string to UTF-8 string.

private static String convertIsoToUTF8(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("ISO-8859-1"), "utf-8");
}

If we want to convert an UTF-8 string to ISO-8859-1 string.

private static String convertUTF8ToISO(String example) throws UnsupportedEncodingException {
    return new String(example.getBytes("utf-8"), "ISO-8859-1");
}

Moreover, a method that converts an ISO-8859-1 string to UTF-8 string without using the constructor of class String.

public static String convertISO_to_UTF8_personal(String strISO_8859_1) {
    String res = "";
    int i = 0;
    for (i = 0; i < strISO_8859_1.length() - 1; i++) {
        char ch = strISO_8859_1.charAt(i);
        char chNext = strISO_8859_1.charAt(i + 1);
        if (ch <= 127) {
            res += ch;
        } else if (ch == 194 && chNext >= 128 && chNext <= 191) {
            res += chNext;
        } else if(ch == 195 && chNext >= 128 && chNext <= 191){
            int resNum = chNext + 64;
            res += (char) resNum;
        } else if(ch == 194){
            res += (char) 173;
        } else if(ch == 195){
            res += (char) 224;
        }
    }
    char ch = strISO_8859_1.charAt(i);
    if (ch <= 127 ){
        res += ch;
    }
    return res;
}

}

That method is based on enconding utf-8 to iso-8859-1 of this website. Encoding utf-8 to iso-8859-1

How to hide close button in WPF window?

This doesn't hide the button but will prevent the user from moving forward by shutting down the window.

protected override void OnClosing(System.ComponentModel.CancelEventArgs e)
{            
    if (e.Cancel == false)
    {
        Application.Current.Shutdown();
    }
}

String to decimal conversion: dot separation instead of comma

Thanks for all reply.

Because I have to write a decimal number in a xml file I have find out the problem. In this discussion I have learned that xml file standard use dot for decimal value and this is culture independent. So my solution is write dot decimal number in a xml file and convert the readed string from the same xml file mystring.Replace(".", ","); Thanks Agat for suggestion to research the problem in xml context and ? ? ? ? ? ? because I didn't know visual studio doesn't respect the culture settings I have in my code.

Django development IDE

Eclipse has the PyDev plugin for python development. Unfortunately, I'm not sure how well it integrates with Django.

Python read in string from file and split it into values

>>> [[int(i) for i in line.strip().split(',')] for line in open('input.txt').readlines()]
[[995957, 16833579], [995959, 16777241], [995960, 16829368], [995961, 50431654]]

C# DataTable.Select() - How do I format the filter criteria to include null?

Try this

myDataTable.Select("[Name] is NULL OR [Name] <> 'n/a'" )

Edit: Relevant sources:

How to create a DB for MongoDB container on start up?

My answer is based on the one provided by @x-yuri; but my scenario it's a little bit different. I wanted an image containing the script, not bind without needing to bind-mount it.

mongo-init.sh -- don't know whether or not is need but but I ran chmod +x mongo-init.sh also:

#!/bin/bash
# https://stackoverflow.com/a/53522699
# https://stackoverflow.com/a/37811764
mongo -- "$MONGO_INITDB_DATABASE" <<EOF
  var rootUser = '$MONGO_INITDB_ROOT_USERNAME';
  var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
  var user = '$MONGO_INITDB_USERNAME';
  var passwd = '$MONGO_INITDB_PASSWORD';

  var admin = db.getSiblingDB('admin');

  admin.auth(rootUser, rootPassword);
  db.createUser({
    user: user,
    pwd: passwd,
    roles: [
      {
        role: "root",
        db: "admin"
      }
    ]
  });
EOF

Dockerfile:

FROM mongo:3.6

COPY mongo-init.sh /docker-entrypoint-initdb.d/mongo-init.sh

CMD [ "/docker-entrypoint-initdb.d/mongo-init.sh" ]

docker-compose.yml:

version: '3'

services:
    mongodb:
        build: .
        container_name: mongodb-test
        environment:
            - MONGO_INITDB_ROOT_USERNAME=root
            - MONGO_INITDB_ROOT_PASSWORD=example
            - MONGO_INITDB_USERNAME=myproject
            - MONGO_INITDB_PASSWORD=myproject
            - MONGO_INITDB_DATABASE=myproject

    myproject:
        image: myuser/myimage
        restart: on-failure
        container_name: myproject
        environment:
            - DB_URI=mongodb
            - DB_HOST=mongodb-test
            - DB_NAME=myproject
            - DB_USERNAME=myproject
            - DB_PASSWORD=myproject
            - DB_OPTIONS=
            - DB_PORT=27017            
        ports:
            - "80:80"

After that, I went ahead and publish this Dockefile as an image to use in other projects.

note: without adding the CMD it mongo throws: unbound variable error

how to get the first and last days of a given month

I know this question has a good answer with 't', but thought I would add another solution.

$first = date("Y-m-d", strtotime("first day of this month"));
$last = date("Y-m-d", strtotime("last day of this month"));

Jquery Validate custom error message location

JQUERY FORM VALIDATION CUSTOM ERROR MESSAGE

Demo & example

_x000D_
_x000D_
$(document).ready(function(){_x000D_
  $("#registration").validate({_x000D_
    // Specify validation rules_x000D_
    rules: {_x000D_
      firstname: "required",_x000D_
      lastname: "required",_x000D_
      email: {_x000D_
        required: true,_x000D_
        email: true_x000D_
      },      _x000D_
      phone: {_x000D_
        required: true,_x000D_
        digits: true,_x000D_
        minlength: 10,_x000D_
        maxlength: 10,_x000D_
      },_x000D_
      password: {_x000D_
        required: true,_x000D_
        minlength: 5,_x000D_
      }_x000D_
    },_x000D_
    messages: {_x000D_
      firstname: {_x000D_
      required: "Please enter first name",_x000D_
     },      _x000D_
     lastname: {_x000D_
      required: "Please enter last name",_x000D_
     },     _x000D_
     phone: {_x000D_
      required: "Please enter phone number",_x000D_
      digits: "Please enter valid phone number",_x000D_
      minlength: "Phone number field accept only 10 digits",_x000D_
      maxlength: "Phone number field accept only 10 digits",_x000D_
     },     _x000D_
     email: {_x000D_
      required: "Please enter email address",_x000D_
      email: "Please enter a valid email address.",_x000D_
     },_x000D_
    },_x000D_
  _x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>jQuery Form Validation Using validator()</title>_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> _x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.0/jquery.validate.js"></script>_x000D_
<style>_x000D_
  .error{_x000D_
    color: red;_x000D_
  }_x000D_
  label,_x000D_
  input,_x000D_
  button {_x000D_
    border: 0;_x000D_
    margin-bottom: 3px;_x000D_
    display: block;_x000D_
    width: 100%;_x000D_
  }_x000D_
 .common_box_body {_x000D_
    padding: 15px;_x000D_
    border: 12px solid #28BAA2;_x000D_
    border-color: #28BAA2;_x000D_
    border-radius: 15px;_x000D_
    margin-top: 10px;_x000D_
    background: #d4edda;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
<div class="common_box_body test">_x000D_
  <h2>Registration</h2>_x000D_
  <form action="#" name="registration" id="registration">_x000D_
 _x000D_
    <label for="firstname">First Name</label>_x000D_
    <input type="text" name="firstname" id="firstname" placeholder="John"><br>_x000D_
 _x000D_
    <label for="lastname">Last Name</label>_x000D_
    <input type="text" name="lastname" id="lastname" placeholder="Doe"><br>_x000D_
 _x000D_
    <label for="phone">Phone</label>_x000D_
    <input type="text" name="phone" id="phone" placeholder="8889988899"><br>  _x000D_
 _x000D_
    <label for="email">Email</label>_x000D_
    <input type="email" name="email" id="email" placeholder="[email protected]"><br>_x000D_
 _x000D_
    <label for="password">Password</label>_x000D_
    <input type="password" name="password" id="password" placeholder=""><br>_x000D_
 _x000D_
    <input name="submit" type="submit" id="submit" class="submit" value="Submit">_x000D_
  </form>_x000D_
</div>_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Write objects into file with Node.js

could you try doing JSON.stringify(obj);

Like this

 var stringify = JSON.stringify(obj);
fs.writeFileSync('./data.json', stringify , 'utf-8'); 

How do I add python3 kernel to jupyter (IPython)

This worked for me on Ubuntu 16.04:

python2 -m pip install ipykernel
python2 -m ipykernel install --user

python3 -m pip install ipykernel
python3 -m ipykernel install --user

Reference to the documentation:
Kernels for Python 2 and 3. Installing the IPython kernel - IPython Docs.

how to save and read array of array in NSUserdefaults in swift?

If you are working with Swift 5+ you have to use UserDefaults.standard.setValue(value, forKey: key) and to get saved data you have to use UserDefaults.standard.dictionary(forKey: key).

To add server using sp_addlinkedserver

I had the same issue to connect an SQL_server 2008 to an SQL_server 2016 hosted in a remote server. @Domnic answer didn't worked for me straightforward. I write my tweaked solution here as I think it may be useful for someone else.

An extended answer for remote IP db connections:

Step 1: Link servers

EXEC sp_addlinkedserver @server='SRV_NAME',
   @srvproduct=N'',
   @provider=N'SQLNCLI',   
   @datasrc=N'aaa.bbb.ccc.ddd';

EXEC sp_addlinkedsrvlogin 'SRV_NAME', 'false', NULL, 'your_remote_db_login_user', 'your_remote_db_login_password'

...where SRV_NAME is an invented name. We will use it to refer to the remote server from our queries. aaa.bbb.ccc.ddd is the ip address of the remote server hosting your SQLserver DB.

Step 2: Run your queries For instance:

SELECT * FROM [SRV_NAME].your_remote_db_name.dbo.your_table

...and that's it!

Syntax details: sp_addlinkedserver and sp_addlinkedsrvlogin

How can you program if you're blind?

I'm blind, and have been programming for about 13 years on Windows, Mac, Linux and DOS, in languages from C/C++, Python, Java, C# and various smaller languages along the way. Though the original question was around configuring the environment, I think it's best answered by looking at how a blind person would use a computer.

Some people use a talking environment, such as T. V. Raman and the Emacspeak environment mentioned in other answers. The more common solution by far is to have a screen reader which runs in the background monitoring OS activity and alerting the user via synthetic speech or a physical braille display (generally showing somewhere from 20 to 80 characters at a time). This then means a blind person can use any accessible application.

So, I personally use Visual Studio 2008 these days, and run it with very few modifications. I turn off certain features like displaying errors as I type since I find this distracting. Prior to joining Microsoft all my development was done in a standard text editor like Notepad, so once again no customisations.

It is possible to configure a screen reader to announce indentation. I personally don't use this, since Visual Studio takes care of this, and C# uses braces. But this would be very important in a language like Python where whitespace matters. Finally, Emacspeak does make use of different voices/pitches to indicate different parts of syntax (keywords, comments, identifiers, etc).

Python: json.loads returns items prefixing with 'u'

Try this:

mail_accounts[0].encode("ascii")

How to remove items from a list while iterating?

This answer was originally written in response to a question which has since been marked as duplicate: Removing coordinates from list on python

There are two problems in your code:

1) When using remove(), you attempt to remove integers whereas you need to remove a tuple.

2) The for loop will skip items in your list.

Let's run through what happens when we execute your code:

>>> L1 = [(1,2), (5,6), (-1,-2), (1,-2)]
>>> for (a,b) in L1:
...   if a < 0 or b < 0:
...     L1.remove(a,b)
... 
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: remove() takes exactly one argument (2 given)

The first problem is that you are passing both 'a' and 'b' to remove(), but remove() only accepts a single argument. So how can we get remove() to work properly with your list? We need to figure out what each element of your list is. In this case, each one is a tuple. To see this, let's access one element of the list (indexing starts at 0):

>>> L1[1]
(5, 6)
>>> type(L1[1])
<type 'tuple'>

Aha! Each element of L1 is actually a tuple. So that's what we need to be passing to remove(). Tuples in python are very easy, they're simply made by enclosing values in parentheses. "a, b" is not a tuple, but "(a, b)" is a tuple. So we modify your code and run it again:

# The remove line now includes an extra "()" to make a tuple out of "a,b"
L1.remove((a,b))

This code runs without any error, but let's look at the list it outputs:

L1 is now: [(1, 2), (5, 6), (1, -2)]

Why is (1,-2) still in your list? It turns out modifying the list while using a loop to iterate over it is a very bad idea without special care. The reason that (1, -2) remains in the list is that the locations of each item within the list changed between iterations of the for loop. Let's look at what happens if we feed the above code a longer list:

L1 = [(1,2),(5,6),(-1,-2),(1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
### Outputs:
L1 is now: [(1, 2), (5, 6), (1, -2), (3, 4), (5, 7), (2, 1), (5, -1), (0, 6)]

As you can infer from that result, every time that the conditional statement evaluates to true and a list item is removed, the next iteration of the loop will skip evaluation of the next item in the list because its values are now located at different indices.

The most intuitive solution is to copy the list, then iterate over the original list and only modify the copy. You can try doing so like this:

L2 = L1
for (a,b) in L1:
    if a < 0 or b < 0 :
        L2.remove((a,b))
# Now, remove the original copy of L1 and replace with L2
print L2 is L1
del L1
L1 = L2; del L2
print ("L1 is now: ", L1)

However, the output will be identical to before:

'L1 is now: ', [(1, 2), (5, 6), (1, -2), (3, 4), (5, 7), (2, 1), (5, -1), (0, 6)]

This is because when we created L2, python did not actually create a new object. Instead, it merely referenced L2 to the same object as L1. We can verify this with 'is' which is different from merely "equals" (==).

>>> L2=L1
>>> L1 is L2
True

We can make a true copy using copy.copy(). Then everything works as expected:

import copy
L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
L2 = copy.copy(L1)
for (a,b) in L1:
    if a < 0 or b < 0 :
        L2.remove((a,b))
# Now, remove the original copy of L1 and replace with L2
del L1
L1 = L2; del L2
>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]

Finally, there is one cleaner solution than having to make an entirely new copy of L1. The reversed() function:

L1 = [(1,2), (5,6),(-1,-2), (1,-2),(3,4),(5,7),(-4,4),(2,1),(-3,-3),(5,-1),(0,6)]
for (a,b) in reversed(L1):
    if a < 0 or b < 0 :
        L1.remove((a,b))
print ("L1 is now: ", L1)
>>> L1 is now: [(1, 2), (5, 6), (3, 4), (5, 7), (2, 1), (0, 6)]

Unfortunately, I cannot adequately describe how reversed() works. It returns a 'listreverseiterator' object when a list is passed to it. For practical purposes, you can think of it as creating a reversed copy of its argument. This is the solution I recommend.

Run javascript function when user finishes typing instead of on key up?

If you need wait until user is finished with typing use simple this:

$(document).on('change','#PageSize', function () {
    //Do something after new value in #PageSize       
});

Complete Example with ajax call - this working for my pager - count of item per list:

$(document).ready(function () {
    $(document).on('change','#PageSize', function (e) {
        e.preventDefault();
        var page = 1;
        var pagesize = $("#PageSize").val();
        var q = $("#q").val();
        $.ajax({
            url: '@Url.Action("IndexAjax", "Materials", new { Area = "TenantManage" })',
            data: { q: q, pagesize: pagesize, page: page },
            type: 'post',
            datatype: "json",
            success: function (data) {
                $('#tablecontainer').html(data);
               // toastr.success('Pager has been changed', "Success!");
            },
            error: function (jqXHR, exception) {
                ShowErrorMessage(jqXHR, exception);
            }
        });  
    });
});    

MySql sum elements of a column

Try this:

select sum(a), sum(b), sum(c)
from your_table

CORS with spring-boot and angularjs not working

Im using spring boot 2.1.0 and what worked for me was to

A. Add cors mappings by:

@Configuration
public class Config implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**").allowedOrigins("*");
    }
}

B. Add below configuration to my HttpSecurity for spring security

.cors().configurationSource(new CorsConfigurationSource() {

    @Override
    public CorsConfiguration getCorsConfiguration(HttpServletRequest request) {
        CorsConfiguration config = new CorsConfiguration();
        config.setAllowedHeaders(Collections.singletonList("*"));
        config.setAllowedMethods(Collections.singletonList("*"));
        config.addAllowedOrigin("*");
        config.setAllowCredentials(true);
        return config;
    }
})

Also in case of a Zuul proxy you can use this INSTEAD OF A and B (just use HttpSecurity.cors() to enable it in Spring security):

@Bean
public CorsFilter corsFilter() {
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    final CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.addAllowedOrigin("*");
    config.addAllowedHeader("*");
    config.addAllowedMethod("OPTIONS");
    config.addAllowedMethod("HEAD");
    config.addAllowedMethod("GET");
    config.addAllowedMethod("PUT");
    config.addAllowedMethod("POST");
    config.addAllowedMethod("DELETE");
    config.addAllowedMethod("PATCH");
    source.registerCorsConfiguration("/**", config);
    return new CorsFilter(source);
}

MongoDB: How to find the exact version of installed MongoDB

From the Java API:

Document result = mongoDatabase.runCommand(new Document("buildInfo", 1));
String version = (String) result.get("version");
List<Integer> versionArray = (List<Integer>) result.get("versionArray");

When adding a Javascript library, Chrome complains about a missing source map, why?

Also i'd face same kind of problem for kendo Telerk Ui javaScript file. For that you need to do , Unchecked the 'Enable JavaScript source maps' and 'Enable CSS source map' from inspect element as shown in image and Refresh the WebPage.

In setting of Inspect elelment

Unchecked the 'Enable JavaScript
source maps' and 'Enable CSS source map'

Replacing Numpy elements if condition is met

>>> import numpy as np
>>> a = np.random.randint(0, 5, size=(5, 4))
>>> a
array([[4, 2, 1, 1],
       [3, 0, 1, 2],
       [2, 0, 1, 1],
       [4, 0, 2, 3],
       [0, 0, 0, 2]])
>>> b = a < 3
>>> b
array([[False,  True,  True,  True],
       [False,  True,  True,  True],
       [ True,  True,  True,  True],
       [False,  True,  True, False],
       [ True,  True,  True,  True]], dtype=bool)
>>> 
>>> c = b.astype(int)
>>> c
array([[0, 1, 1, 1],
       [0, 1, 1, 1],
       [1, 1, 1, 1],
       [0, 1, 1, 0],
       [1, 1, 1, 1]])

You can shorten this with:

>>> c = (a < 3).astype(int)

How to get file name from file path in android

Other Way is:

String[] parts = selectedFilePath.split("/");
    final String fileName = parts[parts.length-1];

What are Keycloak's OAuth2 / OpenID Connect endpoints?

Actually link to .well-know is on the first tab of your realm settings - but link doesn't look like link, but as value of text box... bad ui design. Screenshot of Realm's General Tab

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

How to use 'hover' in CSS

Not an answer, but explanation of why your css is not matching HTML.

In css space is used as a separator to tell browser to look in children, so your css

a .hover :hover{
   text-decoration:underline;
}

means "look for a element, then look for any descendants of it that have hover class and look of any descendants of those descendants that have hover state" and would match this markup

<a>
   <span class="hover">
      <span>
         I will become underlined when you hover on me
      <span/>
   </span>
</a> 

If you want to match <a class="hover">I will become underlined when you hover on me</a> you should use a.hover:hover, which means "look for any a element with class hover and with hover state"

Using CMake with GNU Make: How can I see the exact commands?

If you use the CMake GUI then swap to the advanced view and then the option is called CMAKE_VERBOSE_MAKEFILE.

Business logic in MVC

It does not make sense to put your business layer in the Model for an MVC project.

Say that your boss decides to change the presentation layer to something else, you would be screwed! The business layer should be a separate assembly. A Model contains the data that comes from the business layer that passes to the view to display. Then on post for example, the model binds to a Person class that resides in the business layer and calls PersonBusiness.SavePerson(p); where p is the Person class. Here's what I do (BusinessError class is missing but would go in the BusinessLayer too):enter image description here

Create unique constraint with null columns

You could create a unique index with a coalesce on the MenuId:

CREATE UNIQUE INDEX
Favorites_UniqueFavorite ON Favorites
(UserId, COALESCE(MenuId, '00000000-0000-0000-0000-000000000000'), RecipeId);

You'd just need to pick a UUID for the COALESCE that will never occur in "real life". You'd probably never see a zero UUID in real life but you could add a CHECK constraint if you are paranoid (and since they really are out to get you...):

alter table Favorites
add constraint check
(MenuId <> '00000000-0000-0000-0000-000000000000')

sqlite database default time value 'now'

It's just a syntax error, you need parenthesis: (DATETIME('now'))

If you look at the documentation, you'll note the parenthesis that is added around the 'expr' option in the syntax.

Maven2: Missing artifact but jars are in place

I have seen a bug that manifested as "Error installing artifact: File ../null/... does not exist" (that is, the file was not found because there was "null" in the path). The reason was that one environment variable was not visible to maven. It was:

JV_SRCROOT=$DIRECTORY

instead of

export JV_SRCROOT=$DIRECTORY

(in the latter case the variable is visible to child processes)

download a file from Spring boot rest service

The below Sample code worked for me and might help someone.

import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/app")
public class ImageResource {

    private static final String EXTENSION = ".jpg";
    private static final String SERVER_LOCATION = "/server/images";

    @RequestMapping(path = "/download", method = RequestMethod.GET)
    public ResponseEntity<Resource> download(@RequestParam("image") String image) throws IOException {
        File file = new File(SERVER_LOCATION + File.separator + image + EXTENSION);

        HttpHeaders header = new HttpHeaders();
        header.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=img.jpg");
        header.add("Cache-Control", "no-cache, no-store, must-revalidate");
        header.add("Pragma", "no-cache");
        header.add("Expires", "0");

        Path path = Paths.get(file.getAbsolutePath());
        ByteArrayResource resource = new ByteArrayResource(Files.readAllBytes(path));

        return ResponseEntity.ok()
                .headers(header)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType("application/octet-stream"))
                .body(resource);
    }

}

Setting background color for a JFrame

You can use a container like so:

Container c = JFrame.getContentPane();
c.setBackground(Color.red); 

You must of course import java.awt.Color for the red color constant.

What is compiler, linker, loader?

  • Compiler: A language translator that converts a complete program into machine language to produce a program that the computer can process in its entirety.
  • Linker: Utility program which takes one or more compiled object files and combines them into an executable file or another object file.
  • Loader: loads the executable code into memory ,creates the program and data stack , initializes the registers and starts the code running.

How to play CSS3 transitions in a loop?

If you want to take advantage of the 60FPS smoothness that the "transform" property offers, you can combine the two:

@keyframes changewidth {
  from {
    transform: scaleX(1);
  }

  to {
    transform: scaleX(2);
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

More explanation on why transform offers smoother transitions here: https://medium.com/outsystems-experts/how-to-achieve-60-fps-animations-with-css3-db7b98610108

what is the difference between XSD and WSDL

WSDL - It contains the Operation such as Methods which a webservice provides.and these method can accept simple data types such as int,float etc and complex data types such as objects ,vectors, arrays etc. so mapping this to an xml datatype xsd are used. and based upon the xsd an user who wants to acccess webservice from different platform can provide the data appropriately.

Refer : ayazroomy-java.blogspot.com to read about basics of webservice.

The module ".dll" was loaded but the entry-point was not found

The error indicates that the DLL is either not a COM DLL or it's corrupt. If it's not a COM DLL and not being used as a COM DLL by an application then there is no need to register it.
From what you say in your question (the service is not registered) it seems that we are talking about a service not correctly installed. I will try to reinstall the application.

How to show alert message in mvc 4 controller?

You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.

You therefore need to use javascript when the response returns to show a messagebox of some sort.

OR

using jquery on the button that calls the controller action

<script>
 $(document).ready(function(){
  $("#submitButton").on("click",function()
  {
   alert('Your Message');
  });

});
<script>

When should one use a spinlock instead of mutex?

The rule for using spinlocks is simple: use a spinlock if and only if the real time the lock is held is bounded and sufficiently small.

Note that usually user implemented spinlocks DO NOT satisfy this requirement because they do not disable interrupts. Unless pre-emptions are disabled, a pre-emption whilst a spinlock is held violates the bounded time requirement.

Sufficiently small is a judgement call and depends on the context.

Exception: some kernel programming must use a spinlock even when the time is not bounded. In particular if a CPU has no work to do, it has no choice but to spin until some more work turns up.

Special danger: in low level programming take great care when multiple interrupt priorities exist (usually there is at least one non-maskable interrupt). In this higher priority pre-emptions can run even if interrupts at the thread priority are disabled (such as priority hardware services, often related to the virtual memory management). Provided a strict priority separation is maintained, the condition for bounded real time must be relaxed and replaced with bounded system time at that priority level. Note in this case not only can the lock holder be pre-empted but the spinner can also be interrupted; this is generally not a problem because there's nothing you can do about it.

How to retrieve the hash for the current commit in Git?

Perhaps you want an alias so you don't have to remember all the nifty details. After doing one of the below steps, you will be able to simply type:

$ git lastcommit
49c03fc679ab11534e1b4b35687b1225c365c630

Following up on the accepted answer, here are two ways to set this up:

1) Teach git the explicit way by editing the global config (my original answer):

 # open the git config editor
 $ git config --global --edit
 # in the alias section, add
 ...
 [alias]
   lastcommit = rev-parse HEAD
 ...

2) Or if you like a shortcut to teach git a shortcut, as recently commented by Adrien:

$ git config --global alias.lastcommit "rev-parse HEAD"

From here on, use git lastcommit to show the last commit's hash.

Using Java generics for JPA findAll() query with WHERE clause

This will work, and if you need where statement you can add it as parameter.

class GenericDAOWithJPA<T, ID extends Serializable> {

.......

public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

How Long Does it Take to Learn Java for a Complete Newbie?

I worked with some self-taught programmers who read stuff like "learn javascript in 0.01 days". Everyday was worth it's share of thedailywtf.com.

Besides, at a job inteview you get asked "how much javascript experience do you have?", your answer "0.01 days".

so good luck but I hope our path won't cross before a few more years

Changing the selected option of an HTML Select element

I used almost all of the answers posted here but not comfortable with that so i dig one step furter and found easy solution that fits my need and feel worth sharing with you guys.
Instead of iteration all over the options or using JQuery you can do using core JS in simple steps:

Example

<select id="org_list">
  <option value="23">IBM</option>
  <option value="33">DELL</option>
  <option value="25">SONY</option>
  <option value="29">HP</option>
</select>

So you must know the value of the option to select.

function selectOrganization(id){
    org_list=document.getElementById('org_list');
    org_list.selectedIndex=org_list.querySelector('option[value="'+id+'"]').index;
}

How to Use?

selectOrganization(25); //this will select SONY from option List

Your comments are welcome. :) AzmatHunzai.

C++ Calling a function from another class

    void CallFunction ()
    {   // <----- At this point the compiler knows
        //        nothing about the members of B.
        B b;
        b.bFunction();
    }

This happens for the same reason that functions in C cannot call each other without at least one of them being declared as a function prototype.

To fix this issue we need to make sure both classes are declared before they are used. We separate the declaration from the definition. This MSDN article explains in more detail about the declarations and definitions.

class A
{
public:
    void CallFunction ();
};

class B: public A
{
public:
    virtual void bFunction()
    { ... }
};

void A::CallFunction ()
{
    B b;
    b.bFunction();
}

./configure : /bin/sh^M : bad interpreter

Looks like you have a dos line ending file. The clue is the ^M.

You need to re-save the file using Unix line endings.

You might have a dos2unix command line utility that will also do this for you.

What does the question mark operator mean in Ruby?

It is a code style convention; it indicates that a method returns a boolean value.

The question mark is a valid character at the end of a method name.

Find a line in a file and remove it

    public void removeLineFromFile(String file, String lineToRemove) {

    try {

      File inFile = new File(file);

      if (!inFile.isFile()) {
        System.out.println("Parameter is not an existing file");
        return;
      }

      //Construct the new file that will later be renamed to the original filename.
      File tempFile = new File(inFile.getAbsolutePath() + ".tmp");

      BufferedReader br = new BufferedReader(new FileReader(file));
      PrintWriter pw = new PrintWriter(new FileWriter(tempFile));

      String line = null;

      //Read from the original file and write to the new
      //unless content matches data to be removed.
      while ((line = br.readLine()) != null) {

        if (!line.trim().equals(lineToRemove)) {

          pw.println(line);
          pw.flush();
        }
      }
      pw.close();
      br.close();

      //Delete the original file
      if (!inFile.delete()) {
        System.out.println("Could not delete file");
        return;
      }

      //Rename the new file to the filename the original file had.
      if (!tempFile.renameTo(inFile))
        System.out.println("Could not rename file");

    }
    catch (FileNotFoundException ex) {
      ex.printStackTrace();
    }
    catch (IOException ex) {
      ex.printStackTrace();
    }
  }

This I have found on the internet.

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

Wamp Server not goes to green color

I have same issue with IIS, i uninstalled IIS. Type in run services.msc, I see "wampapache64" service was not running, when I start it using right click it give me error.

I just used these steps.

  1. Click on WAMP icon select Apache -> Service -> Remove Service

  2. Click on Wamp icon select Apache -> Service -> Install Service

Got green Wamp icon :(

Is there a way to word-wrap long words in a div?

As david mentions, DIVs do wrap words by default.

If you are referring to really long strings of text without spaces, what I do is process the string server-side and insert empty spans:

thisIsAreallyLongStringThatIWantTo<span></span>BreakToFitInsideAGivenSpace

It's not exact as there are issues with font-sizing and such. The span option works if the container is variable in size. If it's a fixed width container, you could just go ahead and insert line breaks.

How to crop an image using PIL?

There is a crop() method:

w, h = yourImage.size
yourImage.crop((0, 30, w, h-30)).save(...)

How do I return an int from EditText? (Android)

You can do this in 2 steps:

1: Change the input type(In your EditText field) in the layout file to android:inputType="number"

2: Use int a = Integer.parseInt(yourEditTextObject.getText().toString());

Increase days to php current Date()

a day is 86400 seconds.

$tomorrow = date('y:m:d', time() + 86400);

How to set UITextField height?

UITextField *txt = [[UITextField alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
    [txt setText:@"Ananth"];
    [self.view addSubview:txt];

Last two arguments are width and height, You can set as you wish...

Primitive type 'short' - casting in Java

Given that the "why int by default" question hasn't been answered ...

First, "default" is not really the right term (although close enough). As noted by VonC, an expression composed of ints and longs will have a long result. And an operation consisting of ints/logs and doubles will have a double result. The compiler promotes the terms of an expression to whatever type provides a greater range and/or precision in the result (floating point types are presumed to have greater range and precision than integral, although you do lose precision converting large longs to double).

One caveat is that this promotion happens only for the terms that need it. So in the following example, the subexpression 5/4 uses only integral values and is performed using integer math, even though the overall expression involves a double. The result isn't what you might expect...

(5/4) * 1000.0

OK, so why are byte and short promoted to int? Without any references to back me up, it's due to practicality: there are a limited number of bytecodes.

"Bytecode," as its name implies, uses a single byte to specify an operation. For example iadd, which adds two ints. Currently, 205 opcodes are defined, and integer math takes 18 for each type (ie, 36 total between integer and long), not counting conversion operators.

If short, and byte each got their own set of opcodes, you'd be at 241, limiting the ability of the JVM to expand. As I said, no references to back me up on this, but I suspect that Gosling et al said "how often do people actually use shorts?" On the other hand, promoting byte to int leads to this not-so-wonderful effect (the expected answer is 96, the actual is -16):

byte x = (byte)0xC0;
System.out.println(x >> 2);

Remove or uninstall library previously added : cocoapods

  1. Remove pod name(which to remove) from Podfile and then
  2. Open Terminal, set project folder path
  3. Run pod install --no-integrate

How to add directory to classpath in an application run profile in IntelliJ IDEA?

You can try -Xbootclasspath/a:path option of java application launcher. By description it specifies "a colon-separated path of directires, JAR archives, and ZIP archives to append to the default bootstrap class path."

Java: how to import a jar file from command line

You could run it without the -jar command line argument if you happen to know the name of the main class you wish to run:

java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass

If perchance you are using linux, you should use ":" instead of ";" in the classpath.

Node.js - SyntaxError: Unexpected token import

import statements are supported in the stable release of Node since version 14.x LTS.

All you need to do is specify "type": "module" in package.json.

ORDER BY items must appear in the select list if SELECT DISTINCT is specified

Try one of these:

  1. Use column alias:

    ORDER BY RadioServiceCodeId,RadioService

  2. Use column position:

    ORDER BY 1,2

You can only order by columns that actually appear in the result of the DISTINCT query - the underlying data isn't available for ordering on.

How do I create a self-signed certificate for code signing on Windows?

As of PowerShell 4.0 (Windows 8.1/Server 2012 R2) it is possible to make a certificate in Windows without makecert.exe.

The commands you need are New-SelfSignedCertificate and Export-PfxCertificate.

Instructions are in Creating Self Signed Certificates with PowerShell.

"Unknown class <MyClass> in Interface Builder file" error at runtime

My case - Trying to use a Class from a swift framework in my objective c project, I got this error. Solution was to add Module (swift framework) of the class in Interface builder/ Storyboard as shown below. Nothing else

enter image description here

What are database normal forms and can you give examples?

I've never had a good memory for exact wording, but in my database class I think the professor always said something like:

The data depends on the key [1NF], the whole key [2NF] and nothing but the key [3NF].

mssql '5 (Access is denied.)' error during restoring database

I found this, and it worked for me:

CREATE LOGIN BackupRestoreAdmin WITH PASSWORD='$tr0ngP@$$w0rd'
GO
CREATE USER BackupRestoreAdmin FOR LOGIN BackupRestoreAdmin
GO
EXEC sp_addsrvrolemember 'BackupRestoreAdmin', 'dbcreator'
GO
EXEC sp_addrolemember 'db_owner','BackupRestoreAdmin'
GO

Correct way to remove plugin from Eclipse

Inspired by sergionni's answer, I ended up doing the following steps:

Help --> Installation Details --> Installation History tab

In the Previous configurations table, you can select a configuration and see in the Configuration contents exactly which plugins were installed and are included in it.

It's easy to find the configuration that contains the plugin you want to remove, using the Compare button. This button is enabled when two configurations are selected.

After tracking the configuration that's responsible for that plugin, select the previous configuration and press the Revert button.

Note that if you revert to a configuration that isn't the one just right before the Current Installation, it causes any other plugins that were installed since, to be uninstalled as well.

How do I define the name of image built with docker-compose

Depending on your use case, you can use an image which has already been created and specify it's name in docker-compose.

We have a production use case where our CI server builds a named Docker image. (docker build -t <specific_image_name> .). Once the named image is specified, our docker-compose always builds off of the specific image. This allows a couple of different possibilities:

1- You can ensure that where ever you run your docker-compose from, you will always be using the latest version of that specific image.

2- You can specify multiple named images in your docker-compose file and let them be auto-wired through the previous build step.

So, if your image is already built, you can name the image with docker-compose. Remove build and specify image:

wildfly:
  image: my_custom_wildfly_image
  container_name: wildfly_server
  ports:
   - 9990:9990
   - 80:8080
  environment:
   - MYSQL_HOST=mysql_server
   - MONGO_HOST=mongo_server
   - ELASTIC_HOST=elasticsearch_server
  volumes:
   - /Volumes/CaseSensitive/development/wildfly/deployments/:/opt/jboss/wildfly/standalone/deployments/
  links:
   - mysql:mysql_server
   - mongo:mongo_server
   - elasticsearch:elasticsearch_server

How to access the elements of a function's return array?

This is what I did inside the yii framewok:

public function servicesQuery($section){
        $data = Yii::app()->db->createCommand()
                ->select('*')
                ->from('services')
                ->where("section='$section'")
                ->queryAll();   
        return $data;
    }

then inside my view file:

      <?php $consultation = $this->servicesQuery("consultation"); ?> ?>
      <?php foreach($consultation as $consul): ?>
             <span class="text-1"><?php echo $consul['content']; ?></span>
       <?php endforeach;?>

What I am doing grabbing a cretin part of the table i have selected. should work for just php minus the "Yii" way for the db

Multiple submit buttons on HTML form – designate one button as default

I'm resurrecting this because I was researching a non-JavaScript way to do this. I wasn't into the key handlers, and the CSS positioning stuff was causing tab ordering to break since CSS repositioning doesn't change tab order.

My solution is based on the response at https://stackoverflow.com/a/9491141.

The solution source is below. tabindex is used to correct tab behaviour of the hidden button, as well as aria-hidden to avoid having the button read out by screen readers / identified by assistive devices.

<form method="post" action="">
  <button type="submit" name="useraction" value="2nd" class="default-button-handler" aria-hidden="true" tabindex="-1"></button>
  <div class="form-group">
    <label for="test-input">Focus into this input: </label>
    <input type="text" id="test-input" class="form-control" name="test-input" placeholder="Focus in here and press enter / go" />
  </div>

1st button in DOM 2nd button in DOM 3rd button in DOM

Essential CSS for this solution:

.default-button-handler {
  width: 0;
  height: 0;
  padding: 0;
  border: 0;
  margin: 0;
}

How to bind Events on Ajax loaded Content?

Important step for Event binding on Ajax loading content...

01. First of all unbind or off the event on selector

$(".SELECTOR").off();

02. Add event listener on document level

$(document).on("EVENT", '.SELECTOR', function(event) { 
    console.log("Selector event occurred");
});

How can I hide a checkbox in html?

This two classes are borrowed from the HTML Boilerplate main.css. Although the invisible checkbox will be focused and not the label.

/*
 * Hide only visually, but have it available for screenreaders: h5bp.com/v
 */

.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}

/*
 * Extends the .visuallyhidden class to allow the element to be focusable
 * when navigated to via the keyboard: h5bp.com/p
 */

.visuallyhidden.focusable:active,
.visuallyhidden.focusable:focus {
    clip: auto;
    height: auto;
    margin: 0;
    overflow: visible;
    position: static;
    width: auto;
}

android ellipsize multiline textview

This one handled my html as well,

/*
 * Copyright (C) 2013 Google Inc.
 * Licensed to The Android Open Source Project.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.android.mail.ui;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.Layout;
import android.text.Layout.Alignment;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.StaticLayout;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.widget.TextView;
/**
 * A special MultiLine TextView that will apply ellipsize logic to only the last
 * line of text, such that the last line may be shorter than any previous lines.
 */
public class EllipsizedMultilineTextView extends TextView {
    public static final int ALL_AVAILABLE = -1;
    private int mMaxLines;

    public EllipsizedMultilineTextView(Context context) {
        super(context);
    }
    public EllipsizedMultilineTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }
    public EllipsizedMultilineTextView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs);
    }

    private final void init(Context context, AttributeSet attrs) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
            new int[] { android.R.attr.maxLines });
        setMaxLines(a.getInt(0, 2));
    }
    @Override
    public void setMaxLines(int maxlines) {
        super.setMaxLines(maxlines);
        mMaxLines = maxlines;
    }
    /**
     * Ellipsize just the last line of text in this view and set the text to the
     * new ellipsized value.
     * @param text Text to set and ellipsize
     * @param avail available width in pixels for the last line
     * @param paint Paint that has the proper properties set to measure the text
     *            for this view
     * @return the {@link CharSequence} that was set on the {@link TextView}
     */
    public CharSequence setText(final CharSequence text, int avail) {
        if (text == null || text.length() == 0) {
            return text;
        }
        setEllipsize(null);
        setText(text);
        if (avail == ALL_AVAILABLE) {
            return text;
        }
        Layout layout = getLayout();
        if (layout == null) {
            final int w = getWidth() - getCompoundPaddingLeft() - getCompoundPaddingRight();
            layout = new StaticLayout(text, 0, text.length(), getPaint(), w, Alignment.ALIGN_NORMAL,
                1.0f, 0f, false);
        }
        // find the last line of text and chop it according to available space
        final int lastLineStart = layout.getLineStart(mMaxLines - 1);
        final CharSequence remainder = TextUtils.ellipsize(text.subSequence(lastLineStart,
            text.length()), getPaint(), avail, TextUtils.TruncateAt.END);
        // assemble just the text portion, without spans
        final SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(text.toString(), 0, lastLineStart);
        if (!TextUtils.isEmpty(remainder)) {
            builder.append(remainder.toString());
        }
        // Now copy the original spans into the assembled string, modified for any ellipsizing.
        //
        // Merely assembling the Spanned pieces together would result in duplicate CharacterStyle
        // spans in the assembled version if a CharacterStyle spanned across the lastLineStart
        // offset.
        if (text instanceof Spanned) {
            final Spanned s = (Spanned) text;
            final Object[] spans = s.getSpans(0, s.length(), Object.class);
            final int destLen = builder.length();
            for (int i = 0; i < spans.length; i++) {
                final Object span = spans[i];
                final int start = s.getSpanStart(span);
                final int end = s.getSpanEnd(span);
                final int flags = s.getSpanFlags(span);
                if (start <= destLen) {
                    builder.setSpan(span, start, Math.min(end, destLen), flags);
                }
            }
        }
        setText(builder);
        return builder;
    }
}

Orignal Source LINK

Spring Data JPA findOne() change to Optional how to use this?

The method has been renamed to findById(…) returning an Optional so that you have to handle absence yourself:

Optional<Foo> result = repository.findById(…);

result.ifPresent(it -> …); // do something with the value if present
result.map(it -> …); // map the value if present
Foo foo = result.orElse(null); // if you want to continue just like before

How can we dynamically allocate and grow an array

public class Arr {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int a[] = {1,2,3};
        //let a[] is your original array
        System.out.println(a[0] + " " + a[1] + " " + a[2]);
        int b[];
        //let b[] is your temporary array with size greater than a[]
        //I have took 5
        b = new int[5];
        //now assign all a[] values to b[]
        for(int i = 0 ; i < a.length ; i ++)
            b[i] = a[i];
        //add next index values to b
        b[3] = 4;
        b[4] = 5;
        //now assign b[] to a[]
        a = b;
        //now you can heck that size of an original array increased
        System.out.println(a[0] + " " + a[1] + " " + a[2] + " " + a[3] + " " 
    + a[4]);
    }

}

Output for the above code is:

1 2 3

1 2 3 4 5

Scrollview vertical and horizontal in android

Playing with the code, you can put an HorizontalScrollView into an ScrollView. Thereby, you can have the two scroll method in the same view.

Source : http://androiddevblog.blogspot.com/2009/12/creating-two-dimensions-scroll-view.html

I hope this could help you.

Visual Studio Code PHP Intelephense Keep Showing Not Necessary Error

This solution may help you if you know your problem is limited to Facades and you are running Laravel 5.5 or above.

Install laravel-ide-helper

composer require --dev barryvdh/laravel-ide-helper

Add this conditional statement in your AppServiceProvider to register the helper class.

public function register()
{
    if ($this->app->environment() !== 'production') {
        $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
    }
    // ...
}

Then run php artisan ide-helper:generate to generate a file to help the IDE understand Facades. You will need to restart Visual Studio Code.

References

https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/16

https://github.com/barryvdh/laravel-ide-helper

How to parse this string in Java?

String.split(String regex) is convenient but if you don't need the regular expression handling then go with the substring(..) example, java.util.StringTokenizer or use Apache commons lang 1. The performance difference when not using regular expressions can be a gain of 1 to 2 orders of magnitude in speed.

How to check for file lock?

A variation of DixonD's excellent answer (above).

public static bool TryOpen(string path,
                           FileMode fileMode,
                           FileAccess fileAccess,
                           FileShare fileShare,
                           TimeSpan timeout,
                           out Stream stream)
{
    var endTime = DateTime.Now + timeout;

    while (DateTime.Now < endTime)
    {
        if (TryOpen(path, fileMode, fileAccess, fileShare, out stream))
            return true;
    }

    stream = null;
    return false;
}

public static bool TryOpen(string path,
                           FileMode fileMode,
                           FileAccess fileAccess,
                           FileShare fileShare,
                           out Stream stream)
{
    try
    {
        stream = File.Open(path, fileMode, fileAccess, fileShare);
        return true;
    }
    catch (IOException e)
    {
        if (!FileIsLocked(e))
            throw;

        stream = null;
        return false;
    }
}

private const uint HRFileLocked = 0x80070020;
private const uint HRPortionOfFileLocked = 0x80070021;

private static bool FileIsLocked(IOException ioException)
{
    var errorCode = (uint)Marshal.GetHRForException(ioException);
    return errorCode == HRFileLocked || errorCode == HRPortionOfFileLocked;
}

Usage:

private void Sample(string filePath)
{
    Stream stream = null;

    try
    {
        var timeOut = TimeSpan.FromSeconds(1);

        if (!TryOpen(filePath,
                     FileMode.Open,
                     FileAccess.ReadWrite,
                     FileShare.ReadWrite,
                     timeOut,
                     out stream))
            return;

        // Use stream...
    }
    finally
    {
        if (stream != null)
            stream.Close();
    }
}

window.history.pushState refreshing the browser

The short answer is that history.pushState (not History.pushState, which would throw an exception, the window part is optional) will never do what you suggest.

If pages are refreshing, then it is caused by other things that you are doing (for example, you might have code running that goes to a new location in the case of the address bar changing).

history.pushState({urlPath:'/page2.php'},"",'/page2.php') works exactly like it is supposed to in the latest versions of Chrome, IE and Firefox for me and my colleagues.

In fact you can put whatever you like into the function: history.pushState({}, '', 'So long and thanks for all the fish.not a real file').

If you post some more code (with special attention for code nearby the history.pushState and anywhere document.location is used), then we'll be more than happy to help you figure out where exactly this issue is coming from.

If you post more code, I'll update this answer (I have your question favourited) :).

Stopping Docker containers by image name - Ubuntu

I made a /usr/local/bin/docker.stop that takes in the image name (assumes you only have one running).

docker stop $(docker ps -q -f "name=$1")

What exactly is std::atomic?

std::atomic exists because many ISAs have direct hardware support for it

What the C++ standard says about std::atomic has been analyzed in other answers.

So now let's see what std::atomic compiles to to get a different kind of insight.

The main takeaway from this experiment is that modern CPUs have direct support for atomic integer operations, for example the LOCK prefix in x86, and std::atomic basically exists as a portable interface to those intructions: What does the "lock" instruction mean in x86 assembly? In aarch64, LDADD would be used.

This support allows for faster alternatives to more general methods such as std::mutex, which can make more complex multi-instruction sections atomic, at the cost of being slower than std::atomic because std::mutex it makes futex system calls in Linux, which is way slower than the userland instructions emitted by std::atomic, see also: Does std::mutex create a fence?

Let's consider the following multi-threaded program which increments a global variable across multiple threads, with different synchronization mechanisms depending on which preprocessor define is used.

main.cpp

#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

size_t niters;

#if STD_ATOMIC
std::atomic_ulong global(0);
#else
uint64_t global = 0;
#endif

void threadMain() {
    for (size_t i = 0; i < niters; ++i) {
#if LOCK
        __asm__ __volatile__ (
            "lock incq %0;"
            : "+m" (global),
              "+g" (i) // to prevent loop unrolling
            :
            :
        );
#else
        __asm__ __volatile__ (
            ""
            : "+g" (i) // to prevent he loop from being optimized to a single add
            : "g" (global)
            :
        );
        global++;
#endif
    }
}

int main(int argc, char **argv) {
    size_t nthreads;
    if (argc > 1) {
        nthreads = std::stoull(argv[1], NULL, 0);
    } else {
        nthreads = 2;
    }
    if (argc > 2) {
        niters = std::stoull(argv[2], NULL, 0);
    } else {
        niters = 10;
    }
    std::vector<std::thread> threads(nthreads);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i] = std::thread(threadMain);
    for (size_t i = 0; i < nthreads; ++i)
        threads[i].join();
    uint64_t expect = nthreads * niters;
    std::cout << "expect " << expect << std::endl;
    std::cout << "global " << global << std::endl;
}

GitHub upstream.

Compile, run and disassemble:

comon="-ggdb3 -O3 -std=c++11 -Wall -Wextra -pedantic main.cpp -pthread"
g++ -o main_fail.out                    $common
g++ -o main_std_atomic.out -DSTD_ATOMIC $common
g++ -o main_lock.out       -DLOCK       $common

./main_fail.out       4 100000
./main_std_atomic.out 4 100000
./main_lock.out       4 100000

gdb -batch -ex "disassemble threadMain" main_fail.out
gdb -batch -ex "disassemble threadMain" main_std_atomic.out
gdb -batch -ex "disassemble threadMain" main_lock.out

Extremely likely "wrong" race condition output for main_fail.out:

expect 400000
global 100000

and deterministic "right" output of the others:

expect 400000
global 400000

Disassembly of main_fail.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     mov    0x29b5(%rip),%rcx        # 0x5140 <niters>
   0x000000000000278b <+11>:    test   %rcx,%rcx
   0x000000000000278e <+14>:    je     0x27b4 <threadMain()+52>
   0x0000000000002790 <+16>:    mov    0x29a1(%rip),%rdx        # 0x5138 <global>
   0x0000000000002797 <+23>:    xor    %eax,%eax
   0x0000000000002799 <+25>:    nopl   0x0(%rax)
   0x00000000000027a0 <+32>:    add    $0x1,%rax
   0x00000000000027a4 <+36>:    add    $0x1,%rdx
   0x00000000000027a8 <+40>:    cmp    %rcx,%rax
   0x00000000000027ab <+43>:    jb     0x27a0 <threadMain()+32>
   0x00000000000027ad <+45>:    mov    %rdx,0x2984(%rip)        # 0x5138 <global>
   0x00000000000027b4 <+52>:    retq

Disassembly of main_std_atomic.out:

   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a6 <threadMain()+38>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock addq $0x1,0x299f(%rip)        # 0x5138 <global>
   0x0000000000002799 <+25>:    add    $0x1,%rax
   0x000000000000279d <+29>:    cmp    %rax,0x299c(%rip)        # 0x5140 <niters>
   0x00000000000027a4 <+36>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a6 <+38>:    retq   

Disassembly of main_lock.out:

Dump of assembler code for function threadMain():
   0x0000000000002780 <+0>:     endbr64 
   0x0000000000002784 <+4>:     cmpq   $0x0,0x29b4(%rip)        # 0x5140 <niters>
   0x000000000000278c <+12>:    je     0x27a5 <threadMain()+37>
   0x000000000000278e <+14>:    xor    %eax,%eax
   0x0000000000002790 <+16>:    lock incq 0x29a0(%rip)        # 0x5138 <global>
   0x0000000000002798 <+24>:    add    $0x1,%rax
   0x000000000000279c <+28>:    cmp    %rax,0x299d(%rip)        # 0x5140 <niters>
   0x00000000000027a3 <+35>:    ja     0x2790 <threadMain()+16>
   0x00000000000027a5 <+37>:    retq

Conclusions:

  • the non-atomic version saves the global to a register, and increments the register.

    Therefore, at the end, very likely four writes happen back to global with the same "wrong" value of 100000.

  • std::atomic compiles to lock addq. The LOCK prefix makes the following inc fetch, modify and update memory atomically.

  • our explicit inline assembly LOCK prefix compiles to almost the same thing as std::atomic, except that our inc is used instead of add. Not sure why GCC chose add, considering that our INC generated a decoding 1 byte smaller.

ARMv8 could use either LDAXR + STLXR or LDADD in newer CPUs: How do I start threads in plain C?

Tested in Ubuntu 19.10 AMD64, GCC 9.2.1, Lenovo ThinkPad P51.

How to create a WPF Window without a border that can be resized via a grip only?

Sample here:

<Style TargetType="Window" x:Key="DialogWindow">
        <Setter Property="AllowsTransparency" Value="True"/>
        <Setter Property="WindowStyle" Value="None"/>
        <Setter Property="ResizeMode" Value="CanResizeWithGrip"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Window}">
                    <Border BorderBrush="Black" BorderThickness="3" CornerRadius="10" Height="{TemplateBinding Height}"
                            Width="{TemplateBinding Width}" Background="Gray">
                        <DockPanel>
                            <Grid DockPanel.Dock="Top">
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition></ColumnDefinition>
                                    <ColumnDefinition Width="50"/>
                                </Grid.ColumnDefinitions>
                                <Label Height="35" Grid.ColumnSpan="2"
                                       x:Name="PART_WindowHeader"                                            
                                       HorizontalAlignment="Stretch" 
                                       VerticalAlignment="Stretch"/>
                                <Button Width="15" Height="15" Content="x" Grid.Column="1" x:Name="PART_CloseButton"/>
                            </Grid>
                            <Border HorizontalAlignment="Stretch" VerticalAlignment="Stretch" 
                                        Background="LightBlue" CornerRadius="0,0,10,10" 
                                        Grid.ColumnSpan="2"
                                        Grid.RowSpan="2">
                                <Grid>
                                    <Grid.ColumnDefinitions>
                                        <ColumnDefinition/>
                                        <ColumnDefinition Width="20"/>
                                    </Grid.ColumnDefinitions>
                                    <Grid.RowDefinitions>
                                        <RowDefinition Height="*"/>
                                        <RowDefinition Height="20"></RowDefinition>
                                    </Grid.RowDefinitions>
                                    <ResizeGrip Width="10" Height="10" Grid.Column="1" VerticalAlignment="Bottom" Grid.Row="1"/>
                                </Grid>
                            </Border>
                        </DockPanel>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

JQuery / JavaScript - trigger button click from another button click event

If it does not work by using the click() method like suggested in the accepted answer, then you can try this:

//trigger second button
$("#second").mousedown();
$("#second").mouseup();

Deleting a local branch with Git

Ran into this today and switching to another branch didn't help. It turned out that somehow my worktree information had gotten corrupted and there was a worktree with the same folder path as my working directory with a HEAD pointing at the branch (git worktree list). I deleted the .git/worktree/ folder that was referencing it and git branch -d worked.

download file using an ajax request

You actually don't need ajax at all for this. If you just set "download.php" as the href on the button, or, if it's not a link use:

window.location = 'download.php';

The browser should recognise the binary download and not load the actual page but just serve the file as a download.

Jquery insert new row into table at a certain index

I know it's coming late but for those people who want to implement it purely using the JavaScript , here's how you can do it:

  1. Get the reference to the current tr which is clicked.
  2. Make a new tr DOM element.
  3. Add it to the referred tr parent node.

HTML:

<table>
     <tr>
                    <td>
                        <button id="0" onclick="addRow()">Expand</button>
                    </td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
     </tr>

     <tr>
                    <td>
                        <button id="1" onclick="addRow()">Expand</button>
                    </td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
     </tr>
     <tr>
                    <td>
                        <button id="2" onclick="addRow()">Expand</button>
                    </td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
                    <td>abc</td>
     </tr>

In JavaScript:

function addRow() {
        var evt = event.srcElement.id;
        var btn_clicked = document.getElementById(evt);
        var tr_referred = btn_clicked.parentNode.parentNode;
        var td = document.createElement('td');
        td.innerHTML = 'abc';
        var tr = document.createElement('tr');
        tr.appendChild(td);
        tr_referred.parentNode.insertBefore(tr, tr_referred.nextSibling);
        return tr;
    }

This will add the new table row exactly below the row on which the button is clicked.

Create MSI or setup project with Visual Studio 2012

There is some progress for Visual studio 2013 developers :-D woot woot! See blog post Visual Studio Installer Projects Extension.

Link and information were retrieved from Brian Harry's blog post Creating installers with Visual Studio.

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

I recommend using this:

  1. Retrieve the father Intent.

    Intent intentParent = getIntent();
    
  2. Convey the message directly.

    setResult(RESULT_OK, intentParent);
    

This prevents the loss of its activity which would generate a null data error.

Color theme for VS Code integrated terminal

Simply. You can go to 'File -> Preferences -> Color Theme' option in visual studio and change the color of you choice.

How to run php files on my computer

You have to run a web server (e.g. Apache) and browse to your localhost, mostly likely on port 80.

What you really ought to do is install an all-in-one package like XAMPP, it bundles Apache, MySQL PHP, and Perl (if you were so inclined) as well as a few other tools that work with Apache and MySQL - plus it's cross platform (that's what the 'X' in 'XAMPP' stands for).

Once you install XAMPP (and there is an installer, so it shouldn't be hard) open up the control panel for XAMPP and then click the "Start" button next to Apache - note that on applications that require a database, you'll also need to start MySQL (and you'll be able to interface with it through phpMyAdmin). Once you've started Apache, you can browse to http://localhost.

Again, regardless of whether or not you choose XAMPP (which I would recommend), you should just have to start Apache.

Changing a specific column name in pandas DataFrame

What about?

df.columns.values[2] = "new_name"

What is the use of the JavaScript 'bind' method?

Bind Method

A bind implementation might look something like so:

Function.prototype.bind = function () {
  const self = this;
  const args = [...arguments];
  const context = args.shift();

  return function () {
    return self.apply(context, args.concat([...arguments]));
  };
};

The bind function can take any number of arguments and return a new function.

The new function will call the original function using the JS Function.prototype.apply method.
The apply method will use the first argument passed to the target function as its context (this), and the second array argument of the apply method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).

An example can look something like so:

_x000D_
_x000D_
function Fruit(emoji) {_x000D_
  this.emoji = emoji;_x000D_
}_x000D_
_x000D_
Fruit.prototype.show = function () {_x000D_
  console.log(this.emoji);_x000D_
};_x000D_
_x000D_
const apple = new Fruit('');_x000D_
const orange = new Fruit('');_x000D_
_x000D_
apple.show();  // _x000D_
orange.show(); // _x000D_
_x000D_
const fruit1 = apple.show;_x000D_
const fruit2 = apple.show.bind();_x000D_
const fruit3 = apple.show.bind(apple);_x000D_
const fruit4 = apple.show.bind(orange);_x000D_
_x000D_
fruit1(); // undefined_x000D_
fruit2(); // undefined_x000D_
fruit3(); // _x000D_
fruit4(); // 
_x000D_
_x000D_
_x000D_

Docker Error bind: address already in use

In some cases it is critical to perform a more in-depth debugging to the problem before stopping a container or killing a process.

Consider following the checklist below:

1) Check you current docker compose environment
Run docker-compose ps.
If port is in use by another container, stop it with docker-compose stop <service-name-in-compose-file> or remove it by replacing stop with rm.

2) Check the containers running outside your current workspace
Run docker ps to see list of all containers running under your host.
If you find the port is in use by another container, you can stop it with docker stop <container-id>.
(*) Because you're not under the scope of the origin compose environment - it is a good practice first to use docker inspect to gather more information about the container that you're about to stop.

3) Check if port is used by other processes running on the host
For example if the port is 6379 run:

$ sudo netstat -ltnp | grep ':6379'
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      915/redis-server 12 
tcp6       0      0 ::1:6379                :::*                    LISTEN      915/redis-server 12

(*) You can also use the lsof command which is mainly used to retrieve information about files that are opened by various processes (I suggest running netstat before that).

So, In case of the output above the PID is 915. Now you can run:

$ ps j 915
 PPID   PID  PGID   SID TTY      TPGID STAT   UID   TIME COMMAND
    1   915   915   915 ?           -1 Ssl    123   0:11 /usr/bin/redis-server 127.0.0.1:6379

And see the ID of the parent process (PPID) and the execution command.
You can also run: $ pstree -s <PID> to a visual display of the process and its related processes.

In our case we can see that the process probably is a daemon (PPID is 1) - In that case consider running:
A) $ cat /proc/<PID>/status in order to get a more in-depth information about the process like the number of threads spawned by the process, its capabilities, etc'.
B) $ systemctl status <PID> in order to see the unit that caused the creation of a specific process. If the service is not critical - you can stop and disable the service.

4) Restart Docker service
Run: sudo service docker restart.

5) You reached this point and..
Only if its not placing your system at risk - consider restarting the server.

Classpath resource not found when running as jar

Based on Andy's answer I used the following to get an input streams of all YAMLs under a directory and sub-directories in resources (Note that the path passed doesn't begin with /):

private static Stream<InputStream> getInputStreamsFromClasspath(
        String path,
        PathMatchingResourcePatternResolver resolver
) {
    try {
        return Arrays.stream(resolver.getResources("/" + path + "/**/*.yaml"))
                .filter(Resource::exists)
                .map(resource -> {
                    try {
                        return resource.getInputStream();
                    } catch (IOException e) {
                        return null;
                    }
                })
                .filter(Objects::nonNull);
    } catch (IOException e) {
        logger.error("Failed to get definitions from directory {}", path, e);
        return Stream.of();
    }
}

PHP - Redirect and send data via POST

It would involve the cURL PHP extension.

$ch = curl_init('http://www.provider.com/process.jsp');
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, "id=12345&name=John");
curl_setopt($ch, CURLOPT_RETURNTRANSFER , 1);  // RETURN THE CONTENTS OF THE CALL
$resp = curl_exec($ch);

ASP.NET Background image

write code in body tag like this

<body style="background-image: url('Image URL');" >
</body>

How can I access Oracle from Python?

Here is how my code looks like. It also shows an example of how to use query parameters using a dictionary. It works on using Python 3.6:

import cx_Oracle

CONN_INFO = {
    'host': 'xxx.xx.xxx.x',
    'port': 12345,
    'user': 'SOME_SCHEMA',
    'psw': 'SECRETE',
    'service': 'service.server.com'
}

CONN_STR = '{user}/{psw}@{host}:{port}/{service}'.format(**CONN_INFO)

QUERY = '''
    SELECT
        *
    FROM
        USER
    WHERE
        NAME = :name
'''


class DB:
    def __init__(self):
        self.conn = cx_Oracle.connect(CONN_STR)

    def query(self, query, params=None):
        cursor = self.conn.cursor()
        result = cursor.execute(query, params).fetchall()
        cursor.close()
        return result


db = DB()
result = db.query(QUERY, {'name': 'happy'})

Git Push Error: insufficient permission for adding an object to repository database

For my case none of the suggestions worked. I'm on Windows and this worked for me:

  • Copy the remote repo into another folder
  • Share the folder and give appropriate permissions.
  • Make sure you can access the folder from your local machine.
  • Add this repo as another remote repo in your local repo. (git remote add foo //SERVERNAME/path/to/copied/git)
  • Push to foo. git push foo master. Did it worked? Great! Now delete not-working repo and rename this into whatever it was before. Make sure permissions and share property remains the same.

Split text with '\r\n'

The problem is not with the splitting but rather with the WriteLine. A \n in a string printed with WriteLine will produce an "extra" line.

Example

var text = 
  "somet interesting text\n" +
  "some text that should be in the same line\r\n" +
  "some text should be in another line";

string[] stringSeparators = new string[] { "\r\n" };
string[] lines = text.Split(stringSeparators, StringSplitOptions.None);
Console.WriteLine("Nr. Of items in list: " + lines.Length); // 2 lines
foreach (string s in lines)
{
   Console.WriteLine(s); //But will print 3 lines in total.
}

To fix the problem remove \n before you print the string.

Console.WriteLine(s.Replace("\n", ""));

stale element reference: element is not attached to the page document

This could be done in newer versions of selenium in JS( but all supporting stalenessOf will work):

 const { until } = require('selenium-webdriver');
 driver.wait(
        until.stalenessOf(
          driver.findElement(
            By.css(SQLQueriesByPhpMyAdminSelectors.sqlQueryArea)
          )
        ),
        5 * 1000
      )
      .then( driver.findElement(By.css(SQLQueriesByPhpMyAdminSelectors.sqlQueryArea))
      .sendKeys(sqlString)
  );

SQL left join vs multiple tables on FROM line?

The JOIN syntax keeps conditions near the table they apply to. This is especially useful when you join a large amount of tables.

By the way, you can do an outer join with the first syntax too:

WHERE a.x = b.x(+)

Or

WHERE a.x *= b.x

Or

WHERE a.x = b.x or a.x not in (select x from b)

Message "Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout"

For Jest 24.9+, you can also set the timeout from the command line by adding --testTimeout.

Here's an excerpt from its documentation:

--testTimeout=<number>
Default timeout of a test in milliseconds. Default value: 5000.

Return current date plus 7 days

$now = date('Y-m-d');
$start_date = strtotime($now);
$end_date = strtotime("+7 day", $start_date);
echo date('Y-m-d', $start_date) . '  + 7 days =  ' . date('Y-m-d', $end_date);

Unzip files (7-zip) via cmd command

Regarding Phil Street's post:

It may actually be installed in your 32-bit program folder instead of your default x64, if you're running 64-bit OS. Check to see where 7-zip is installed, and if it is in Program Files (x86) then try using this instead:

PATH=%PATH%;C:\Program Files (x86)\7-Zip

How do I tell if .NET 3.5 SP1 is installed?

Look at HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\. One of these must be true:

  • The Version value in that key should be 3.5.30729.01
  • Or the SP value in the same key should be 1

In C# (taken from the first comment), you could do something along these lines:

const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();

Why Is Subtracting These Two Times (in 1927) Giving A Strange Result?

As explained by others, there's a time discontinuity there. There are two possible timezone offsets for 1927-12-31 23:54:08 at Asia/Shanghai, but only one offset for 1927-12-31 23:54:07. So, depending on which offset is used, there's either a one second difference or a 5 minutes and 53 seconds difference.

This slight shift of offsets, instead of the usual one-hour daylight savings (summer time) we are used to, obscures the problem a bit.

Note that the 2013a update of the timezone database moved this discontinuity a few seconds earlier, but the effect would still be observable.

The new java.time package on Java 8 let use see this more clearly, and provide tools to handle it. Given:

DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
dtfb.append(DateTimeFormatter.ISO_LOCAL_DATE);
dtfb.appendLiteral(' ');
dtfb.append(DateTimeFormatter.ISO_LOCAL_TIME);
DateTimeFormatter dtf = dtfb.toFormatter();
ZoneId shanghai = ZoneId.of("Asia/Shanghai");

String str3 = "1927-12-31 23:54:07";  
String str4 = "1927-12-31 23:54:08";  

ZonedDateTime zdt3 = LocalDateTime.parse(str3, dtf).atZone(shanghai);
ZonedDateTime zdt4 = LocalDateTime.parse(str4, dtf).atZone(shanghai);

Duration durationAtEarlierOffset = Duration.between(zdt3.withEarlierOffsetAtOverlap(), zdt4.withEarlierOffsetAtOverlap());

Duration durationAtLaterOffset = Duration.between(zdt3.withLaterOffsetAtOverlap(), zdt4.withLaterOffsetAtOverlap());

Then durationAtEarlierOffset will be one second, while durationAtLaterOffset will be five minutes and 53 seconds.

Also, these two offsets are the same:

// Both have offsets +08:05:52
ZoneOffset zo3Earlier = zdt3.withEarlierOffsetAtOverlap().getOffset();
ZoneOffset zo3Later = zdt3.withLaterOffsetAtOverlap().getOffset();

But these two are different:

// +08:05:52
ZoneOffset zo4Earlier = zdt4.withEarlierOffsetAtOverlap().getOffset();

// +08:00
ZoneOffset zo4Later = zdt4.withLaterOffsetAtOverlap().getOffset();

You can see the same problem comparing 1927-12-31 23:59:59 with 1928-01-01 00:00:00, though, in this case, it is the earlier offset that produces the longer divergence, and it is the earlier date that has two possible offsets.

Another way to approach this is to check whether there's a transition going on. We can do this like this:

// Null
ZoneOffsetTransition zot3 = shanghai.getRules().getTransition(ld3.toLocalDateTime);

// An overlap transition
ZoneOffsetTransition zot4 = shanghai.getRules().getTransition(ld3.toLocalDateTime);

You can check whether the transition is an overlap where there's more than one valid offset for that date/time or a gap where that date/time is not valid for that zone id - by using the isOverlap() and isGap() methods on zot4.

I hope this helps people handle this sort of issue once Java 8 becomes widely available, or to those using Java 7 who adopt the JSR 310 backport.

Why can't I have "public static const string S = "stuff"; in my Class?

A const member is considered static by the compiler, as well as implying constant value semantics, which means references to the constant might be compiled into the using code as the value of the constant member, instead of a reference to the member.

In other words, a const member containing the value 10, might get compiled into code that uses it as the number 10, instead of a reference to the const member.

This is different from a static readonly field, which will always be compiled as a reference to the field.

Note, this is pre-JIT. When the JIT'ter comes into play, it might compile both these into the target code as values.

Reset the Value of a Select Box

use the .val('') setter

jsfiddle example

$('select').val('1');

C++11 rvalues and move semantics confusion (return statement)

First example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> &&rval_ref = return_vector();

The first example returns a temporary which is caught by rval_ref. That temporary will have its life extended beyond the rval_ref definition and you can use it as if you had caught it by value. This is very similar to the following:

const std::vector<int>& rval_ref = return_vector();

except that in my rewrite you obviously can't use rval_ref in a non-const manner.

Second example

std::vector<int>&& return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

In the second example you have created a run time error. rval_ref now holds a reference to the destructed tmp inside the function. With any luck, this code would immediately crash.

Third example

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return std::move(tmp);
}

std::vector<int> &&rval_ref = return_vector();

Your third example is roughly equivalent to your first. The std::move on tmp is unnecessary and can actually be a performance pessimization as it will inhibit return value optimization.

The best way to code what you're doing is:

Best practice

std::vector<int> return_vector(void)
{
    std::vector<int> tmp {1,2,3,4,5};
    return tmp;
}

std::vector<int> rval_ref = return_vector();

I.e. just as you would in C++03. tmp is implicitly treated as an rvalue in the return statement. It will either be returned via return-value-optimization (no copy, no move), or if the compiler decides it can not perform RVO, then it will use vector's move constructor to do the return. Only if RVO is not performed, and if the returned type did not have a move constructor would the copy constructor be used for the return.

Warning: X may be used uninitialized in this function

one has not been assigned so points to an unpredictable location. You should either place it on the stack:

Vector one;
one.a = 12;
one.b = 13;
one.c = -11

or dynamically allocate memory for it:

Vector* one = malloc(sizeof(*one))
one->a = 12;
one->b = 13;
one->c = -11
free(one);

Note the use of free in this case. In general, you'll need exactly one call to free for each call made to malloc.

time delayed redirect?

<meta http-equiv="refresh" content="2; url=http://example.com/" />

Here 2 is delay in seconds.

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

SOAP 1.1 uses namespace http://schemas.xmlsoap.org/wsdl/soap/

SOAP 1.2 uses namespace http://schemas.xmlsoap.org/wsdl/soap12/

The wsdl is able to define operations under soap 1.1 and soap 1.2 at the same time in the same wsdl. Thats useful if you need to evolve your wsdl to support new functionality that requires soap 1.2 (eg. MTOM), in this case you dont need to create a new service but just evolve the original one.

How to do ToString for a possibly null object?

Even though this is an old question and the OP asked for C# I would like to share a VB.Net solution for those, who work with VB.Net rather than C#:

Dim myObj As Object = Nothing
Dim s As String = If(myObj, "").ToString()

myObj = 42
s = If(myObj, "").ToString()

Unfortunatly VB.Net doesn't allow the ?-operator after a variable so myObj?.ToString isn't valid (at least not in .Net 4.5, which I used for testing the solution). Instead I use the If to return an empty string in case myObj ist Nothing. So the first Tostring-Call return an an empty string, while the second (where myObj is not Nothing) returns "42".

Auto height of div

According to this, you need to assign a height to the element in which the div is contained in order for 100% height to work. Does that work for you?

Why does sudo change the PATH?

$PATH is an environment variable and it means that value of $PATH can differ for another users.

When you are doing login into your system then your profile setting decide the value of the $PATH.

Now, lets take a look:-

User       |        Value of $PATH
--------------------------
root                /var/www
user1               /var/www/user1
user2               /var/www/html/private

Suppose that these are the values of $PATH for different user. Now when you are executing any command with sudo then in actual meaning root user executes that command .

You can confirm by executing these commands on terminal :-

user@localhost$ whoami
username
user@localhost$ sudo whoami
root
user@localhost$ 

This is the reason. I think its clear to you.

Using Environment Variables with Vue.js

  1. Create two files in root folder (near by package.json) .env and .env.production
  2. Add variables to theese files with prefix VUE_APP_ eg: VUE_APP_WHATEVERYOUWANT
  3. serve uses .env and build uses .env.production
  4. In your components (vue or js), use process.env.VUE_APP_WHATEVERYOUWANT to call value
  5. Don't forget to restart serve if it is currently running
  6. Clear browser cache

Be sure you are using vue-cli version 3 or above

For more information: https://cli.vuejs.org/guide/mode-and-env.html

Get an object attribute

If you need to fetch an object's property dynamically, use the getattr() function: getattr(user, "fullName") - or to elaborate:

user = User()
property = "fullName"
name = getattr(user, property)

Otherwise just use user.fullName.

How do I raise an exception in Rails so it behaves like other Rails exceptions?

You can do it like this:

class UsersController < ApplicationController
  ## Exception Handling
  class NotActivated < StandardError
  end

  rescue_from NotActivated, :with => :not_activated

  def not_activated(exception)
    flash[:notice] = "This user is not activated."
    Event.new_event "Exception: #{exception.message}", current_user, request.remote_ip
    redirect_to "/"
  end

  def show
      // Do something that fails..
      raise NotActivated unless @user.is_activated?
  end
end

What you're doing here is creating a class "NotActivated" that will serve as Exception. Using raise, you can throw "NotActivated" as an Exception. rescue_from is the way of catching an Exception with a specified method (not_activated in this case). Quite a long example, but it should show you how it works.

Best wishes,
Fabian

What is the point of "Initial Catalog" in a SQL Server connection string?

If the user name that is in the connection string has access to more then one database you have to specify the database you want the connection string to connect to. If your user has only one database available then you are correct that it doesn't matter. But it is good practice to put this in your connection string.