Programs & Examples On #Semaphore

A semaphore is a synchronization primitive that tracks how many of a limited number of resources are available.

Is there a Mutex in Java?

Each object's lock is little different from Mutex/Semaphore design. For example there is no way to correctly implement traversing linked nodes with releasing previous node's lock and capturing next one. But with mutex it is easy to implement:

Node p = getHead();
if (p == null || x == null) return false;
p.lock.acquire();  // Prime loop by acquiring first lock.
// If above acquire fails due to interrupt, the method will
//   throw InterruptedException now, so there is no need for
//   further cleanup.
for (;;) {
Node nextp = null;
boolean found;
try { 
 found = x.equals(p.item); 
 if (!found) { 
   nextp = p.next; 
   if (nextp != null) { 
     try {      // Acquire next lock 
                //   while still holding current 
       nextp.lock.acquire(); 
     } 
     catch (InterruptedException ie) { 
      throw ie;    // Note that finally clause will 
                   //   execute before the throw 
     } 
   } 
 } 
}finally {     // release old lock regardless of outcome 
   p.lock.release();
} 

Currently, there is no such class in java.util.concurrent, but you can find Mutext implementation here Mutex.java. As for standard libraries, Semaphore provides all this functionality and much more.

What is a semaphore?

@Craig:

A semaphore is a way to lock a resource so that it is guaranteed that while a piece of code is executed, only this piece of code has access to that resource. This keeps two threads from concurrently accesing a resource, which can cause problems.

This is not restricted to only one thread. A semaphore can be configured to allow a fixed number of threads to access a resource.

Difference between binary semaphore and mutex

The Toilet example is an enjoyable analogy:

Mutex:

Is a key to a toilet. One person can have the key - occupy the toilet - at the time. When finished, the person gives (frees) the key to the next person in the queue.

Officially: "Mutexes are typically used to serialise access to a section of re-entrant code that cannot be executed concurrently by more than one thread. A mutex object only allows one thread into a controlled section, forcing other threads which attempt to gain access to that section to wait until the first thread has exited from that section." Ref: Symbian Developer Library

(A mutex is really a semaphore with value 1.)

Semaphore:

Is the number of free identical toilet keys. Example, say we have four toilets with identical locks and keys. The semaphore count - the count of keys - is set to 4 at beginning (all four toilets are free), then the count value is decremented as people are coming in. If all toilets are full, ie. there are no free keys left, the semaphore count is 0. Now, when eq. one person leaves the toilet, semaphore is increased to 1 (one free key), and given to the next person in the queue.

Officially: "A semaphore restricts the number of simultaneous users of a shared resource up to a maximum number. Threads can request access to the resource (decrementing the semaphore), and can signal that they have finished using the resource (incrementing the semaphore)." Ref: Symbian Developer Library

Semaphore vs. Monitors - what's the difference?

A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal() on the semaphore when a file is downloaded. The consumer calls wait() on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.

A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait() can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.

A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.

A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized keyword. The synchronized keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.

semaphore implementation

Please check this out below sample code for semaphore implementation(Lock and unlock).

    #include<stdio.h>
    #include<stdlib.h>
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include<string.h>
    #include<malloc.h>
    #include <sys/sem.h>
    int main()
    {
            int key,share_id,num;
            char *data;
            int semid;
            struct sembuf sb={0,-1,0};
            key=ftok(".",'a');
            if(key == -1 ) {
                    printf("\n\n Initialization Falied of shared memory \n\n");
                    return 1;
            }
            share_id=shmget(key,1024,IPC_CREAT|0744);
            if(share_id == -1 ) {
                    printf("\n\n Error captured while share memory allocation\n\n");
                    return 1;
            }
            data=(char *)shmat(share_id,(void *)0,0);
            strcpy(data,"Testing string\n");
            if(!fork()) { //Child Porcess
                 sb.sem_op=-1; //Lock
                 semop(share_id,(struct sembuf *)&sb,1);

                 strncat(data,"feeding form child\n",20);

                 sb.sem_op=1;//Unlock
                 semop(share_id,(struct sembuf *)&sb,1);
                 _Exit(0);
            } else {     //Parent Process
              sb.sem_op=-1; //Lock
              semop(share_id,(struct sembuf *)&sb,1);

               strncat(data,"feeding form parent\n",20);

              sb.sem_op=1;//Unlock
              semop(share_id,(struct sembuf *)&sb,1);

            }
            return 0;
    }

Lock, mutex, semaphore... what's the difference?

Wikipedia has a great section on the differences between Semaphores and Mutexes:

A mutex is essentially the same thing as a binary semaphore and sometimes uses the same basic implementation. The differences between them are:

Mutexes have a concept of an owner, which is the process that locked the mutex. Only the process that locked the mutex can unlock it. In contrast, a semaphore has no concept of an owner. Any process can unlock a semaphore.

Unlike semaphores, mutexes provide priority inversion safety. Since the mutex knows its current owner, it is possible to promote the priority of the owner whenever a higher-priority task starts waiting on the mutex.

Mutexes also provide deletion safety, where the process holding the mutex cannot be accidentally deleted. Semaphores do not provide this.

What is mutex and semaphore in Java ? What is the main difference?

Semaphore:

A counting semaphore. Conceptually, a semaphore maintains a set of permits. Each acquire() blocks if necessary until a permit is available, and then takes it. Each release() adds a permit, potentially releasing a blocking acquirer. However, no actual permit objects are used; the Semaphore just keeps a count of the number available and acts accordingly.

Semaphores are often used to restrict the number of threads than can access some (physical or logical) resource

Java does not have built-in Mutex API. But it can be implemented as binary semaphore.

A semaphore initialized to one, and which is used such that it only has at most one permit available, can serve as a mutual exclusion lock. This is more commonly known as a binary semaphore, because it only has two states: one permit available, or zero permits available.

When used in this way, the binary semaphore has the property (unlike many Lock implementations), that the "lock" can be released by a thread other than the owner (as semaphores have no notion of ownership). This can be useful in some specialized contexts, such as deadlock recovery.

So key differences between Semaphore and Mutex:

  1. Semaphore restrict number of threads to access a resource throuhg permits. Mutex allows only one thread to access resource.

  2. No threads owns Semaphore. Threads can update number of permits by calling acquire() and release() methods. Mutexes should be unlocked only by the thread holding the lock.

  3. When a mutex is used with condition variables, there is an implied bracketing—it is clear which part of the program is being protected. This is not necessarily the case for a semaphore, which might be called the go to of concurrent programming—it is powerful but too easy to use in an unstructured, indeterminate way.

"The semaphore timeout period has expired" error for USB connection

I had this problem as well on two different Windows computers when communicating with a Arduino Leonardo. The reliable solution was:

  • Find the COM port in device manager and open the device properties.
  • Open the "Port Settings" tab, and click the advanced button.
  • There, uncheck the box "Use FIFO buffers (required 16550 compatible UART), and press OK.

Unfortunately, I don't know what this feature does, or how it affects this issue. After several PC restarts and a dozen device connection cycles, this is the only thing that reliably fixed the issue.

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

to remove all shared memory segments on FreeBSD

#!/bin/sh
for i in $(ipcs -m | awk '{ print $2 }' | sed 1,2d);
do
    echo "ipcrm -m $i"
    ipcrm -m $i
done

to remove all semaphores

#!/bin/sh
for i in $(ipcs -s | awk '{ print $2 }' | sed 1,2d);
do
    echo "ipcrm -s $i"
    ipcrm -s $i
done

When should we use mutex and when should we use semaphore

Binary semaphore and Mutex are different. From OS perspective, a binary semaphore and counting semaphore are implemented in the same way and a binary semaphore can have a value 0 or 1.

Mutex -> Can only be used for one and only purpose of mutual exclusion for a critical section of code.

Semaphore -> Can be used to solve variety of problems. A binary semaphore can be used for signalling and also solve mutual exclusion problem. When initialized to 0, it solves signalling problem and when initialized to 1, it solves mutual exclusion problem.

When the number of resources are more and needs to be synchronized, we can use counting semaphore.

In my blog, I have discussed these topics in detail.

https://designpatterns-oo-cplusplus.blogspot.com/2015/07/synchronization-primitives-mutex-and.html

Can Google Chrome open local links?

It's not really an anwser but a workaround to open a local link in chrome using python.

Copy the local link you want to run then run the code bellow (using a shortcut), it will open your link.

import win32clipboard
import os

win32clipboard.OpenClipboard()
clipboard_data= win32clipboard.GetClipboardData()
win32clipboard.CloseClipboard()

os.system("start "+clipboard_data)

How to display alt text for an image in chrome

You can put title attribute to tag.I hope it will work.

<img src="smiley.gif" title="Smiley face" width="42" height="42">

How to add title to seaborn boxplot

Seaborn box plot returns a matplotlib axes instance. Unlike pyplot itself, which has a method plt.title(), the corresponding argument for an axes is ax.set_title(). Therefore you need to call

sns.boxplot('Day', 'Count', data= gg).set_title('lalala')

A complete example would be:

import seaborn as sns
import matplotlib.pyplot as plt

tips = sns.load_dataset("tips")
sns.boxplot(x=tips["total_bill"]).set_title("LaLaLa")

plt.show()

Of course you could also use the returned axes instance to make it more readable:

ax = sns.boxplot('Day', 'Count', data= gg)
ax.set_title('lalala')
ax.set_ylabel('lololo')

Efficient way to rotate a list in python

I think you've got the most efficient way

def shift(l,n):
    n = n % len(l)  
    return l[-U:] + l[:-U]

store return json value in input hidden field

It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).

Anyway, if that is an array wrapper, you'll want something like this:

$('#my-hidden-field').val(theObject[0].id);

You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,

$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;

This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.

Drawing circles with System.Drawing

With this code you can easily draw a circle... C# is great and easy my friend

public partial class Form1 : Form
{


public Form1()
    {
        InitializeComponent();
    }

  private void button1_Click(object sender, EventArgs e)
    {
        Graphics myGraphics = base.CreateGraphics();
        Pen myPen = new Pen(Color.Red);
        SolidBrush mySolidBrush = new SolidBrush(Color.Red);
        myGraphics.DrawEllipse(myPen, 50, 50, 150, 150);
    }
 }

MySQL ON DUPLICATE KEY UPDATE for multiple rows insert in single query

Beginning with MySQL 8.0.19 you can use an alias for that row (see reference).

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
    AS new
ON DUPLICATE KEY UPDATE
    age = new.age
    ...

For earlier versions use the keyword VALUES (see reference, deprecated with MySQL 8.0.20).

INSERT INTO beautiful (name, age)
    VALUES
    ('Helen', 24),
    ('Katrina', 21),
    ('Samia', 22),
    ('Hui Ling', 25),
    ('Yumie', 29)
ON DUPLICATE KEY UPDATE
    age = VALUES(age),
     ...

How to access JSON Object name/value?

If you response is like {'customer':{'first_name':'John','last_name':'Cena'}}

var d = JSON.parse(response);
alert(d.customer.first_name); // contains "John"

Thanks,

How to close a Java Swing application from the code

Your JFrame default close action can be set to "DISPOSE_ON_CLOSE" instead of EXIT_ON_CLOSE (why people keep using EXIT_ON_CLOSE is beyond me).

If you have any undisposed windows or non-daemon threads, your application will not terminate. This should be considered a error (and solving it with System.exit is a very bad idea).

The most common culprits are java.util.Timer and a custom Thread you've created. Both should be set to daemon or must be explicitly killed.

If you want to check for all active frames, you can use Frame.getFrames(). If all Windows/Frames are disposed of, then use a debugger to check for any non-daemon threads that are still running.

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

Use of String.Format in JavaScript?

I just started porting Java's String.format() to JavaScript. You might find it useful too.

It supports basic stuff like this:

StringFormat.format("Hi %s, I like %s", ["Rob", "icecream"]);

Which results in

Hi Rob, I like icecream.

But also more advanced numberic formatting and date formatting like:

StringFormat.format("Duke's Birthday: %1$tA %1$te %1$tB, %1$tY", [new Date("2014-12-16")]);

Duke's Birthday: Tuesday 16 December, 2014

See for more in the examples.

See here: https://github.com/RobAu/javascript.string.format

Check if registry key exists using VBScript

I found the solution.

dim bExists
ssig="Unable to open registry key"

set wshShell= Wscript.CreateObject("WScript.Shell")
strKey = "HKEY_USERS\.Default\Software\Microsoft\Windows\CurrentVersion\Internet Settings\Digest\"
on error resume next
present = WshShell.RegRead(strKey)
if err.number<>0 then
    if right(strKey,1)="\" then    'strKey is a registry key
        if instr(1,err.description,ssig,1)<>0 then
            bExists=true
        else
            bExists=false
        end if
    else    'strKey is a registry valuename
        bExists=false
    end if
    err.clear
else
    bExists=true
end if
on error goto 0
if bExists=vbFalse then
    wscript.echo strKey & " does not exist."
else
    wscript.echo strKey & " exists."
end if

JSON - Iterate through JSONArray

for(int i = 0; i < getArray.size(); i++){
      Object object = getArray.get(i);
      // now do something with the Object
}

You need to check for the type:

The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object. [Source]

In your case, the elements will be of type JSONObject, so you need to cast to JSONObject and call JSONObject.names() to retrieve the individual keys.

How can I order a List<string>?

List<string> myCollection = new List<string>()
{
    "Bob", "Bob","Alex", "Abdi", "Abdi", "Bob", "Alex", "Bob","Abdi"
};

myCollection.Sort();
foreach (var name in myCollection.Distinct())
{
    Console.WriteLine(name + " " + myCollection.Count(x=> x == name));
}

output: Abdi 3 Alex 2 Bob 4

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

How to set zoom level in google map

Here is a function I use:

var map =  new google.maps.Map(document.getElementById('map'), {
            center: new google.maps.LatLng(52.2, 5),
            mapTypeId: google.maps.MapTypeId.ROADMAP,
            zoom: 7
        });

function zoomTo(level) {
        google.maps.event.addListener(map, 'zoom_changed', function () {
            zoomChangeBoundsListener = google.maps.event.addListener(map, 'bounds_changed', function (event) {
                if (this.getZoom() > level && this.initialZoom == true) {
                    this.setZoom(level);
                    this.initialZoom = false;
                }
                google.maps.event.removeListener(zoomChangeBoundsListener);
            });
        });
    }

Angular window resize event

I checked most of these answers. then decided to check out Angular documentation on Layout.

Angular has its own Observer for detecting different sizes and it is easy to implement into the component or a Service.

a simpl example would be:

_x000D_
_x000D_
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';_x000D_
_x000D_
@Component({...})_x000D_
class MyComponent {_x000D_
  constructor(breakpointObserver: BreakpointObserver) {_x000D_
    breakpointObserver.observe([_x000D_
      Breakpoints.HandsetLandscape,_x000D_
      Breakpoints.HandsetPortrait_x000D_
    ]).subscribe(result => {_x000D_
      if (result.matches) {_x000D_
        this.activateHandsetLayout();_x000D_
      }_x000D_
    });_x000D_
  }_x000D_
}
_x000D_
_x000D_
_x000D_

hope it helps

How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator

This is my solution, no warning, no errors, but perfect

let redStr: String = String(trimmStr[String.Index.init(encodedOffset: 0)..<String.Index.init(encodedOffset: 2)])
let greenStr: String = String(trimmStr[String.Index.init(encodedOffset: 3)..<String.Index.init(encodedOffset: 4)])
let blueStr: String = String(trimmStr[String.Index.init(encodedOffset: 5)..<String.Index.init(encodedOffset: 6)])

What's the difference between "git reset" and "git checkout"?

brief mnemonics:

git reset HEAD           :             index = HEAD
git checkout             : file_tree = index
git reset --hard HEAD    : file_tree = index = HEAD

Remove Datepicker Function dynamically

This is the solution I use. It has more lines but it will only create the datepicker once.

$('#txtSearch').datepicker({
    constrainInput:false,
    beforeShow: function(){
        var t = $('#ddlSearchType').val();
        if( ['Required Date', 'Submitted Date'].indexOf(t) ) {
            $('#txtSearch').prop('readonly', false);
            return false;
        }
        else $('#txtSearch').prop('readonly', true);
    }
});

The datepicker will not show unless the value of ddlSearchType is either "Required Date" or "Submitted Date"

How can I clear event subscriptions in C#?

This is my solution:

public class Foo : IDisposable
{
    private event EventHandler _statusChanged;
    public event EventHandler StatusChanged
    {
        add
        {
            _statusChanged += value;
        }
        remove
        {
            _statusChanged -= value;
        }
    }

    public void Dispose()
    {
        _statusChanged = null;
    }
}

You need to call Dispose() or use using(new Foo()){/*...*/} pattern to unsubscribe all members of invocation list.

Extract csv file specific columns to list in Python

A standard-lib version (no pandas)

This assumes that the first row of the csv is the headers

import csv

# open the file in universal line ending mode 
with open('test.csv', 'rU') as infile:
  # read the file as a dictionary for each row ({header : value})
  reader = csv.DictReader(infile)
  data = {}
  for row in reader:
    for header, value in row.items():
      try:
        data[header].append(value)
      except KeyError:
        data[header] = [value]

# extract the variables you want
names = data['name']
latitude = data['latitude']
longitude = data['longitude']

Perfect 100% width of parent container for a Bootstrap input?

Use .container-fluid, if you want to full-width as parent, spanning the entire width of your viewport.

Setup a Git server with msysgit on Windows

After following Tim Davis' guide and Steve's follow-up, here is what I did:

Server PC

  1. Install CopSSH, msysgit.
  2. When creating the CopSSH user, uncheck Password Authentication and check Public Key Authentication so your public/private keys will work.
  3. Create public/private keys using PuTTygen. put both keys in the user's CopSSH/home/user/.ssh directory.
  4. Add the following to the user's CopSSH/home/user/.bashrc file:

    GITPATH='/cygdrive/c/Program Files (x86)/Git/bin'
    GITCOREPATH='/cygdrive/c/Program Files (x86)/Git/libexec/git-core'
    PATH=${GITPATH}:${GITCOREPATH}:${PATH}
    
  5. Open Git Bash and create a repository anywhere on your PC:

    $ git --bare init repo.git
    Initialized empty Git repository in C:/repopath/repo.git/
    

Client PC

  1. Install msysgit.
  2. Use the private key you created on the server to clone your repo from ssh://user@server:port/repopath/repo.git (for some reason, the root is the C: drive)

This allowed me to successfully clone and commit, but I could not push to the bare repo on the server. I kept getting:

git: '/repopath/repo.git' is not a git command. See 'git --help'.
fatal: The remote end hung up unexpectedly

This led me to Rui's trace and solution which was to create or add the following lines to .gitconfig in your Client PC's %USERPROFILE% path (C:\Users\UserName).

[remote "origin"]
    receivepack = git receive-pack

I am not sure why this is needed...if anybody could provide insight, this would be helpful.

my git version is 1.7.3.1.msysgit.0

How can I check whether a variable is defined in Node.js?

Determine if property is existing (but is not a falsy value):

if (typeof query !== 'undefined' && query !== null){
   doStuff();
}

Usually using

if (query){
   doStuff();
}

is sufficient. Please note that:

if (!query){
   doStuff();
}

doStuff() will execute even if query was an existing variable with falsy value (0, false, undefined or null)

Btw, there's a sexy coffeescript way of doing this:

if object?.property? then doStuff()

which compiles to:

if ((typeof object !== "undefined" && object !== null ? object.property : void 0) != null) 

{
  doStuff();
}

req.body empty on posts

You have to check whether the body-parser middleware is set properly to the type of request(json, urlencoded).

If you have set,

app.use(bodyParser.json());

then in postman you have to send the data as raw.

https://i.stack.imgur.com/k9IdQ.png postman screenshot

If you have set,

app.use(bodyParser.urlencoded({
    extended: true
}));

then 'x-www-form-urlencoded' option should be selected.

Hibernate throws MultipleBagFetchException - cannot simultaneously fetch multiple bags

To fix it simply take Set in place of List for your nested object.

@OneToMany
Set<Your_object> objectList;

and don't forget to use fetch=FetchType.EAGER

it will work.

There is one more concept CollectionId in Hibernate if you want to stick with list only.

But remind that you won't eliminate the underlaying Cartesian Product as described by Vlad Mihalcea in his answer!

Select specific row from mysql table

You can add an auto generated id field in the table and select by this id

SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = 3;

org.glassfish.jersey.servlet.ServletContainer ClassNotFoundException

It's an eclipse setup issue, not a Jersey issue.

From this thread ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer

Right click your eclipse project Properties -> Deployment Assembly -> Add -> Java Build Path Entries -> Gradle Dependencies -> Finish.

So Eclipse wasn't using the Gradle dependencies when Apache was starting .

How do synchronized static methods work in Java and can I use it for loading Hibernate entities?

If it is something to do with the data in your database, why not utilize database isolation locking to achieve?

How do I animate constraint changes?

Storyboard, Code, Tips and a few Gotchas

The other answers are just fine but this one highlights a few fairly important gotchas of animating constraints using a recent example. I went through a lot of variations before I realized the following:

Make the constraints you want to target into Class variables to hold a strong reference. In Swift I used lazy variables:

lazy var centerYInflection:NSLayoutConstraint = {
       let temp =  self.view.constraints.filter({ $0.firstItem is MNGStarRating }).filter ( { $0.secondItem is UIWebView }).filter({ $0.firstAttribute == .CenterY }).first
        return temp!
}()

After some experimentation I noted that one MUST obtain the constraint from the view ABOVE (aka the superview) the two views where the constraint is defined. In the example below (both MNGStarRating and UIWebView are the two types of items I am creating a constraint between, and they are subviews within self.view).

Filter Chaining

I take advantage of Swift's filter method to separate the desired constraint that will serve as the inflection point. One could also get much more complicated but filter does a nice job here.

Animating Constraints Using Swift

Nota Bene - This example is the storyboard/code solution and assumes one has made default constraints in the storyboard. One can then animate the changes using code.

Assuming you create a property to filter with accurate criteria and get to a specific inflection point for your animation (of course you could also filter for an array and loop through if you need multiple constraints):

lazy var centerYInflection:NSLayoutConstraint = {
    let temp =  self.view.constraints.filter({ $0.firstItem is MNGStarRating }).filter ( { $0.secondItem is UIWebView }).filter({ $0.firstAttribute == .CenterY }).first
    return temp!
}()

....

Sometime later...

@IBAction func toggleRatingView (sender:AnyObject){

    let aPointAboveScene = -(max(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height) * 2.0)

    self.view.layoutIfNeeded()


    //Use any animation you want, I like the bounce in springVelocity...
    UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 0.75, options: [.CurveEaseOut], animations: { () -> Void in

        //I use the frames to determine if the view is on-screen
        if CGRectContainsRect(self.view.frame, self.ratingView.frame) {

            //in frame ~ animate away
            //I play a sound to give the animation some life

            self.centerYInflection.constant = aPointAboveScene
            self.centerYInflection.priority = UILayoutPriority(950)

        } else {

            //I play a different sound just to keep the user engaged
            //out of frame ~ animate into scene
            self.centerYInflection.constant = 0
            self.centerYInflection.priority = UILayoutPriority(950)
            self.view.setNeedsLayout()
            self.view.layoutIfNeeded()
         }) { (success) -> Void in

            //do something else

        }
    }
}

The many wrong turns

These notes are really a set of tips that I wrote for myself. I did all the don'ts personally and painfully. Hopefully this guide can spare others.

  1. Watch out for zPositioning. Sometimes when nothing is apparently happening, you should hide some of the other views or use the view debugger to locate your animated view. I've even found cases where a User Defined Runtime Attribute was lost in a storyboard's xml and led to the animated view being covered (while working).

  2. Always take a minute to read the documentation (new and old), Quick Help, and headers. Apple keeps making a lot of changes to better manage AutoLayout constraints (see stack views). Or at least the AutoLayout Cookbook. Keep in mind that sometimes the best solutions are in the older documentation/videos.

  3. Play around with the values in the animation and consider using other animateWithDuration variants.

  4. Don't hardcode specific layout values as criteria for determining changes to other constants, instead use values that allow you to determine the location of the view. CGRectContainsRect is one example

  5. If needed, don't hesitate to use the layout margins associated with a view participating in the constraint definition let viewMargins = self.webview.layoutMarginsGuide: is on example
  6. Don't do work you don't have to do, all views with constraints on the storyboard have constraints attached to the property self.viewName.constraints
  7. Change your priorities for any constraints to less than 1000. I set mine to 250 (low) or 750 (high) on the storyboard; (if you try to change a 1000 priority to anything in code then the app will crash because 1000 is required)
  8. Consider not immediately trying to use activateConstraints and deactivateConstraints (they have their place but when just learning or if you are using a storyboard using these probably means your doing too much ~ they do have a place though as seen below)
  9. Consider not using addConstraints / removeConstraints unless you are really adding a new constraint in code. I found that most times I layout the views in the storyboard with desired constraints (placing the view offscreen), then in code, I animate the constraints previously created in the storyboard to move the view around.
  10. I spent a lot of wasted time building up constraints with the new NSAnchorLayout class and subclasses. These work just fine but it took me a while to realize that all the constraints that I needed already existed in the storyboard. If you build constraints in code then most certainly use this method to aggregate your constraints:

Quick Sample Of Solutions to AVOID when using Storyboards

private var _nc:[NSLayoutConstraint] = []
    lazy var newConstraints:[NSLayoutConstraint] = {

        if !(self._nc.isEmpty) {
            return self._nc
        }

        let viewMargins = self.webview.layoutMarginsGuide
        let minimumScreenWidth = min(UIScreen.mainScreen().bounds.width,UIScreen.mainScreen().bounds.height)

        let centerY = self.ratingView.centerYAnchor.constraintEqualToAnchor(self.webview.centerYAnchor)
        centerY.constant = -1000.0
        centerY.priority = (950)
        let centerX =  self.ratingView.centerXAnchor.constraintEqualToAnchor(self.webview.centerXAnchor)
        centerX.priority = (950)

        if let buttonConstraints = self.originalRatingViewConstraints?.filter({

            ($0.firstItem is UIButton || $0.secondItem is UIButton )
        }) {
            self._nc.appendContentsOf(buttonConstraints)

        }

        self._nc.append( centerY)
        self._nc.append( centerX)

        self._nc.append (self.ratingView.leadingAnchor.constraintEqualToAnchor(viewMargins.leadingAnchor, constant: 10.0))
        self._nc.append (self.ratingView.trailingAnchor.constraintEqualToAnchor(viewMargins.trailingAnchor, constant: 10.0))
        self._nc.append (self.ratingView.widthAnchor.constraintEqualToConstant((minimumScreenWidth - 20.0)))
        self._nc.append (self.ratingView.heightAnchor.constraintEqualToConstant(200.0))

        return self._nc
    }()

If you forget one of these tips or the more simple ones such as where to add the layoutIfNeeded, most likely nothing will happen: In which case you may have a half baked solution like this:

NB - Take a moment to read the AutoLayout Section Below and the original guide. There is a way to use these techniques to supplement your Dynamic Animators.

UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.3, initialSpringVelocity: 1.0, options: [.CurveEaseOut], animations: { () -> Void in

            //
            if self.starTopInflectionPoint.constant < 0  {
                //-3000
                //offscreen
                self.starTopInflectionPoint.constant = self.navigationController?.navigationBar.bounds.height ?? 0
                self.changeConstraintPriority([self.starTopInflectionPoint], value: UILayoutPriority(950), forView: self.ratingView)

            } else {

                self.starTopInflectionPoint.constant = -3000
                 self.changeConstraintPriority([self.starTopInflectionPoint], value: UILayoutPriority(950), forView: self.ratingView)
            }

        }) { (success) -> Void in

            //do something else
        }

    }

Snippet from the AutoLayout Guide (note the second snippet is for using OS X). BTW - This is no longer in the current guide as far as I can see. The preferred techniques continue to evolve.

Animating Changes Made by Auto Layout

If you need full control over animating changes made by Auto Layout, you must make your constraint changes programmatically. The basic concept is the same for both iOS and OS X, but there are a few minor differences.

In an iOS app, your code would look something like the following:

[containerView layoutIfNeeded]; // Ensures that all pending layout operations have been completed
[UIView animateWithDuration:1.0 animations:^{
     // Make all constraint changes here
     [containerView layoutIfNeeded]; // Forces the layout of the subtree animation block and then captures all of the frame changes
}];

In OS X, use the following code when using layer-backed animations:

[containterView layoutSubtreeIfNeeded];
[NSAnimationContext runAnimationGroup:^(NSAnimationContext *context) {
     [context setAllowsImplicitAnimation: YES];
     // Make all constraint changes here
     [containerView layoutSubtreeIfNeeded];
}];

When you aren’t using layer-backed animations, you must animate the constant using the constraint’s animator:

[[constraint animator] setConstant:42];

For those who learn better visually check out this early video from Apple.

Pay Close Attention

Often in documentation there are small notes or pieces of code that lead to bigger ideas. For example attaching auto layout constraints to dynamic animators is a big idea.

Good Luck and May the Force be with you.

Not Equal to This OR That in Lua

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

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

try something like this instead.

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

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

Evaluate list.contains string in JSTL

The following is more of a workaround than an answer to your question but it may be what you are looking for. If you can put your values in a map instead of a list, that would solve your problem. Just map your values to a non null value and do this <c:if test="${mymap.myValue ne null}">style='display:none;'</c:if> or you can even map to style='display:none; and simply output ${mymap.myValue}

Singleton in Android

EDIT :

The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.


Could you post an example from your code ?

Take a look at this gist : https://gist.github.com/Akayh/5566992

it works but it was done very quickly :

MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")

Set new value to mString : "Singleton"

Launch activityB and show the mString value. "Singleton" appears...

Escaping HTML strings with jQuery

Try Underscore.string lib, it works with jQuery.

_.str.escapeHTML('<div>Blah blah blah</div>')

output:

'&lt;div&gt;Blah blah blah&lt;/div&gt;'

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

Python - List of unique dictionaries

a = [
{'id':1,'name':'john', 'age':34},
{'id':1,'name':'john', 'age':34},
{'id':2,'name':'hanna', 'age':30},
]

b = {x['id']:x for x in a}.values()

print(b)

outputs:

[{'age': 34, 'id': 1, 'name': 'john'}, {'age': 30, 'id': 2, 'name': 'hanna'}]

fatal error C1083: Cannot open include file: 'xyz.h': No such file or directory?

Add the "code" folder to the project properties within Visual Studio

Project->Properties->Configuration Properties->C/C++->Additional Include Directories

Cast Double to Integer in Java

You need to explicitly get the int value using method intValue() like this:

Double d = 5.25;
Integer i = d.intValue(); // i becomes 5

Or

double d = 5.25;
int i = (int) d;

How do I programmatically set device orientation in iOS 7?

I was in a similar problem than you. I need to lock device orientation for some screens (like Login) and allow rotation in others.

After a few changes and following some answers below I did it by:

  • Enabling all the orientations in the Project's Info.plist.

enter image description here

  • Disabling orientation in those ViewControllers where I need the device not to rotate, like in the Login screen in my case. I needed to override shouldAutorotate method in this VC:

-(BOOL)shouldAutorotate{ return NO; }

Hope this will work for you.

What is the difference between an Instance and an Object?

I can't believe, except for one guy no one has used the code to explain this, let me give it a shot too!

// Design Class
class HumanClass {
    var name:String
    init(name:String) {
        self.name = name
    }
}

var humanClassObject1 = HumanClass(name: "Rehan") 

Now the left side i.e: "humanClassObject1" is the object and the right side i.e: HumanClass(name: "Rehan") is the instance of this object.

var humanClassObject2 = HumanClass(name: "Ahmad") // again object on left and it's instance on the right.

So basically, instance contains the specific values for that object and objects contains the memory location (at run-time).

Remember the famous statement "object reference not set to an instance of an object", this means that non-initialised objects don't have any instance. In some programming languages like swift the compiler will not allow you to even design a class that don't have any way to initialise all it's members (variable eg: name, age e.t.c), but in some language you are allowed to do this:

// Design Class
class HumanClass {
    var name:String // See we don't have any way to initialise name property.
}

And the error will only be shown at run time when you try to do something like this:

var myClass = HumanClass()
print(myClass.name) // will give, object reference not set to an instance of the object.

This error indicates that, the specific values (for variables\property) is the "INSTANCE" as i tried to explain this above! And the object i.e: "myClass" contains the memory location (at run-time).

Laravel PHP Command Not Found

1) First, download the Laravel installer using Composer:

composer global require "laravel/installer"

2) Make sure to place the ~/.composer/vendor/bin directory in your PATH so the laravel executable can be located by your system.

  set PATH=%PATH%;%USERPROFILE%\AppData\Roaming\Composer\vendor\bin

  eg: “C:\Users\\AppData\Roaming\Composer\vendor\bin” 

3) Once installed, the simple laravel new command will create a fresh Laravel installation in the directory you specify.

eG:  laravel new blog

Rounding BigDecimal to *always* have two decimal places

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

C++ Fatal Error LNK1120: 1 unresolved externals

My problem was int Main() instead of int main()

good luck

Get the cartesian product of a series of lists?

In Python 2.6 and above you can use 'itertools.product`. In older versions of Python you can use the following (almost -- see documentation) equivalent code from the documentation, at least as a starting point:

def product(*args, **kwds):
    # product('ABCD', 'xy') --> Ax Ay Bx By Cx Cy Dx Dy
    # product(range(2), repeat=3) --> 000 001 010 011 100 101 110 111
    pools = map(tuple, args) * kwds.get('repeat', 1)
    result = [[]]
    for pool in pools:
        result = [x+[y] for x in result for y in pool]
    for prod in result:
        yield tuple(prod)

The result of both is an iterator, so if you really need a list for furthert processing, use list(result).

git diff file against its last change

One of the ways to use git diff is:

git diff <commit> <path>

And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...

So the answer to your question is:

git diff HEAD^^ myfile

How to get current route in Symfony 2?

From something that is ContainerAware (like a controller):

$request = $this->container->get('request');
$routeName = $request->get('_route');

I want to load another HTML page after a specific amount of time

Use Javascript's setTimeout:

<body onload="setTimeout(function(){window.location = 'form2.html';}, 5000)">

<DIV> inside link (<a href="">) tag

No, the link assigned to the containing <a> will be assigned to every elements inside it.

And, this is not the proper way. You can make a <a> behave like a <div>.

An Example [Demo]

CSS

a.divlink { 
     display:block;
     width:500px;
     height:500px; 
     float:left;
}

HTML

<div>
    <a class="divlink" href="yourlink.html">
         The text or elements inside the elements
    </a>
    <a class="divlink" href="yourlink2.html">
         Another text or element
    </a>
</div>

Angularjs how to upload multipart form data and a file?

It is more efficient to send the files directly.

The base64 encoding of Content-Type: multipart/form-data adds an extra 33% overhead. If the server supports it, it is more efficient to send the files directly:

Doing Multiple $http.post Requests Directly from a FileList

$scope.upload = function(url, fileList) {
    var config = {
      headers: { 'Content-Type': undefined },
      transformResponse: angular.identity
    };
    var promises = fileList.map(function(file) {
      return $http.post(url, file, config);
    });
    return $q.all(promises);
};

When sending a POST with a File object, it is important to set 'Content-Type': undefined. The XHR send method will then detect the File object and automatically set the content type.


Working Demo of "select-ng-files" Directive that Works with ng-model1

The <input type=file> element does not by default work with the ng-model directive. It needs a custom directive:

_x000D_
_x000D_
angular.module("app",[]);

angular.module("app").directive("selectNgFiles", function() {
  return {
    require: "ngModel",
    link: function postLink(scope,elem,attrs,ngModel) {
      elem.on("change", function(e) {
        var files = elem[0].files;
        ngModel.$setViewValue(files);
      })
    }
  }
});
_x000D_
<script src="//unpkg.com/angular/angular.js"></script>
  <body ng-app="app">
    <h1>AngularJS Input `type=file` Demo</h1>
    
    <input type="file" select-ng-files ng-model="fileList" multiple>
    
    <h2>Files</h2>
    <div ng-repeat="file in fileList">
      {{file.name}}
    </div>
  </body>
_x000D_
_x000D_
_x000D_

Using Lato fonts in my css (@font-face)

Well, you're missing the letter 'd' in url("~/fonts/Lato-Bol.ttf"); - but assuming that's not it, I would open up your page with developer tools in Chrome and make sure there's no errors loading any of the files (you would probably see an issue in the JavaScript console, or you can check the Network tab and see if anything is red).

(I don't see anything obviously wrong with the code you have posted above)

Other things to check: 1) Are you including your CSS file in your html above the lines where you are trying to use the font-family style? 2) What do you see in the CSS panel in the developer tools for that div? Is font-family: lato crossed out?

What is the function __construct used for?

__construct simply initiates a class. Suppose you have the following code;

Class Person { 

 function __construct() {
   echo 'Hello';
  }

}

$person = new Person();

//the result 'Hello' will be shown.

We did not create another function to echo the word 'Hello'. It simply shows that the keyword __construct is quite useful in initiating a class or an object.

HTML/JavaScript: Simple form validation on submit

The simplest validation is as follows:

_x000D_
_x000D_
<form name="ff1" method="post">
  <input type="email" name="email" id="fremail" placeholder="[email protected]" />
  <input type="text" pattern="[a-z0-9. -]+" title="Please enter only alphanumeric characters." name="title" id="frtitle" placeholder="Title" />
  <input type="url" name="url" id="frurl" placeholder="http://yourwebsite.com/" />
  <input type="submit" name="Submit" value="Continue" />
</form>
_x000D_
_x000D_
_x000D_

It uses HTML5 attributes (like as pattern).

JavaScript: none.

How to generate UML diagrams (especially sequence diagrams) from Java code?

EDIT: If you're a designer then Papyrus is your best choice it's very advanced and full of features, but if you just want to sketch out some UML diagrams and easy installation then ObjectAid is pretty cool and it doesn't require any plugins I just installed it over Eclipse-Java EE and works great !.


UPDATE Oct 11th, 2013

My original post was in June 2012 a lot of things have changed many tools has grown and others didn't. Since I'm going back to do some modeling and also getting some replies to the post I decided to install papyrus again and will investigate other possible UML modeling solutions again. UML generation (with synchronization feature) is really important not to software designer but to the average developer.

I wish papyrus had straightforward way to Reverse Engineer classes into UML class diagram and It would be super cool if that reverse engineering had a synchronization feature, but unfortunately papyrus project is full of features and I think developers there have already much at hand since also many actions you do over papyrus might not give you any response and just nothing happens but that's out of this question scope anyway.

The Answer (Oct 11th, 2013)

Tools

  1. Download Papyrus
  2. Go to Help -> Install New Software...
  3. In the Work with: drop-down, select --All Available Sites--
  4. In the filter, type in Papyrus
  5. After installation finishes restart Eclipse
  6. Repeat steps 1-3 and this time, install Modisco

Steps

  1. In your java project (assume it's called MyProject) create a folder e.g UML
  2. Right click over the project name -> Discovery -> Discoverer -> Discover Java and inventory model from java project, a file called MyProject_kdm.xmi will be generated. enter image description here
  3. Right click project name file --> new --> papyrus model -> and call it MyProject.
  4. Move the three generated files MyProject.di , MyProject.notation, MyProject.uml to the UML folder
  5. Right click on MyProject_kdm.xmi -> Discovery -> Discoverer -> Discover UML model from KDM code again you'll get a property dialog set the serialization prop to TRUE to generate a file named MyProject.uml enter image description here

  6. Move generated MyProject.uml which was generated at root, to UML folder, Eclipse will ask you If you wanted to replace it click yes. What we did in here was that we replaced an empty model with a generated one.

  7. ALT+W -> show view -> papyrus -> model explorer

  8. In that view, you'll find your classes like in the picture enter image description here

  9. In the view Right click root model -> New diagram enter image description here

  10. Then start grabbing classes to the diagram from the view

Some features

  • To show the class elements (variables, functions etc) Right click on any class -> Filters -> show/hide contents Voila !!

  • You can have default friendly color settings from Window -> pereferences -> papyrus -> class diagram

  • one very important setting is Arrange when you drop the classes they get a cramped right click on any empty space at a class diagram and click Arrange All

  • Arrows in the model explorer view can be grabbed to the diagram to show generalization, realization etc

  • After all of that your settings will show diagrams like enter image description here

  • Synchronization isn't available as far as I know you'll need to manually import any new classes.

That's all, And don't buy commercial products unless you really need it, papyrus is actually great and sophisticated instead donate or something.

Disclaimer: I've no relation to the papyrus people, in fact, I didn't like papyrus at first until I did lots of research and experienced it with some patience. And will get back to this post again when I try other free tools.

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

Could not complete the operation due to error 80020101. IE

I dont know why but it worked for me. If you have comments like

//Comment

Then it gives this error. To fix this do

/*Comment*/

Doesn't make sense but it worked for me.

PHP add elements to multidimensional array with array_push

I know the topic is old, but I just fell on it after a google search so... here is another solution:

$array_merged = array_merge($array_going_first, $array_going_second);

This one seems pretty clean to me, it works just fine!

Get only specific attributes with from Laravel Collection

use User::get(['id', 'name', 'email']), it will return you a collection with the specified columns and if you want to make it an array, just use toArray() after the get() method like so:

User::get(['id', 'name', 'email'])->toArray()

Most of the times, you won't need to convert the collection to an array because collections are actually arrays on steroids and you have easy-to-use methods to manipulate the collection.

How to run a PowerShell script without displaying a window?

I have created a small tool passing the call to any console tool you want to start windowless through to the original file:

https://github.com/Vittel/RunHiddenConsole

After compiling just rename the executable to "<targetExecutableName>w.exe" (append a "w"), and put it next to the original executable. You can then call e.G. powershellw.exe with the usual parameters and it wont pop up a window.

If someone has an idea how to check whether the created process is waiting for input, ill be happy to include your solution :)

AngularJS - Create a directive that uses ng-model

EDIT: This answer is old and likely out of date. Just a heads up so it doesn't lead folks astray. I no longer use Angular so I'm not in a good position to make improvements.


It's actually pretty good logic but you can simplify things a bit.

Directive

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.model = { name: 'World' };
  $scope.name = "Felipe";
});

app.directive('myDirective', function($compile) {
  return {
    restrict: 'AE', //attribute or element
    scope: {
      myDirectiveVar: '=',
     //bindAttr: '='
    },
    template: '<div class="some">' +
      '<input ng-model="myDirectiveVar"></div>',
    replace: true,
    //require: 'ngModel',
    link: function($scope, elem, attr, ctrl) {
      console.debug($scope);
      //var textField = $('input', elem).attr('ng-model', 'myDirectiveVar');
      // $compile(textField)($scope.$parent);
    }
  };
});

Html with directive

<body ng-controller="MainCtrl">
  This scope value <input ng-model="name">
  <my-directive my-directive-var="name"></my-directive>
</body>

CSS

.some {
  border: 1px solid #cacaca;
  padding: 10px;
}

You can see it in action with this Plunker.

Here's what I see:

  • I understand why you want to use 'ng-model' but in your case it's not necessary. ng-model is to link existing html elements with a value in the scope. Since you're creating a directive yourself you're creating a 'new' html element, so you don't need ng-model.

EDIT As mentioned by Mark in his comment, there's no reason that you can't use ng-model, just to keep with convention.

  • By explicitly creating a scope in your directive (an 'isolated' scope), the directive's scope cannot access the 'name' variable on the parent scope (which is why, I think, you wanted to use ng-model).
  • I removed ngModel from your directive and replaced it with a custom name that you can change to whatever.
  • The thing that makes it all still work is that '=' sign in the scope. Checkout the docs docs under the 'scope' header.

In general, your directives should use the isolated scope (which you did correctly) and use the '=' type scope if you want a value in your directive to always map to a value in the parent scope.

How to Configure SSL for Amazon S3 bucket

It is not possible directly with S3, but you can create a Cloud Front distribution from you bucket. Then go to certificate manager and request a certificate. Amazon gives them for free. Ones you have successfully confirmed the certification, assign it to your Cloud Front distribution. Also remember to set the rule to re-direct http to https.

I'm hosting couple of static websites on Amazon S3, like my personal website to which I have assigned the SSL certificate as they have the Cloud Front distribution.

String to decimal conversion: dot separation instead of comma

I had faced the similar issue while using Convert.ToSingle(my_value) If the OS language settings is English 2.5 (example) will be taken as 2.5 If the OS language is German, 2.5 will be treated as 2,5 which is 25 I used the invariantculture IFormat provided and it works. It always treats '.' as '.' instead of ',' irrespective of the system language.

float var = Convert.ToSingle(my_value, System.Globalization.CultureInfo.InvariantCulture);

How to get the first 2 letters of a string in Python?

All previous examples will raise an exception in case your string is not long enough.

Another approach is to use 'yourstring'.ljust(100)[:100].strip().

This will give you first 100 chars. You might get a shorter string in case your string last chars are spaces.

How to automatically crop and center an image

Try this:

#yourElementId
{
    background: url(yourImageLocation.jpg) no-repeat center center;
    width: 100px;
    height: 100px;
}

Keep in mind that width and height will only work if your DOM element has layout (a block displayed element, like a div or an img). If it is not (a span, for example), add display: block; to the CSS rules. If you do not have access to the CSS files, drop the styles inline in the element.

Returning multiple objects in an R function

Unlike many other languages, R functions don't return multiple objects in the strict sense. The most general way to handle this is to return a list object. So if you have an integer foo and a vector of strings bar in your function, you could create a list that combines these items:

foo <- 12
bar <- c("a", "b", "e")
newList <- list("integer" = foo, "names" = bar)

Then return this list.

After calling your function, you can then access each of these with newList$integer or newList$names.

Other object types might work better for various purposes, but the list object is a good way to get started.

How do you reverse a string in place in C or C++?

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

unsigned char * utf8_reverse(const unsigned char *, int);
void assert_true(bool);

int main(void)
{
    unsigned char str[] = "mañana man~ana";
    unsigned char *ret = utf8_reverse(str,  strlen((const char *) str) + 1);

    printf("%s\n", ret);
    assert_true(0 == strncmp((const char *) ret, "ana~nam anañam", strlen("ana~nam anañam") + 1));

    free(ret);

    return EXIT_SUCCESS;
}

unsigned char * utf8_reverse(const unsigned char *str, int size)
{
    unsigned char *ret = calloc(size, sizeof(unsigned char*));
    int ret_size = 0;
    int pos = size - 2;
    int char_size = 0;

    if (str ==  NULL) {
        fprintf(stderr, "failed to allocate memory.\n");
        exit(EXIT_FAILURE);
    }

    while (pos > -1) {

        if (str[pos] < 0x80) {
            char_size = 1;
        } else if (pos > 0 && str[pos - 1] > 0xC1 && str[pos - 1] < 0xE0) {
            char_size = 2;
        } else if (pos > 1 && str[pos - 2] > 0xDF && str[pos - 2] < 0xF0) {
            char_size = 3;
        } else if (pos > 2 && str[pos - 3] > 0xEF && str[pos - 3] < 0xF5) {
            char_size = 4;
        } else {
            char_size = 1;
        }

        pos -= char_size;
        memcpy(ret + ret_size, str + pos + 1, char_size);
        ret_size += char_size;
    }    

    ret[ret_size] = '\0';

    return ret;
}

void assert_true(bool boolean)
{
    puts(boolean == true ? "true" : "false");
}

Load text file as strings using numpy.loadtxt()

Is it essential that you need a NumPy array? Otherwise you could speed things up by loading the data as a nested list.

def load(fname):
    ''' Load the file using std open'''
    f = open(fname,'r')

    data = []
    for line in f.readlines():
        data.append(line.replace('\n','').split(' '))

    f.close()

    return data

For a text file with 4000x4000 words this is about 10 times faster than loadtxt.

How can we draw a vertical line in the webpage?

That's no struts related problem but rather plain HMTL/CSS.

I'm not HTML or CSS expert, but I guess you could use a div with a border on the left or right side only.

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

You need to only depend on one major version of angular, so update all modules depending on angular 2.x :

  • update @angular/flex-layout to ^2.0.0-beta.9
  • update @angular/material to ^2.0.0-beta.12
  • update angularfire2 to ^4.0.0-rc.2
  • update zone.js to ^0.8.18
  • update webpack to ^3.8.1
  • add @angular/[email protected] (required for @angular/material)
  • replace angular2-google-maps by @agm/[email protected] (new name)

How to add a local repo and treat it as a remote repo

It appears that your format is incorrect:

If you want to share a locally created repository, or you want to take contributions from someone elses repository - if you want to interact in any way with a new repository, it's generally easiest to add it as a remote. You do that by running git remote add [alias] [url]. That adds [url] under a local remote named [alias].

#example
$ git remote
$ git remote add github [email protected]:schacon/hw.git
$ git remote -v

http://gitref.org/remotes/#remote

How to check if the user can go back in browser history or not

My code let the browser go back one page, and if that fails it loads a fallback url. It also detect hashtags changes.

When the back button wasn't available, the fallback url will be loaded after 500 ms, so the browser has time enough to load the previous page. Loading the fallback url right after window.history.go(-1); would cause the browser to use the fallback url, because the js script didn't stop yet.

function historyBackWFallback(fallbackUrl) {
    fallbackUrl = fallbackUrl || '/';
    var prevPage = window.location.href;

    window.history.go(-1);

    setTimeout(function(){ 
        if (window.location.href == prevPage) {
            window.location.href = fallbackUrl; 
        }
    }, 500);
}

How do I turn off autocommit for a MySQL client?

Do you mean the mysql text console? Then:

START TRANSACTION;
  ...
  your queries.
  ...
COMMIT;

Is what I recommend.

However if you want to avoid typing this each time you need to run this sort of query, add the following to the [mysqld] section of your my.cnf file.

init_connect='set autocommit=0'

This would set autocommit to be off for every client though.

How to export html table to excel using javascript

Excel Export Script works on IE7+ , Firefox and Chrome
===========================================================



function fnExcelReport()
    {
             var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>";
             var textRange; var j=0;
          tab = document.getElementById('headerTable'); // id of table


          for(j = 0 ; j < tab.rows.length ; j++) 
          {     
                tab_text=tab_text+tab.rows[j].innerHTML+"</tr>";
                //tab_text=tab_text+"</tr>";
          }

          tab_text=tab_text+"</table>";
          tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table
          tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table
                      tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params

               var ua = window.navigator.userAgent;
              var msie = ua.indexOf("MSIE "); 

                 if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))      // If Internet Explorer
                    {
                           txtArea1.document.open("txt/html","replace");
                           txtArea1.document.write(tab_text);
                           txtArea1.document.close();
                           txtArea1.focus(); 
                            sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls");
                          }  
                  else                 //other browser not tested on IE 11
                      sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));  


                      return (sa);
                            }

    Just Create a blank iframe
    enter code here
        <iframe id="txtArea1" style="display:none"></iframe>

    Call this function on

        <button id="btnExport" onclick="fnExcelReport();"> EXPORT 
        </button>

MySQL and PHP - insert NULL rather than empty string

This works just fine for me:

INSERT INTO table VALUES ('', NULLIF('$date',''))

(first '' increments id field)

How to compare DateTime without time via LINQ?

Try this code

var today = DateTime.Today;
var q = db.Games.Where(t => DbFunctions.TruncateTime(t.StartDate) <= today);

Maven command to determine which settings.xml file Maven is using

You can use the maven help plugin to tell you the contents of your user and global settings files.

mvn help:effective-settings

will ask maven to spit out the combined global and user settings.

Detect end of ScrollView

EDIT

With the content of your XML, I can see that you use a ScrollView. If you want to use your custom view, you must write com.your.packagename.ScrollViewExt and you will be able to use it in your code.

<com.your.packagename.ScrollViewExt
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <WebView
        android:id="@+id/textterms"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:gravity="center_horizontal"
        android:textColor="@android:color/black" />

</com.your.packagename.ScrollViewExt>

EDIT END

Could you post the xml content ?

I think that you could simply add a scroll listener and check if the last item showed is the lastest one from the listview like :

mListView.setOnScrollListener(new OnScrollListener() {      
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        // TODO Auto-generated method stub      
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
            int visibleItemCount, int totalItemCount) {
        // TODO Auto-generated method stub
        if(view.getLastVisiblePosition()==(totalItemCount-1)){
            //dosomething
        }
    }
});

Download a specific tag with Git

I checked the git checkout documentation, it revealed one interesting thing:

git checkout -b <new_branch_name> <start_point> , where the <start_point> is the name of a commit at which to start the new branch; Defaults to HEAD

So we can mention the tag name( as tag is nothing but a name of a commit) as, say:

>> git checkout -b 1.0.2_branch 1.0.2
later, modify some files
>> git push --tags

P.S: In Git, you can't update a tag directly(since tag is just a label to a commit), you need to checkout the same tag as a branch and then commit to it and then create a separate tag.

Could not insert new outlet connection: Could not find any information for the class named

I got this bug when I renamed the class. Then I solved it just by following the below steps

  • In Xcode Menu -> Product -> Clean
  • Restart the Xcode

How do I pass the this context to a function?

Javascripts .call() and .apply() methods allow you to set the context for a function.

var myfunc = function(){
    alert(this.name);
};

var obj_a = {
    name:  "FOO"
};

var obj_b = {
    name:  "BAR!!"
};

Now you can call:

myfunc.call(obj_a);

Which would alert FOO. The other way around, passing obj_b would alert BAR!!. The difference between .call() and .apply() is that .call() takes a comma separated list if you're passing arguments to your function and .apply() needs an array.

myfunc.call(obj_a, 1, 2, 3);
myfunc.apply(obj_a, [1, 2, 3]);

Therefore, you can easily write a function hook by using the apply() method. For instance, we want to add a feature to jQuerys .css() method. We can store the original function reference, overwrite the function with custom code and call the stored function.

var _css = $.fn.css;
$.fn.css = function(){
   alert('hooked!');
   _css.apply(this, arguments);
};

Since the magic arguments object is an array like object, we can just pass it to apply(). That way we guarantee, that all parameters are passed through to the original function.

access denied for user @ 'localhost' to database ''

Try this: Adding users to MySQL

You need grant privileges to the user if you want external acess to database(ie. web pages).

How to append to New Line in Node.js

It looks like you're running this on Windows (given your H://log.txt file path).

Try using \r\n instead of just \n.

Honestly, \n is fine; you're probably viewing the log file in notepad or something else that doesn't render non-Windows newlines. Try opening it in a different viewer/editor (e.g. Wordpad).

Recommended way to get hostname in Java

The most portable way to get the hostname of the current computer in Java is as follows:

import java.net.InetAddress;
import java.net.UnknownHostException;

public class getHostName {

    public static void main(String[] args) throws UnknownHostException {
        InetAddress iAddress = InetAddress.getLocalHost();
        String hostName = iAddress.getHostName();
        //To get  the Canonical host name
        String canonicalHostName = iAddress.getCanonicalHostName();

        System.out.println("HostName:" + hostName);
        System.out.println("Canonical Host Name:" + canonicalHostName);
    }
}

How to fix: Handler "PageHandlerFactory-Integrated" has a bad module "ManagedPipelineHandler" in its module list

Error: Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list

I found the articles to fix this issue by simply run the following commands at the command prompt:

%windir%\Microsoft.NET\Framework64\v4.0.30319\aspnet_regiis.exe -i

If the system is 32 bit, it would have looked like this:

%windir%\Microsoft.NET\Framework\v4.0.21006\aspnet_regiis.exe -i

But, when I tried to execute these commands using a command prompt, I got the following error/warning message:

C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis.exe -i Microsoft (R) ASP.NET RegIIS version 4.0.30319.33440 Administration utility to install and uninstall ASP.NET on the local machine. Copyright (C) Microsoft Corporation. All rights reserved. Start installing ASP.NET (4.0.30319.33440). This option is not supported on this version of the operating system. Administr ators should instead install/uninstall ASP.NET 4.5 with IIS8 using the "Turn Win dows Features On/Off" dialog, the Server Manager management tool, or the dism.exe command line tool. For more details please see http://go.microsoft.com/fwlin k/?LinkID=216771. Finished installing ASP.NET (4.0.30319.33440).**

To fix this on a Windows 8.1, I would suggest to do the following thing.

Solution:

Goto: Turn Windows features on or off -> Internet Information Services -> World Wide Web Services -> Application Development Features -> Enable ASP.NET 4.5

This should resolve the issue.

How do I pass data to Angular routed components?

<div class="button" click="routeWithData()">Pass data and route</div>

well the easiest way to do it in angular 6 or other versions I hope is to simply to define your path with the amount of data you want to pass

{path: 'detailView/:id', component: DetailedViewComponent}

as you can see from my routes definition, I have added the /:id to stand to the data I want to pass to the component via router navigation. Therefore your code will look like

<a class="btn btn-white-view" [routerLink]="[ '/detailView',list.id]">view</a>

in order to read the id on the component, just import ActivatedRoute like

import { ActivatedRoute } from '@angular/router'

and on the ngOnInit is where you retrieve the data

ngOnInit() {
       this.sub = this.route.params.subscribe(params => {
        this.id = params['id'];
        });
        console.log(this.id);
      }

you can read more in this article https://www.tektutorialshub.com/angular-passing-parameters-to-route/

How do I Alter Table Column datatype on more than 1 column?

Use the following syntax:

  ALTER TABLE your_table
  MODIFY COLUMN column1 datatype,
  MODIFY COLUMN column2 datatype,
  ... ... ... ... ... 
  ... ... ... ... ...

Based on that, your ALTER command should be:

  ALTER TABLE webstore.Store
  MODIFY COLUMN ShortName VARCHAR(100),
  MODIFY COLUMN UrlShort VARCHAR(100)

Note that:

  1. There are no second brackets around the MODIFY statements.
  2. I used two separate MODIFY statements for two separate columns.

This is the standard format of the MODIFY statement for an ALTER command on multiple columns in a MySQL table.

Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement

Regular Expression for matching parentheses

Because ( is special in regex, you should escape it \( when matching. However, depending on what language you are using, you can easily match ( with string methods like index() or other methods that enable you to find at what position the ( is in. Sometimes, there's no need to use regex.

Hadoop/Hive : Loading data from .csv on a local machine

There is another way of enabling this,

  1. use hadoop hdfs -copyFromLocal to copy the .csv data file from your local computer to somewhere in HDFS, say '/path/filename'

  2. enter Hive console, run the following script to load from the file to make it as a Hive table. Note that '\054' is the ascii code of 'comma' in octal number, representing fields delimiter.


CREATE EXTERNAL TABLE table name (foo INT, bar STRING)
 COMMENT 'from csv file'
 ROW FORMAT DELIMITED FIELDS TERMINATED BY '\054'
 STORED AS TEXTFILE
 LOCATION '/path/filename';

Lock screen orientation (Android)

In the Manifest, you can set the screenOrientation to landscape. It would look something like this in the XML:

<activity android:name="MyActivity"
android:screenOrientation="landscape"
android:configChanges="keyboardHidden|orientation|screenSize">
...
</activity>

Where MyActivity is the one you want to stay in landscape.

The android:configChanges=... line prevents onResume(), onPause() from being called when the screen is rotated. Without this line, the rotation will stay as you requested but the calls will still be made.

Note: keyboardHidden and orientation are required for < Android 3.2 (API level 13), and all three options are required 3.2 or above, not just orientation.

Should I use .done() and .fail() for new jQuery AJAX code instead of success and error

I want to add something on @Michael Laffargue's post:

jqXHR.done() is faster!

jqXHR.success() have some load time in callback and sometimes can overkill script. I find that on hard way before.

UPDATE:

Using jqXHR.done(), jqXHR.fail() and jqXHR.always() you can better manipulate with ajax request. Generaly you can define ajax in some variable or object and use that variable or object in any part of your code and get data faster. Good example:

/* Initialize some your AJAX function */
function call_ajax(attr){
    var settings=$.extend({
        call            : 'users',
        option          : 'list'
    }, attr );

    return $.ajax({
        type: "POST",
        url: "//exapmple.com//ajax.php",
        data: settings,
        cache : false
    });
}

/* .... Somewhere in your code ..... */

call_ajax({
    /* ... */
    id : 10,
    option : 'edit_user'
    change : {
          name : 'John Doe'
    }
    /* ... */
}).done(function(data){

    /* DO SOMETHING AWESOME */

});

How do you push a tag to a remote repository using Git?

You can push all local tags by simply git push --tags command.

$ git tag                         # see tag lists
$ git push origin <tag-name>      # push a single tag
$ git push --tags                 # push all local tags 

Markdown and including multiple files

I think we better adopt a new file inclusion syntax (so won't mess up with code blocks, I think the C style inclusion is totally wrong), and I wrote a small tool in Perl, naming cat.pl, because it works like cat (cat a.txt b.txt c.txt will merge three files), but it merges files in depth, not in width. How to use?

$ perl cat.pl <your file>

The syntax in detail is:

  • recursive include files: @include <-=path=
  • just include one: %include <-=path=

It can properly handle file inclusion loops (if a.txt <- b.txt, b.txt <- a.txt, then what you expect?).

Example:

a.txt:

a.txt

    a <- b

    @include <-=b.txt=

a.end

b.txt:

b.txt

    b <- a

    @include <-=a.txt=

b.end

perl cat.pl a.txt > c.txt, c.txt:

a.txt

    a <- b

    b.txt

        b <- a

        a.txt

            a <- b

            @include <-=b.txt= (note:won't include, because it will lead to infinite loop.)

        a.end

    b.end

a.end

More examples at https://github.com/district10/cat/blob/master/tutorial_cat.pl_.md.

I also wrote a Java version having an identical effect (not the same, but close).

How to append rows to an R data frame

Lets take a vector 'point' which has numbers from 1 to 5

point = c(1,2,3,4,5)

if we want to append a number 6 anywhere inside the vector then below command may come handy

i) Vectors

new_var = append(point, 6 ,after = length(point))

ii) columns of a table

new_var = append(point, 6 ,after = length(mtcars$mpg))

The command append takes three arguments:

  1. the vector/column to be modified.
  2. value to be included in the modified vector.
  3. a subscript, after which the values are to be appended.

simple...!! Apologies in case of any...!

iOS 10 - Changes in asking permissions of Camera, microphone and Photo Library causing application to crash

You have to add this permission in Info.plist for iOS 10.

Photo :

Key       :  Privacy - Photo Library Usage Description    
Value   :  $(PRODUCT_NAME) photo use

Microphone :

Key        :  Privacy - Microphone Usage Description    
Value    :  $(PRODUCT_NAME) microphone use

Camera :

Key       :  Privacy - Camera Usage Description   
Value   :  $(PRODUCT_NAME) camera use

Disable/enable an input with jQuery?

Approach 4 (this is extension of wild coder answer)

_x000D_
_x000D_
txtName.disabled=1     // 0 for enable
_x000D_
<input id="txtName">
_x000D_
_x000D_
_x000D_

Bash conditionals: how to "and" expressions? (if [ ! -z $VAR && -e $VAR ])

Simply quote your variable:

[ -e "$VAR" ]

This evaluates to [ -e "" ] if $VAR is empty.

Your version does not work because it evaluates to [ -e ]. Now in this case, bash simply checks if the single argument (-e) is a non-empty string.

From the manpage:

test and [ evaluate conditional expressions using a set of rules based on the number of arguments. ...

1 argument

The expression is true if and only if the argument is not null.

(Also, this solution has the additional benefit of working with filenames containing spaces)

How can I debug what is causing a connection refused or a connection time out?

The problem

The problem is in the network layer. Here are the status codes explained:

  • Connection refused: The peer is not listening on the respective network port you're trying to connect to. This usually means that either a firewall is actively denying the connection or the respective service is not started on the other site or is overloaded.

  • Connection timed out: During the attempt to establish the TCP connection, no response came from the other side within a given time limit. In the context of urllib this may also mean that the HTTP response did not arrive in time. This is sometimes also caused by firewalls, sometimes by network congestion or heavy load on the remote (or even local) site.

In context

That said, it is probably not a problem in your script, but on the remote site. If it's occuring occasionally, it indicates that the other site has load problems or the network path to the other site is unreliable.

Also, as it is a problem with the network, you cannot tell what happened on the other side. It is possible that the packets travel fine in the one direction but get dropped (or misrouted) in the other.

It is also not a (direct) DNS problem, that would cause another error (Name or service not known or something similar). It could however be the case that the DNS is configured to return different IP addresses on each request, which would connect you (DNS caching left aside) to different addresses hosts on each connection attempt. It could in turn be the case that some of these hosts are misconfigured or overloaded and thus cause the aforementioned problems.

Debugging this

As suggested in the another answer, using a packet analyzer can help to debug the issue. You won't see much however except the packets reflecting exactly what the error message says.

To rule out network congestion as a problem you could use a tool like mtr or traceroute or even ping to see if packets get lost to the remote site. Note that, if you see loss in mtr (and any traceroute tool for that matter), you must always consider the first host where loss occurs (in the route from yours to remote) as the one dropping packets, due to the way ICMP works. If the packets get lost only at the last hop over a long time (say, 100 packets), that host definetly has an issue. If you see that this behaviour is persistent (over several days), you might want to contact the administrator.

Loss in a middle of the route usually corresponds to network congestion (possibly due to maintenance), and there's nothing you could do about it (except whining at the ISP about missing redundance).

If network congestion is not a problem (i.e. not more than, say, 5% of the packets get lost), you should contact the remote server administrator to figure out what's wrong. He may be able to see relevant infos in system logs. Running a packet analyzer on the remote site might also be more revealing than on the local site. Checking whether the port is open using netstat -tlp is definetly recommended then.

Insert string at specified position

Simple and another way to solve :

function stringInsert($str,$insertstr,$pos)
{
  $count_str=strlen($str);
  for($i=0;$i<$pos;$i++)
    {
    $new_str .= $str[$i];
    }

    $new_str .="$insertstr";

   for($i=$pos;$i<$count_str;$i++)
    {
    $new_str .= $str[$i];
    }

  return $new_str;

}  

remove double quotes from Json return data using Jquery

You can simple try String(); to remove the quotes.

Refer the first example here: https://www.w3schools.com/jsref/jsref_string.asp

Thank me later.

PS: TO MODs: don't mistaken me for digging the dead old question. I faced this issue today and I came across this post while searching for the answer and I'm just posting the answer.

What is Join() in jQuery?

I use join to separate the word in array with "and, or , / , &"

EXAMPLE

HTML

<p>London Mexico Canada</p>
<div></div>

JS

 newText = $("p").text().split(" ").join(" or ");
 $('div').text(newText);

Results

London or Mexico or Canada

Twitter Bootstrap 3, vertically center content

You can use display:inline-block instead of float and vertical-align:middle with this CSS:

.col-lg-4, .col-lg-8 {
    float:none;
    display:inline-block;
    vertical-align:middle;
    margin-right:-4px;
}

The demo http://bootply.com/94402

How can I make my own event in C#?

to do it we have to know the three components

  1. the place responsible for firing the Event
  2. the place responsible for responding to the Event
  3. the Event itself

    a. Event

    b .EventArgs

    c. EventArgs enumeration

now lets create Event that fired when a function is called

but I my order of solving this problem like this: I'm using the class before I create it

  1. the place responsible for responding to the Event

    NetLog.OnMessageFired += delegate(object o, MessageEventArgs args) 
    {
            // when the Event Happened I want to Update the UI
            // this is WPF Window (WPF Project)  
            this.Dispatcher.Invoke(() =>
            {
                LabelFileName.Content = args.ItemUri;
                LabelOperation.Content = args.Operation;
                LabelStatus.Content = args.Status;
            });
    };
    

NetLog is a static class I will Explain it later

the next step is

  1. the place responsible for firing the Event

    //this is the sender object, MessageEventArgs Is a class I want to create it  and Operation and Status are Event enums
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Started));
    downloadFile = service.DownloadFile(item.Uri);
    NetLog.FireMessage(this, new MessageEventArgs("File1.txt", Operation.Download, Status.Finished));
    

the third step

  1. the Event itself

I warped The Event within a class called NetLog

public sealed class NetLog
{
    public delegate void MessageEventHandler(object sender, MessageEventArgs args);

    public static event MessageEventHandler OnMessageFired;
    public static void FireMessage(Object obj,MessageEventArgs eventArgs)
    {
        if (OnMessageFired != null)
        {
            OnMessageFired(obj, eventArgs);
        }
    }
}

public class MessageEventArgs : EventArgs
{
    public string ItemUri { get; private set; }
    public Operation Operation { get; private set; }
    public Status Status { get; private set; }

    public MessageEventArgs(string itemUri, Operation operation, Status status)
    {
        ItemUri = itemUri;
        Operation = operation;
        Status = status;
    }
}

public enum Operation
{
    Upload,Download
}

public enum Status
{
    Started,Finished
}

this class now contain the Event, EventArgs and EventArgs Enums and the function responsible for firing the event

sorry for this long answer

How to create a connection string in asp.net c#

Demo :

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

Based on your question:

<connectionStrings>
    <add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>

Refer links:

http://www.connectionstrings.com/store-connection-string-in-webconfig/

Retrive connection string from web.config file:

write the below code in your file where you want;

string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;

SqlConnection con = new SqlConnection(connstring);

or you can go in your way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);

Note:

The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)

How to Convert unsigned char* to std::string in C++?

BYTE* is probably a typedef for unsigned char*, but I can't say for sure. It would help if you tell us what BYTE is.

If BYTE* is unsigned char*, you can convert it to an std::string using the std::string range constructor, which will take two generic Iterators.

const BYTE* str1 = reinterpret_cast<const BYTE*> ("Hello World");
int len = strlen(reinterpret_cast<const char*>(str1));
std::string str2(str1, str1 + len);

That being said, are you sure this is a good idea? If BYTE is unsigned char it may contain non-ASCII characters, which can include NULLs. This will make strlen give an incorrect length.

Android device chooser - My device seems offline

I had a similar problem in Android Studio 0.2.2 (IntelliJ). On Windows 7 my Nexus 7 did not appear in device chooser although it was fine on my Mac. I could also browse my Nexus 7 in Windows Explorer.

In the end I needed to install the Asus USB drivers for the Nexus 7 (link):

After that ADB detected my Nexus and everything worked as expected.

How to ftp with a batch file?

Each line of a batch file will get executed; but only after the previous line has completed. In your case, as soon as it hits the ftp line the ftp program will start and take over user input. When it is closed then the remaining lines will execute. Meaning the username/password are never sent to the FTP program and instead will be fed to the command prompt itself once the ftp program is closed.

Instead you need to pass everything you need on the ftp command line. Something like:

@echo off
echo user MyUserName> ftpcmd.dat
echo MyPassword>> ftpcmd.dat
echo bin>> ftpcmd.dat
echo put %1>> ftpcmd.dat
echo quit>> ftpcmd.dat
ftp -n -s:ftpcmd.dat SERVERNAME.COM
del ftpcmd.dat

UTF-8 problems while reading CSV file with fgetcsv

Now I got it working (after removing the header command). I think the problem was that the encoding of the php file was in ISO-8859-1. I set it to UTF-8 without BOM. I thought I already have done that, but perhaps I made an additional undo.

Furthermore, I used SET NAMES 'utf8' for the database. Now it is also correct in the database.

Who sets response content-type in Spring MVC (@ResponseBody)

I set the content-type in the MarshallingView in the ContentNegotiatingViewResolver bean. It works easily, clean and smoothly:

<property name="defaultViews">
  <list>
    <bean class="org.springframework.web.servlet.view.xml.MarshallingView">
      <constructor-arg>
        <bean class="org.springframework.oxm.xstream.XStreamMarshaller" />     
      </constructor-arg>
      <property name="contentType" value="application/xml;charset=UTF-8" />
    </bean>
  </list>
</property>

How can I use the apply() function for a single column?

Given a sample dataframe df as:

a,b
1,2
2,3
3,4
4,5

what you want is:

df['a'] = df['a'].apply(lambda x: x + 1)

that returns:

   a  b
0  2  2
1  3  3
2  4  4
3  5  5

How to change an input button image using CSS?

Perhaps you could just import a .js file as well and have the image replacement there, in JavaScript.

Access Https Rest Service using Spring RestTemplate

KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(new FileInputStream(new File(keyStoreFile)),
  keyStorePassword.toCharArray());

SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(
  new SSLContextBuilder()
    .loadTrustMaterial(null, new TrustSelfSignedStrategy())
    .loadKeyMaterial(keyStore, keyStorePassword.toCharArray())
    .build(),
    NoopHostnameVerifier.INSTANCE);

HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(
  socketFactory).build();

ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(
  httpClient);
RestTemplate restTemplate = new RestTemplate(requestFactory);
MyRecord record = restTemplate.getForObject(uri, MyRecord.class);
LOG.debug(record.toString());

Page scroll when soft keyboard popped up

put this inside your Manifest like this in No fullscreen Mode

android:windowSoftInputMode="stateVisible|adjustPan" 

in your manifest

<activity
    android:windowSoftInputMode="stateVisible|adjustPan"
    android:name="com.example.patronusgps.MainActivity"
    android:label="@string/app_name" >
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />

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

Regular expression for matching HH:MM time format

You can try the following

^\d{1,2}([:.]?\d{1,2})?([ ]?[a|p]m)?$

It can detect the following patterns :

2300 
23:00 
4 am 
4am 
4pm 
4 pm
04:30pm 
04:30 pm 
4:30pm 
4:30 pm
04.30pm
04.30 pm
4.30pm
4.30 pm
23:59 
0000 
00:00

Ship an application with a database

I modified the class and the answers to the question and wrote a class that allows updating the database via DB_VERSION.

public class DatabaseHelper extends SQLiteOpenHelper {
    private static String DB_NAME = "info.db";
    private static String DB_PATH = "";
    private static final int DB_VERSION = 1;

    private SQLiteDatabase mDataBase;
    private final Context mContext;
    private boolean mNeedUpdate = false;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        if (android.os.Build.VERSION.SDK_INT >= 17)
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        else
            DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
        this.mContext = context;

        copyDataBase();

        this.getReadableDatabase();
    }

    public void updateDataBase() throws IOException {
        if (mNeedUpdate) {
            File dbFile = new File(DB_PATH + DB_NAME);
            if (dbFile.exists())
                dbFile.delete();

            copyDataBase();

            mNeedUpdate = false;
        }
    }

    private boolean checkDataBase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    private void copyDataBase() {
        if (!checkDataBase()) {
            this.getReadableDatabase();
            this.close();
            try {
                copyDBFile();
            } catch (IOException mIOException) {
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }

    private void copyDBFile() throws IOException {
        InputStream mInput = mContext.getAssets().open(DB_NAME);
        //InputStream mInput = mContext.getResources().openRawResource(R.raw.info);
        OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0)
            mOutput.write(mBuffer, 0, mLength);
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    public boolean openDataBase() throws SQLException {
        mDataBase = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        return mDataBase != null;
    }

    @Override
    public synchronized void close() {
        if (mDataBase != null)
            mDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            mNeedUpdate = true;
    }
}

Using a class.

In the activity class, declare variables.

private DatabaseHelper mDBHelper;
private SQLiteDatabase mDb;

In the onCreate method, write the following code.

mDBHelper = new DatabaseHelper(this);

try {
    mDBHelper.updateDataBase();
} catch (IOException mIOException) {
    throw new Error("UnableToUpdateDatabase");
}

try {
    mDb = mDBHelper.getWritableDatabase();
} catch (SQLException mSQLException) {
    throw mSQLException;
}

If you add a database file to the folder res/raw then use the following modification of the class.

public class DatabaseHelper extends SQLiteOpenHelper {
    private static String DB_NAME = "info.db";
    private static String DB_PATH = "";
    private static final int DB_VERSION = 1;

    private SQLiteDatabase mDataBase;
    private final Context mContext;
    private boolean mNeedUpdate = false;

    public DatabaseHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        if (android.os.Build.VERSION.SDK_INT >= 17)
            DB_PATH = context.getApplicationInfo().dataDir + "/databases/";
        else
            DB_PATH = "/data/data/" + context.getPackageName() + "/databases/";
        this.mContext = context;

        copyDataBase();

        this.getReadableDatabase();
    }

    public void updateDataBase() throws IOException {
        if (mNeedUpdate) {
            File dbFile = new File(DB_PATH + DB_NAME);
            if (dbFile.exists())
                dbFile.delete();

            copyDataBase();

            mNeedUpdate = false;
        }
    }

    private boolean checkDataBase() {
        File dbFile = new File(DB_PATH + DB_NAME);
        return dbFile.exists();
    }

    private void copyDataBase() {
        if (!checkDataBase()) {
            this.getReadableDatabase();
            this.close();
            try {
                copyDBFile();
            } catch (IOException mIOException) {
                throw new Error("ErrorCopyingDataBase");
            }
        }
    }

    private void copyDBFile() throws IOException {
        //InputStream mInput = mContext.getAssets().open(DB_NAME);
        InputStream mInput = mContext.getResources().openRawResource(R.raw.info);
        OutputStream mOutput = new FileOutputStream(DB_PATH + DB_NAME);
        byte[] mBuffer = new byte[1024];
        int mLength;
        while ((mLength = mInput.read(mBuffer)) > 0)
            mOutput.write(mBuffer, 0, mLength);
        mOutput.flush();
        mOutput.close();
        mInput.close();
    }

    public boolean openDataBase() throws SQLException {
        mDataBase = SQLiteDatabase.openDatabase(DB_PATH + DB_NAME, null, SQLiteDatabase.CREATE_IF_NECESSARY);
        return mDataBase != null;
    }

    @Override
    public synchronized void close() {
        if (mDataBase != null)
            mDataBase.close();
        super.close();
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        if (newVersion > oldVersion)
            mNeedUpdate = true;
    }
}

http://blog.harrix.org/article/6784

JS how to cache a variable

Use localStorage for that. It's persistent over sessions.

Writing :

localStorage['myKey'] = 'somestring'; // only strings

Reading :

var myVar = localStorage['myKey'] || 'defaultValue';

If you need to store complex structures, you might serialize them in JSON. For example :

Reading :

var stored = localStorage['myKey'];
if (stored) myVar = JSON.parse(stored);
else myVar = {a:'test', b: [1, 2, 3]};

Writing :

localStorage['myKey'] = JSON.stringify(myVar);

Note that you may use more than one key. They'll all be retrieved by all pages on the same domain.

Unless you want to be compatible with IE7, you have no reason to use the obsolete and small cookies.

Why does an onclick property set with setAttribute fail to work in IE?

Actually, as far as I know, dynamically created inline event-handlers DO work perfectly within Internet Explorer 8 when created with the x.setAttribute() command; you just have to position them properly within your JavaScript code. I stumbled across the solution to your problem (and mine) here.

When I moved all of my statements containing x.appendChild() to their correct positions (i.e., immediately following the last setAttribute command within their groups), I found that EVERY single setAttribute worked in IE8 as it was supposed to, including all form input attributes (including "name" and "type" attributes, as well as my "onclick" event-handlers).

I found this quite remarkable, since all I got in IE before I did this was garbage rendered across the screen, and one error after another. In addition, I found that every setAttribute still worked within the other browsers as well, so if you just remember this simple coding-practice, you'll be good to go in most cases.

However, this solution won't work if you have to change any attributes on the fly, since they cannot be changed in IE once their HTML element has been appended to the DOM; in this case, I would imagine that one would have to delete the element from the DOM, and then recreate it and its attributes (in the correct order, of course!) for them to work properly, and not throw any errors.

How to dynamically update labels captions in VBA form?

Use Controls object

For i = 1 To X
    Controls("Label" & i).Caption =  MySheet.Cells(i + 1, i).Value
Next

Unable to read repository at http://download.eclipse.org/releases/indigo

No meu caso era o anti-vírus que estava bloqueando a conexão do eclipse, desativei o anti-víruse tudo funcionou o//.

Translation: In my case it was the anti-virus that was blocking the connection from eclipse. I disabled the anti-virus and everything worked.

How can you have SharePoint Link Lists default to opening in a new window?

The same instance for SP2010; the Links List webpart will not automatically open in a new window, rather user must manually rt click Link object and select Open in New Window.

The add/ insert Link option withkin SP2010 will allow a user to manually configure the link to open in a new window.

Maybe SP2012 release will adrress this...

What does string::npos mean in this code?

The document for string::npos says:

npos is a static member constant value with the greatest possible value for an element of type size_t.

As a return value it is usually used to indicate failure.

This constant is actually defined with a value of -1 (for any trait), which because size_t is an unsigned integral type, becomes the largest possible representable value for this type.

Navigation drawer: How do I set the selected item at startup?

on your activity(behind the drawer):

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
            this, drawer, toolbar,
               R.string.navigation_drawer_open,
               R.string.navigation_drawer_close);
    drawer.addDrawerListener(toggle);
    toggle.syncState();

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
    navigationView.setNavigationItemSelectedListener(this);
    navigationView.setCheckedItem(R.id.nav_portfolio);
    onNavigationItemSelected(navigationView.getMenu().getItem(0));
}

and

@Override
public boolean onNavigationItemSelected(MenuItem item) {
    // Handle navigation view item clicks here.
    int id = item.getItemId();

    Fragment fragment = null;

    if (id == R.id.nav_test1) {
        fragment = new Test1Fragment();
        displaySelectedFragment(fragment);
    } else if (id == R.id.nav_test2) {
        fragment = new Test2Fragment();
        displaySelectedFragment(fragment);
    }

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    drawer.closeDrawer(GravityCompat.START);
    return true;
}

and in your menu:

<group android:checkableBehavior="single">

    <item
        android:id="@+id/nav_test1"
        android:title="@string/test1" />

    <item
        android:id="@+id/nav_test2"
        android:title="@string/test2" />

  </group>

so first menu is highlight and show as default menu.

HTML5 Form Input Pattern Currency Format

Another answer for this would be

^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{2}|)$

This will match a string of:

  • one or more numbers with out the decimal place (\d+)
  • any number of commas each of which must be followed by 3 numbers and have upto 3 numbers before it (\d{1,3})(\,\d{3}|)*

Each or which can have a decimal place which must be followed by 2 numbers (.\d{2}|)

Why doesn't JavaScript have a last method?

Yeah, or just:

var arr = [1, 2, 5];
arr.reverse()[0]

if you want the value, and not a new list.

How do you programmatically update query params in react-router?

It can also be written this way

this.props.history.push(`${window.location.pathname}&page=${pageNumber}`)

How do you make an element "flash" in jQuery

If you're using jQueryUI, there is pulsate function in UI/Effects

$("div").click(function () {
      $(this).effect("pulsate", { times:3 }, 2000);
});

http://docs.jquery.com/UI/Effects/Pulsate

Convert pandas.Series from dtype object to float, and errors to nans

In [30]: pd.Series([1,2,3,4,'.']).convert_objects(convert_numeric=True)
Out[30]: 
0     1
1     2
2     3
3     4
4   NaN
dtype: float64

ComboBox: Adding Text and Value to an Item (no Binding Source)

This is a very simple solution for windows forms if all is needed is the final value as a (string). The items' names will be displayed on the Combo Box and the selected value can be easily compared.

List<string> items = new List<string>();

// populate list with test strings
for (int i = 0; i < 100; i++)
            items.Add(i.ToString());

// set data source
testComboBox.DataSource = items;

and on the event handler get the value (string) of the selected value

string test = testComboBox.SelectedValue.ToString();

Calculate time difference in minutes in SQL Server

Please try as below to get the time difference in hh:mm:ss format

Select StartTime, EndTime, CAST((EndTime - StartTime) as time(0)) 'TotalTime' from [TableName]

Using css transform property in jQuery

$(".oSlider-rotate").slider({
     min: 10,
     max: 74,
     step: .01,
     value: 24,
     slide: function(e,ui){
                 $('.user-text').css('transform', 'scale(' + ui.value + ')')

            }                
  });

This will solve the issue

How to Position a table HTML?

As BalausC mentioned in a comment, you are probably looking for CSS (Cascading Style Sheets) not HTML attributes.

To position an element, a <table> in your case you want to use either padding or margins.

the difference between margins and paddings can be seen as the "box model":

box model image

Image from HTML Dog article on margins and padding http://www.htmldog.com/guides/cssbeginner/margins/.

I highly recommend the article above if you need to learn how to use CSS.

To move the table down and right I would use margins like so:

table{
    margin:25px 0 0 25px;
}

This is in shorthand so the margins are as follows:

margin: top right bottom left;

Looping through JSON with node.js

A little late but I believe some further clarification is given below.

You can iterate through a JSON array with a simple loop as well, like:

for(var i = 0; i < jsonArray.length; i++)
{
    console.log(jsonArray[i].attributename);
}

If you have a JSON object and you want to loop through all of its inner objects, then you first need to get all the keys in an array and loop through the keys to retrieve objects using the key names, like:

var keys = Object.keys(jsonObject);
for(var i = 0; i < keys.length; i++) 
{
    var key = keys[i];
    console.log(jsonObject.key.attributename);
}

What is the best way to paginate results in SQL Server

From 2012 onward we can use OFFSET 10 ROWS FETCH NEXT 10 ROWS ONLY

How to ensure a <select> form field is submitted when it is disabled?

Or use some JavaScript to change the name of the select and set it to disabled. This way the select is still submitted, but using a name you aren't checking.

Angularjs - display current date

Here is the sample of your answer: http://plnkr.co/edit/MKugkgCSpdZFefSeDRi7?p=preview

<span>Date Of Birth: {{DateOfBirth | date:"dd-MM-yyyy"}}</span>
<input type="text" datepicker-popup="dd/MM/yyyy" ng-model="DateOfBirth" class="form-control" />

and then in the controller:

$scope.DateOfBirth = new Date();

Sql query to insert datetime in SQL Server

I encounter into a more generic problem: getting different (and not necessarily known) datetime formats and insert them into datetime column. I've solved it using this statement, which was finally became a scalar function (relevant for ODBC canonical, american, ANSI and british\franch date style - can be expanded):

insert into <tableName>(<dateTime column>) values(coalesce 
(TRY_CONVERT(datetime, <DateString, 121), TRY_CONVERT(datetime, <DateString>, 
101), TRY_CONVERT(datetime, <DateString>, 102), TRY_CONVERT(datetime, 
<DateString>, 103))) 

How to install JQ on Mac by command-line?

You can install any application/packages with brew on mac. If you want to know the exact command just search your package on https://brewinstall.org and you will get the set of commands needed to install that package.

First open terminal and install brew

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" < /dev/null 2> /dev/null

Now Install jq

brew install jq

pass **kwargs argument to another function with **kwargs

For #2 args will be only a formal parameter with dict value, but not a keyword type parameter.

If you want to pass a keyword type parameter into a keyword argument You need to specific ** before your dictionary, which means **args

check this out for more detail on using **kw

http://www.saltycrane.com/blog/2008/01/how-to-use-args-and-kwargs-in-python/

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

Getting URL parameter in java and extract a specific text from that URL

this will work for all sort of youtube url :
if url could be

youtube.com/?v=_RCIP6OrQrE
youtube.com/v/_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE
youtube.com/watch?v=_RCIP6OrQrE&feature=whatever&this=that

Pattern p = Pattern.compile("http.*\\?v=([a-zA-Z0-9_\\-]+)(?:&.)*");
String url = "http://www.youtube.com/watch?v=_RCIP6OrQrE";
Matcher m = p.matcher(url.trim()); //trim to remove leading and trailing space if any

if (m.matches()) {
    url = m.group(1);        
}
System.out.println(url);

this will extract video id from your url

further reference

String to HtmlDocument

Using Html Agility Pack as suggested by SLaks, this becomes very easy:

string html = webClient.DownloadString(url);
var doc = new HtmlDocument();
doc.LoadHtml(html);

HtmlNode specificNode = doc.GetElementById("nodeId");
HtmlNodeCollection nodesMatchingXPath = doc.DocumentNode.SelectNodes("x/path/nodes");

WPF Label Foreground Color

The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:

<StackPanel>
    <Label Foreground="Red">Red text</Label>
    <Label Foreground="Blue">Blue text</Label>
</StackPanel>

In summary, No, there was nothing wrong with your snippet.

Remove 'standalone="yes"' from generated XML

in JAXB that is part of JDK1.6

marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);

Why is the Visual Studio 2015/2017/2019 Test Runner not discovering my xUnit v2 tests

I am using xUnit 2.2.0.

My issue was my solution was not able to find certain dlls and app.config was trying to resolve them. The error was not showing up in the test output window in Visual Studio.

I was able to identify the error when I installed xunit.runner.console and tried to run the tests through command line.

How to run xunit tests in CLI.

Binding to static property

In .NET 4.5 it's possible to bind to static properties, read more

You can use static properties as the source of a data binding. The data binding engine recognizes when the property's value changes if a static event is raised. For example, if the class SomeClass defines a static property called MyProperty, SomeClass can define a static event that is raised when the value of MyProperty changes. The static event can use either of the following signatures:

public static event EventHandler MyPropertyChanged; 
public static event EventHandler<PropertyChangedEventArgs> StaticPropertyChanged; 

Note that in the first case, the class exposes a static event named PropertyNameChanged that passes EventArgs to the event handler. In the second case, the class exposes a static event named StaticPropertyChanged that passes PropertyChangedEventArgs to the event handler. A class that implements the static property can choose to raise property-change notifications using either method.

Spring @Autowired and @Qualifier

The @Qualifier annotation is used to resolve the autowiring conflict, when there are multiple beans of same type.

The @Qualifier annotation can be used on any class annotated with @Component or on methods annotated with @Bean. This annotation can also be applied on constructor arguments or method parameters.

Ex:-

public interface Vehicle {
     public void start();
     public void stop();
}

There are two beans, Car and Bike implements Vehicle interface

@Component(value="car")
public class Car implements Vehicle {

     @Override
     public void start() {
           System.out.println("Car started");
     }

     @Override
     public void stop() {
           System.out.println("Car stopped");
     }
 }

@Component(value="bike")
public class Bike implements Vehicle {

     @Override
     public void start() {
          System.out.println("Bike started");
     }

     @Override
     public void stop() {
          System.out.println("Bike stopped");
     }
}

Injecting Bike bean in VehicleService using @Autowired with @Qualifier annotation. If you didn't use @Qualifier, it will throw NoUniqueBeanDefinitionException.

@Component
public class VehicleService {

    @Autowired
    @Qualifier("bike")
    private Vehicle vehicle;

    public void service() {
         vehicle.start();
         vehicle.stop();
    }
}

Reference:- @Qualifier annotation example

php codeigniter count rows

Try This :) I created my on model of count all results

in library_model

function count_all_results($column_name = array(),$where=array(), $table_name = array())
{
        $this->db->select($column_name);
        // If Where is not NULL
        if(!empty($where) && count($where) > 0 )
        {
            $this->db->where($where);
        }
        // Return Count Column
        return $this->db->count_all_results($table_name[0]);//table_name array sub 0
}

Your Controller will look like this

public function my_method()
{
  $data = array(
     $countall = $this->model->your_method_model()
  );
   $this->load->view('page',$data);
}

Then Simple Call The Library Model In Your Model

function your_method_model()
{
        return $this->library_model->count_all_results(
               ['id'],
               ['where],
               ['table name']
           );
}

Counting lines, words, and characters within a text file using Python

One of the way I like is this one , but may be good for small files

with open(fileName,'r') as content_file:
    content = content_file.read()
    lineCount = len(re.split("\n",content))
    words = re.split("\W+",content.lower())

To count words, there is two way, if you don't care about repetition you can just do

words_count = len(words)

if you want the counts of each word you can just do

import collections
words_count = collections.Counter(words) #Count the occurrence of each word

Visual Studio: How to show Overloads in IntelliSense?

It happens that none of the above methods work. Key binding is proper, but tool tip simply doesn't show in any case, neither as completion help or on demand.

To fix it just go to Tools\Text Editor\C# (or all languages) and check the 'Parameter Information'. Now it should work

How to kill a process in MacOS?

If you know the process name you can use:

killall Dock

If you don't you can open Activity Monitor and find it.

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

Bash 4's brace expansion has a step feature:

for {0..10..2}; do
  ..
done

No matter if Bash 2/3 (C-style for loop, see answers above) or Bash 4, I would prefer anything over the 'seq' command.

Open local folder from link

Linking to local resources is disabled in all modern browsers due to security restrictions.

For Firefox:

For security purposes, Mozilla applications block links to local files (and directories) from remote files. This includes linking to files on your hard drive, on mapped network drives, and accessible via Uniform Naming Convention (UNC) paths. This prevents a number of unpleasant possibilities, including:

  • Allowing sites to detect your operating system by checking default installation paths
  • Allowing sites to exploit system vulnerabilities (e.g., C:\con\con in Windows 95/98)
  • Allowing sites to detect browser preferences or read sensitive data

for IE:

Internet Explorer 6 Service Pack 1 (SP1) no longer allows browsing a local machine from the Internet zone. For instance, if an Internet site contains a link to a local file, Internet Explorer 6 SP1 displays a blank page when a user clicks on the link. Previous versions of Windows Internet Explorer followed the link to the local file.

for Opera (in the context of a security advisory, I'm sure there is a more canonical link for this):

As a security precaution, Opera does not allow Web pages to link to files on the user's local disk

Calculate distance between two points in google maps V3

Example using GPS latitude/longitude of 2 points.

var latitude1 = 39.46;
var longitude1 = -0.36;
var latitude2 = 40.40;
var longitude2 = -3.68;

var distance = google.maps.geometry.spherical.computeDistanceBetween(new google.maps.LatLng(latitude1, longitude1), new google.maps.LatLng(latitude2, longitude2));       

How do I select which GPU to run a job on?

Set the following two environment variables:

NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0

where gpu_id is the ID of your selected GPU, as seen in the host system's nvidia-smi (a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).

You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id parameter in nvidia-smi run in a terminal in the guest system).

More info

This method based on NVIDIA_VISIBLE_DEVICES exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).

Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0 or env in Kubernetes or Openshift.

If you want GPU load-balancing, make gpu_id random at each guest system start.

If setting this with python, make sure you are using strings for all environment variables, including numerical ones.

You can verify that a different card is selected for each value of gpu_id by inspecting nvidia-smi's Bus-Id parameter (in a terminal run in the guest system).

The accepted solution based on CUDA_VISIBLE_DEVICES alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).

This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).

This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.

Throughput and bandwidth difference?

In most cases with "bandwidth" and "throughput" it is OVER complicated; like trying to learn calculus in one day. There is NO need for this, in MOST cases when referencing "Bandwidth" and "Throughput".

All you need to know in MOST cases is this:

"MB" means mega "BYTES"; OR 8 bits and 8 bits and 8 bits, etc; is being sent down the line. Mb means mega "bits". OR a single bit and bit and bit, etc; down the line.

Example: IF your carrier says this is a "6 Mb line"; it means that is the maximum Bandwidth. More succinctly it means that you ONLY are going to benefit 750 kilobytes per/sec "throughput". Now why? Because the line is only sending a series of "bits", which uses 8 bits/sec to create a byte. Thus; you must divide bits/sec by 8 to get to bytes/sec. Thus: a 6Mb line can ONLY deliver 750 thousand bytes/sec.

Another example: I just got a fiber optic line from A T & T; and they LOVE to talk about "bits". So they advertise a whopping "100 mega bits per second". Big deal. Because that is only 12.5 "MBytes/per second.

Remember, EACH "character" on your keyboard or printed on the screen, etc, requires 8 bits; for the other end to "distinguish" what character it is, etc.

So even though I have a "Gargantuan" fiber line touted as "100Mb"; it is really only 12.5 MBytes (characters) per second (100 divided by 8).

Worse: MOST interchange the terms "MB" and "Mb". Worse yet; EVEN The technician that installed the Fiber Optic line and router in my home, did not know what the terms meant. So he thought, and his co-workers (according to him) believed the same. IE: That 100Mb line was a 100MB line. This is very sad.

A T & T reps on the phone rarely know the difference either. Even some of their supervisors do not know it either. Even sadder.

To summarize: "Bandwidth" uses "bits". "Throughput" uses "bytes". And...one byte takes up 8 bits. So again: a 100Mb line (bandwidth) can ONLY produce 12.5 MBytes/sec (throughput).

For whatever it's worth.

Find unique rows in numpy.array

np.unique works by sorting a flattened array, then looking at whether each item is equal to the previous. This can be done manually without flattening:

ind = np.lexsort(a.T)
a[ind[np.concatenate(([True],np.any(a[ind[1:]]!=a[ind[:-1]],axis=1)))]]

This method does not use tuples, and should be much faster and simpler than other methods given here.

NOTE: A previous version of this did not have the ind right after a[, which mean that the wrong indices were used. Also, Joe Kington makes a good point that this does make a variety of intermediate copies. The following method makes fewer, by making a sorted copy and then using views of it:

b = a[np.lexsort(a.T)]
b[np.concatenate(([True], np.any(b[1:] != b[:-1],axis=1)))]

This is faster and uses less memory.

Also, if you want to find unique rows in an ndarray regardless of how many dimensions are in the array, the following will work:

b = a[lexsort(a.reshape((a.shape[0],-1)).T)];
b[np.concatenate(([True], np.any(b[1:]!=b[:-1],axis=tuple(range(1,a.ndim)))))]

An interesting remaining issue would be if you wanted to sort/unique along an arbitrary axis of an arbitrary-dimension array, something that would be more difficult.

Edit:

To demonstrate the speed differences, I ran a few tests in ipython of the three different methods described in the answers. With your exact a, there isn't too much of a difference, though this version is a bit faster:

In [87]: %timeit unique(a.view(dtype)).view('<i8')
10000 loops, best of 3: 48.4 us per loop

In [88]: %timeit ind = np.lexsort(a.T); a[np.concatenate(([True], np.any(a[ind[1:]]!= a[ind[:-1]], axis=1)))]
10000 loops, best of 3: 37.6 us per loop

In [89]: %timeit b = [tuple(row) for row in a]; np.unique(b)
10000 loops, best of 3: 41.6 us per loop

With a larger a, however, this version ends up being much, much faster:

In [96]: a = np.random.randint(0,2,size=(10000,6))

In [97]: %timeit unique(a.view(dtype)).view('<i8')
10 loops, best of 3: 24.4 ms per loop

In [98]: %timeit b = [tuple(row) for row in a]; np.unique(b)
10 loops, best of 3: 28.2 ms per loop

In [99]: %timeit ind = np.lexsort(a.T); a[np.concatenate(([True],np.any(a[ind[1:]]!= a[ind[:-1]],axis=1)))]
100 loops, best of 3: 3.25 ms per loop

<!--[if !IE]> not working

For targeting IE Users:

<!--[if IE]>
Place Content here for Users of Internet Explorer.
<![endif]-->

For targeting all others:

<![if !IE]>
Place Content here for Users of all other Browsers.
<![endif]>

The Conditional Comments can only be detected by Internet Explorer, all other Browsers thread it as normal Comments.

To target IE 6,7 etc.. You have to use "Greater Than Equal" or "Lesser Than (Equal)" in the If Statement. Like this.

Greater Than or Equal:

<!--[if gte IE 7]>
Place Content here for Users of Internet Explorer 7 or above.
<![endif]-->

Lesser Than:

<!--[if lt IE 6]>
Place Content here for Users of Internet Explorer 5 or lower.
<![endif]-->

Source: mediacollege.com

Windows batch: sleep

The Windows 2003 Resource Kit has a sleep batch file. If you ever move up to PowerShell, you can use:

Start-Sleep -s <time to sleep>

Or something like that.

Pass a javascript variable value into input type hidden value

if you already have that hidden input :

function product(a, b) {
   return a * b;
}
function setInputValue(input_id, val) {
    document.getElementById(input_id).setAttribute('value', val);
}

if not, you can create one, add it to the body and then set it's value :

function addInput(val) {
    var input = document.createElement('input');
    input.setAttribute('type', 'hidden');
    input.setAttribute('value', val);
    document.body.appendChild(input);
}

And then you can use(depending on the case) :

addInput(product(2, 3)); // if you want to create the input
// or
setInputValue('input_id', product(2, 3)); 

When should I use git pull --rebase?

Just remember:

  • pull = fetch + merge
  • pull --rebase = fetch + rebase

So, choose the way what you want to handle your branch.

You'd better know the difference between merge and rebase :)

How to use ImageBackground to set background image for screen in react-native

Two options:

  1. Try setting width and height to width and height of the device screen
  2. Good old position absolute

Code for #2:

 render(){
    return(
        <View style={{ flex: 1 }}>
           <Image style={{ width: screenWidth, height: screenHeight, position: 'absolute', top: 0, left: 0 }}/>
           <Text>Hey look, image background</Text>
        </View>
    )
}

Edit: For option #2 you can experiment with resizeMode="stretch|cover"

Edit 2: Keep in mind that option #2 renders the image and then everything after that in this order, which means that some pixels are rendered twice, this might have a very small performance impact (usually unnoticeable) but just for your information

Switch statement for string matching in JavaScript

You can't do it in a switch unless you're doing full string matching; that's doing substring matching. (This isn't quite true, as Sean points out in the comments. See note at the end.)

If you're happy that your regex at the top is stripping away everything that you don't want to compare in your match, you don't need a substring match, and could do:

switch (base_url_string) {
    case "xxx.local":
        // Blah
        break;
    case "xxx.dev.yyy.com":
        // Blah
        break;
}

...but again, that only works if that's the complete string you're matching. It would fail if base_url_string were, say, "yyy.xxx.local" whereas your current code would match that in the "xxx.local" branch.


Update: Okay, so technically you can use a switch for substring matching, but I wouldn't recommend it in most situations. Here's how (live example):

function test(str) {
    switch (true) {
      case /xyz/.test(str):
        display("• Matched 'xyz' test");
        break;
      case /test/.test(str):
        display("• Matched 'test' test");
        break;
      case /ing/.test(str):
        display("• Matched 'ing' test");
        break;
      default:
        display("• Didn't match any test");
        break;
    }
}

That works because of the way JavaScript switch statements work, in particular two key aspects: First, that the cases are considered in source text order, and second that the selector expressions (the bits after the keyword case) are expressions that are evaluated as that case is evaluated (not constants as in some other languages). So since our test expression is true, the first case expression that results in true will be the one that gets used.

I get Access Forbidden (Error 403) when setting up new alias

This question is old and although you managed to make it work but I feel it would be helpful if I make clear some of points you have raised here.

First about directory name having spaces. I have been playing with apache2 configuration files and I have discovered that, if the directory name has space then enclose it in double quotes and all problems disappear. For example...

    NameVirtualHost     local.webapp.org
    <VirtualHost local.webapp.org:80>
        ServerAdmin [email protected]
        DocumentRoot "E:/Project/my php webapp"
        ServerName local.webapp.org
    </VirtualHost>

Note the way DocumentRoot line is written.

Second is about Access forbidden from xampp. I found that default xampp configuration (..path to xampp/apache/httpd.conf) has a section that looks like the following.

    <Directory>
        AllowOverride none
        Require all denied
    </Directory>

Change it and make it look like below. Save the file restart apache from xampp and that solves the problem.

    <Directory>
       Options Indexes FollowSymLinks Includes ExecCGI
       AllowOverride none
       Require all granted
    </Directory>

How do I extract part of a string in t-sql

I would recommend a combination of PatIndex and Left. Carefully constructed, you can write a query that always works, no matter what your data looks like.

Ex:

Declare @Temp Table(Data VarChar(20))

Insert Into @Temp Values('BTA200')
Insert Into @Temp Values('BTA50')
Insert Into @Temp Values('BTA030')
Insert Into @Temp Values('BTA')
Insert Into @Temp Values('123')
Insert Into @Temp Values('X999')

Select Data, Left(Data, PatIndex('%[0-9]%', Data + '1') - 1)
From   @Temp

PatIndex will look for the first character that falls in the range of 0-9, and return it's character position, which you can use with the LEFT function to extract the correct data. Note that PatIndex is actually using Data + '1'. This protects us from data where there are no numbers found. If there are no numbers, PatIndex would return 0. In this case, the LEFT function would error because we are using Left(Data, PatIndex - 1). When PatIndex returns 0, we would end up with Left(Data, -1) which returns an error.

There are still ways this can fail. For a full explanation, I encourage you to read:

Extracting numbers with SQL Server

That article shows how to get numbers out of a string. In your case, you want to get alpha characters instead. However, the process is similar enough that you can probably learn something useful out of it.

I want to declare an empty array in java and then I want do update it but the code is not working

So the issue is in your array declaration you are declaring an empty array with the empty curly braces{} instead of an array that allows slots.

Roughly speaking, there can be three types of inputs :

 1. int array[] = null; #Does not point to any memory locations so is a null arrau
 2. int array[] = {) which is sort of equivalent to int array[] = new int[0];
 3. int array[] = new int[n] where n is some number indicating the number of 
memory locations in the array

How to make a 3-level collapsing menu in Bootstrap?

Bootstrap 3 dropped native support for nested collapsing menus, but there's a way to re-enable it with a 3rd party script. It's called SmartMenus. It means adding three new resources to your page, but it seamlessly supports Bootstrap 3.x with multiple levels of menus for nested <ul>/<li> elements with class="dropdown-menu". It automatically displays the proper caret indicator as well.

<head>
   ...
   <script src=".../jquery.smartmenus.min.js"></script>
   <script src=".../jquery.smartmenus.bootstrap.min.js"></script>
   ...
   <link rel="stylesheet" href=".../jquery.smartmenus.bootstrap.min.css"/>
   ...
</head>

Here's a demo page: http://vadikom.github.io/smartmenus/src/demo/bootstrap-navbar-fixed-top.html

what is an illegal reflective access

Apart from an understanding of the accesses amongst modules and their respective packages. I believe the crux of it lies in the Module System#Relaxed-strong-encapsulation and I would just cherry-pick the relevant parts of it to try and answer the question.

What defines an illegal reflective access and what circumstances trigger the warning?

To aid in the migration to Java-9, the strong encapsulation of the modules could be relaxed.

  • An implementation may provide static access, i.e. by compiled bytecode.

  • May provide a means to invoke its run-time system with one or more packages of one or more of its modules open to code in all unnamed modules, i.e. to code on the classpath. If the run-time system is invoked in this way, and if by doing so some invocations of the reflection APIs succeed where otherwise they would have failed.

In such cases, you've actually ended up making a reflective access which is "illegal" since in a pure modular world you were not meant to do such accesses.

How it all hangs together and what triggers the warning in what scenario?

This relaxation of the encapsulation is controlled at runtime by a new launcher option --illegal-access which by default in Java9 equals permit. The permit mode ensures

The first reflective-access operation to any such package causes a warning to be issued, but no warnings are issued after that point. This single warning describes how to enable further warnings. This warning cannot be suppressed.

The modes are configurable with values debug(message as well as stacktrace for every such access), warn(message for each such access), and deny(disables such operations).


Few things to debug and fix on applications would be:-

  • Run it with --illegal-access=deny to get to know about and avoid opening packages from one module to another without a module declaration including such a directive(opens) or explicit use of --add-opens VM arg.
  • Static references from compiled code to JDK-internal APIs could be identified using the jdeps tool with the --jdk-internals option

The warning message issued when an illegal reflective-access operation is detected has the following form:

WARNING: Illegal reflective access by $PERPETRATOR to $VICTIM

where:

$PERPETRATOR is the fully-qualified name of the type containing the code that invoked the reflective operation in question plus the code source (i.e., JAR-file path), if available, and

$VICTIM is a string that describes the member being accessed, including the fully-qualified name of the enclosing type

Questions for such a sample warning: = JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState

Last and an important note, while trying to ensure that you do not face such warnings and are future safe, all you need to do is ensure your modules are not making those illegal reflective accesses. :)

Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 71 bytes)

I had this problem. I searched the internet, took all advices, changes configurations, but the problem is still there. Finally with the help of the server administrator, he found that the problem lies in MySQL database column definition. one of the columns in the a table was assigned to 'Longtext' which leads to allocate 4,294,967,295 bites of memory. It seems working OK if you don't use MySqli prepare statement, but once you use prepare statement, it tries to allocate that amount of memory. I changed the column type to Mediumtext which needs 16,777,215 bites of memory space. The problem is gone. Hope this help.

npm install won't install devDependencies

make sure you don't have env variable NODE_ENV set to 'production'.

If you do, dev dependencies will not be installed without the --dev flag

How to sort a Pandas DataFrame by index?

Slightly more compact:

df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df = df.sort_index()
print(df)

Note:

Read data from a text file using Java

The reason your code skipped the last line was because you put fis.available() > 0 instead of fis.available() >= 0

How can I easily view the contents of a datatable or dataview in the immediate window

The Visual Studio debugger comes with four standard visualizers. These are the text, HTML, and XML visualizers, all of which work on string objects, and the dataset visualizer, which works for DataSet, DataView, and DataTable objects.

To use it, break into your code, mouse over your DataSet, expand the quick watch, view the Tables, expand that, then view Table[0] (for example). You will see something like {Table1} in the quick watch, but notice that there is also a magnifying glass icon. Click on that icon and your DataTable will open up in a grid view.

enter image description here

How to calculate the difference between two dates using PHP?

use this function

//function Diff between Dates
//////////////////////////////////////////////////////////////////////
//PARA: Date Should In YYYY-MM-DD Format
//RESULT FORMAT:
// '%y Year %m Month %d Day %h Hours %i Minute %s Seconds' =>  1 Year 3 Month 14 Day 11 Hours 49 Minute 36 Seconds
// '%y Year %m Month %d Day'                       =>  1 Year 3 Month 14 Days
// '%m Month %d Day'                                     =>  3 Month 14 Day
// '%d Day %h Hours'                                   =>  14 Day 11 Hours
// '%d Day'                                                 =>  14 Days
// '%h Hours %i Minute %s Seconds'         =>  11 Hours 49 Minute 36 Seconds
// '%i Minute %s Seconds'                           =>  49 Minute 36 Seconds
// '%h Hours                                          =>  11 Hours
// '%a Days                                                =>  468 Days
//////////////////////////////////////////////////////////////////////
function dateDifference($date_1 , $date_2 , $differenceFormat = '%a' )
{
    $datetime1 = date_create($date_1);
    $datetime2 = date_create($date_2);

    $interval = date_diff($datetime1, $datetime2);

    return $interval->format($differenceFormat);

}

only set parameter $differenceFormat As your need example I want Diff between to years with months and days your age

dateDifference(date('Y-m-d') , $date , '%y %m %d')

or other format

dateDifference(date('Y-m-d') , $date , '%y-%m-%d')

Changing the default title of confirm() in JavaScript?

YES YOU CAN do it!! It's a little tricky way ; ) (it almost works on ios)

var iframe = document.createElement("IFRAME");
iframe.setAttribute("src", 'data:text/plain,');
document.documentElement.appendChild(iframe);
if(window.frames[0].window.confirm("Are you sure?")){
    // what to do if answer "YES"
}else{
    // what to do if answer "NO"
}

Enjoy it!

How to make an HTML back link?

<a href="#" onclick="history.back();">Back</a>

How to launch jQuery Fancybox on page load?

For my case, the following can work successfully. When the page is loaded, the lightbox is pop-up immediately.

JQuery: 1.4.2

Fancybox: 1.3.1

<body onload="$('#aLink').trigger('click');">
<a id="aLink" href="http://www.google.com" >Link</a></body>

<script type="text/javascript">
    $(document).ready(function() {

        $("#aLink").fancybox({
            'width'             : '75%',
            'height'            : '75%',
            'autoScale'         : false,
            'transitionIn'      : 'none',
            'transitionOut'     : 'none',
            'type'              : 'iframe'
        });
    });
</script>

How can I read a whole file into a string variable

This is how I did it:

package main

import (
  "fmt"
  "os"
  "bytes"
  "log"
)

func main() {
   filerc, err := os.Open("filename")
   if err != nil{
     log.Fatal(err)
   }
   defer filerc.Close()

   buf := new(bytes.Buffer)
   buf.ReadFrom(filerc)
   contents := buf.String()

   fmt.Print(contents) 

}    

Generate an integer that is not among four billion given ones

You could speed up finding the missing integers after reading the existing ones by storing ranges of unvisited integers in some tree structure.

You'd start by storing [0..4294967295] and every time you read an integer you splice the range it falls in, deleting a range when it becomes empty. At the end you have the exact set of integers that are missing in the ranges. So if you see 5 as the first integer, you'd have [0..4] and [6..4294967295].

This is a lot slower than marking bits so it would only be a solution for the 10MB case provided you can store the lower levels of the tree in files.

One way to store such a tree would be a B-tree with the start of the range as the key and the end of the range as the value. Worst case usage would be when you get all odd or even integers which would mean storing 2^31 values or tens of GB for the tree... Ouch. Best case is a sorted file where you'd only use a few integers for the whole tree.

So not really the correct answer but I thought I'd mention this way of doing it. I suppose I'd fail the interview ;-)

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

I was getting this error while was presenting controller after the user opens the deeplink. I know this isn't the best solution, but if you are in short time frame here is a quick fix - just wrap your code in asyncAfter:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: { [weak self] in
                                navigationController.present(signInCoordinator.baseController, animated: animated, completion: completion)
                            })

It will give time for your presenting controller to call viewDidAppear.

How to compile or convert sass / scss to css with node-sass (no Ruby)?

The installation of these tools may vary on different OS.

Under Windows, node-sass currently supports VS2015 by default, if you only have VS2013 in your box and meet any error while running the command, you can define the version of VS by adding: --msvs_version=2013. This is noted on the node-sass npm page.

So, the safe command line that works on Windows with VS2013 is: npm install --msvs_version=2013 gulp node-sass gulp-sass

Error "File google-services.json is missing from module root folder. The Google Services Plugin cannot function without it"

Please go to this URL :

https://developers.google.com/mobile/add

Choose your Options and finally you will be able to download

google-service.json file

copy that file and paste it Into

YourProjectName/app Directory

Then recompile the project Most probably it will fly

In my case the project directory looks like this :

enter image description here

Convert JSON string to dict using Python

use simplejson or cjson for speedups

import simplejson as json

json.loads(obj)

or 

cjson.decode(obj)

Get Filename Without Extension in Python

In most cases, you shouldn't use a regex for that.

os.path.splitext(filename)[0]

This will also handle a filename like .bashrc correctly by keeping the whole name.

throwing exceptions out of a destructor

I am in the group that considers that the "scoped guard" pattern throwing in the destructor is useful in many situations - particularly for unit tests. However, be aware that in C++11, throwing in a destructor results in a call to std::terminate since destructors are implicitly annotated with noexcept.

Andrzej Krzemienski has a great post on the topic of destructors that throw:

He points out that C++11 has a mechanism to override the default noexcept for destructors:

In C++11, a destructor is implicitly specified as noexcept. Even if you add no specification and define your destructor like this:

  class MyType {
        public: ~MyType() { throw Exception(); }            // ...
  };

The compiler will still invisibly add specification noexcept to your destructor. And this means that the moment your destructor throws an exception, std::terminate will be called, even if there was no double-exception situation. If you are really determined to allow your destructors to throw, you will have to specify this explicitly; you have three options:

  • Explicitly specify your destructor as noexcept(false),
  • Inherit your class from another one that already specifies its destructor as noexcept(false).
  • Put a non-static data member in your class that already specifies its destructor as noexcept(false).

Finally, if you do decide to throw in the destructor, you should always be aware of the risk of a double-exception (throwing while the stack is being unwind because of an exception). This would cause a call to std::terminate and it is rarely what you want. To avoid this behaviour, you can simply check if there is already an exception before throwing a new one using std::uncaught_exception().

How to import a csv file using python with headers intact, where first column is a non-numerical

Python's csv module handles data row-wise, which is the usual way of looking at such data. You seem to want a column-wise approach. Here's one way of doing it.

Assuming your file is named myclone.csv and contains

workers,constant,age
w0,7.334,-1.406
w1,5.235,-4.936
w2,3.2225,-1.478
w3,0,0

this code should give you an idea or two:

>>> import csv
>>> f = open('myclone.csv', 'rb')
>>> reader = csv.reader(f)
>>> headers = next(reader, None)
>>> headers
['workers', 'constant', 'age']
>>> column = {}
>>> for h in headers:
...    column[h] = []
...
>>> column
{'workers': [], 'constant': [], 'age': []}
>>> for row in reader:
...   for h, v in zip(headers, row):
...     column[h].append(v)
...
>>> column
{'workers': ['w0', 'w1', 'w2', 'w3'], 'constant': ['7.334', '5.235', '3.2225', '0'], 'age': ['-1.406', '-4.936', '-1.478', '0']}
>>> column['workers']
['w0', 'w1', 'w2', 'w3']
>>> column['constant']
['7.334', '5.235', '3.2225', '0']
>>> column['age']
['-1.406', '-4.936', '-1.478', '0']
>>>

To get your numeric values into floats, add this

converters = [str.strip] + [float] * (len(headers) - 1)

up front, and do this

for h, v, conv in zip(headers, row, converters):
  column[h].append(conv(v))

for each row instead of the similar two lines above.

How can I find all matches to a regular expression in Python?

Use re.findall or re.finditer instead.

re.findall(pattern, string) returns a list of matching strings.

re.finditer(pattern, string) returns an iterator over MatchObject objects.

Example:

re.findall( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')
# Output: ['cats', 'dogs']

[x.group() for x in re.finditer( r'all (.*?) are', 'all cats are smarter than dogs, all dogs are dumber than cats')]
# Output: ['all cats are', 'all dogs are']

Java random numbers using a seed

That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.

Permission denied error on Github Push

Based on the information that the original poster has provided so far, it might be the case that the project owners of EasySoftwareLicensing/software-licensing-php will only accept pull requests from forks, so you may need to fork the main repo and push to your fork, then make pull requests from it to the main repo.

See the following GitHub help articles for instructions:

  1. Fork a Repo.
  2. Collaborating.

Identifying Exception Type in a handler Catch Block

Alternative Solution

Instead halting a debug session to add some throw-away statements to then recompile and restart, why not just use the debugger to answer that question immediately when a breakpoint is hit?

That can be done by opening up the Immediate Window of the debugger and typing a GetType off of the exception and hitting Enter. The immediate window also allows one to interrogate variables as needed.

See VS Docs: Immediate Window


For example I needed to know what the exception was and just extracted the Name property of GetType as such without having to recompile:

enter image description here

How we can bold only the name in table td tag not the value

Wrap the name in a span, give it a class and assign a style to that class:

<td><span class="names">Name text you want bold</span> rest of your text</td>

style:

.names { font-weight: bold; }

Download an SVN repository?

For me DownloadSVN is the best SVN client no install no explore shell integration so no need to worry about system instability small and very light weight and it does a great job just recently i had a very bad experience with TortoiseSVN on my WindowsXP_x86:) luckily i found this great SVN client

How do I redirect to the previous action in ASP.NET MVC?

You could return to the previous page by using ViewBag.ReturnUrl property.

Find Nth occurrence of a character in a string

Hi all i have created two overload methods for finding nth occurrence of char and for text with less complexity without navigating through loop ,which increase performance of your application.

public static int NthIndexOf(string text, char searchChar, int nthindex)
{
   int index = -1;
   try
   {
      var takeCount = text.TakeWhile(x => (nthindex -= (x == searchChar ? 1 : 0)) > 0).Count();
      if (takeCount < text.Length) index = takeCount;
   }
   catch { }
   return index;
}
public static int NthIndexOf(string text, string searchText, int nthindex)
{
     int index = -1;
     try
     {
        Match m = Regex.Match(text, "((" + searchText + ").*?){" + nthindex + "}");
        if (m.Success) index = m.Groups[2].Captures[nthindex - 1].Index;
     }
     catch { }
     return index;
}

How to read data from a file in Lua

There's a I/O library available, but if it's available depends on your scripting host (assuming you've embedded lua somewhere). It's available, if you're using the command line version. The complete I/O model is most likely what you're looking for.

Random Number Between 2 Double Numbers

You could use code like this:

public double getRandomNumber(double minimum, double maximum) {
    return minimum + randomizer.nextDouble() * (maximum - minimum);
}

How to round each item in a list of floats to 2 decimal places?

Another option which doesn't require numpy is:

precision = 2  
myRoundedList = [int(elem*(10**precision)+delta)/(10.0**precision) for elem in myList]

# delta=0 for floor
# delta = 0.5 for round
# delta = 1 for ceil

fail to change placeholder color with Bootstrap 3

There was an issue posted here about this: https://github.com/twbs/bootstrap/issues/14107

The issue was solved by this commit: https://github.com/twbs/bootstrap/commit/bd292ca3b89da982abf34473318c77ace3417fb5

The solution therefore is to override it back to #999 and not white as suggested (and also overriding all bootstraps styles, not just for webkit-styles):

.form-control::-moz-placeholder {
  color: #999;
}
.form-control:-ms-input-placeholder {
  color: #999;
}
.form-control::-webkit-input-placeholder {
  color: #999;
}

How to enter special characters like "&" in oracle database?

We can use another way as well for example to insert the value with special characters 'Java_22 & Oracle_14' into db we can use the following format..

'Java_22 '||'&'||' Oracle_14'

Though it consider as 3 different tokens we dont have any option as the handling of escape sequence provided in the oracle documentation is incorrect.

Class vs. static method in JavaScript

There are tree ways methods and properties are implemented on function or class objects, and on they instances.

  1. On the class (or function) itself : Foo.method() or Foo.prop. Those are static methods or properties
  2. On its prototype : Foo.prototype.method() or Foo.prototype.prop. When created, the instances will inherit those object via the prototype witch is {method:function(){...}, prop:...}. So the foo object will receive, as prototype, a copy of the Foo.prototype object.
  3. On the instance itself : the method or property is added to the object itself. foo={method:function(){...}, prop:...}

The this keyword will represent and act differently according to the context. In a static method, it will represent the class itself (witch is after all an instance of Function : class Foo {} is quite equivalent to let Foo = new Function({})

With ECMAScript 2015, that seems well implemented today, it is clearer to see the difference between class (static) methods and properties, instance methods and properties and own methods ans properties. You can thus create three method or properties having the same name, but being different because they apply to different objects, the this keyword, in methods, will apply to, respectively, the class object itself and the instance object, by the prototype or by its own.

class Foo {
  constructor(){super();}
  
  static prop = "I am static" // see 1.
  static method(str) {alert("static method"+str+" :"+this.prop)} // see 1.
  
  prop="I am of an instance"; // see 2.
  method(str) {alert("instance method"+str+" : "+this.prop)} // see 2.
}

var foo= new Foo();
foo.prop = "I am of own";  // see 3.
foo.func = function(str){alert("own method" + str + this.prop)} // see 3.

Python - add PYTHONPATH during command line module run

If you are running the command from a POSIX-compliant shell, like bash, you can set the environment variable like this:

PYTHONPATH="/path/to" python somescript.py somecommand

If it's all on one line, the PYTHONPATH environment value applies only to that one command.

$ echo $PYTHONPATH

$ python -c 'import sys;print("/tmp/pydir" in sys.path)'
False
$ PYTHONPATH=/tmp/pydir python -c 'import sys;print("/tmp/pydir" in sys.path)'
True
$ echo $PYTHONPATH