Programs & Examples On #Timesten

TimesTen is a high performance event-processing software component that enables applications to capture, store, use, and distribute information in real-time, while preserving transactional integrity and continuous availability.

PHP preg_match - only allow alphanumeric strings and - _ characters

Here is one equivalent of the accepted answer for the UTF-8 world.

if (!preg_match('/^[\p{L}\p{N}_-]+$/u', $string)){
  //Disallowed Character In $string
}

Explanation:

  • [] => character class definition
  • p{L} => matches any kind of letter character from any language
  • p{N} => matches any kind of numeric character
  • _- => matches underscore and hyphen
  • + => Quantifier — Matches between one to unlimited times (greedy)
  • /u => Unicode modifier. Pattern strings are treated as UTF-16. Also causes escape sequences to match unicode characters

Note, that if the hyphen is the last character in the class definition it does not need to be escaped. If the dash appears elsewhere in the class definition it needs to be escaped, as it will be seen as a range character rather then a hyphen.

How to concatenate string variables in Bash

If what you are trying to do is to split a string into several lines, you can use a backslash:

$ a="hello\
> world"
$ echo $a
helloworld

With one space in between:

$ a="hello \
> world"
$ echo $a
hello world

This one also adds only one space in between:

$ a="hello \
>      world"
$ echo $a
hello world

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

The practical way is setting font-family to a value that is the specific name of the semibold version, such as

font-family: "Myriad pro Semibold"

if that’s the name. (Personally I use my own font listing tool, which runs on Internet Explorer only to see the fonts in my system by names as usable in CSS.)

In this approach, font-weight is not needed (and probably better not set).

Web browsers have been poor at implementing font weights by the book: they largely cannot find the specific weight version, except bold. The workaround is to include the information in the font family name, even though this is not how things are supposed to work.

Testing with Segoe UI, which often exists in different font weight versions on Windows systems, I was able to make Internet Explorer 9 select the proper version when using the logical approach (of using the font family name Segoe UI and different font-weight values), but it failed on Firefox 9 and Chrome 16 (only normal and bold work). On all of these browsers, for example, setting font-family: Segoe UI Light works OK.

Google Gson - deserialize list<class> object? (generic type)

Since Gson 2.8, we can create util function like

public <T> List<T> getList(String jsonArray, Class<T> clazz) {
    Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
    return new Gson().fromJson(jsonArray, typeOfT);
}

Example using

String jsonArray = ...
List<User> user = getList(jsonArray, User.class);

UILabel text margin

If you're using autolayout in iOS 6+, you can do this by adjusting the intrinsicContentSize in a subclass of UILabel.

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.textAlignment = NSTextAlignmentRight;
    }
    return self;
}

- (CGSize)intrinsicContentSize 
{
    CGSize size = [super intrinsicContentSize];
    return CGSizeMake(size.width + 10.0, size.height);
}

Should I use PATCH or PUT in my REST API?

The PATCH method is the correct choice here as you're updating an existing resource - the group ID. PUT should only be used if you're replacing a resource in its entirety.

Further information on partial resource modification is available in RFC 5789. Specifically, the PUT method is described as follows:

Several applications extending the Hypertext Transfer Protocol (HTTP) require a feature to do partial resource modification. The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

Concatenate in jQuery Selector

There is nothing wrong with syntax of

$('#part' + number).html(text);

jQuery accepts a String (usually a CSS Selector) or a DOM Node as parameter to create a jQuery Object.

In your case you should pass a String to $() that is

$(<a string>)

Make sure you have access to the variables number and text.

To test do:

function(){
    alert(number + ":" + text);//or use console.log(number + ":" + text)
    $('#part' + number).html(text);
}); 

If you see you dont have access, pass them as parameters to the function, you have to include the uual parameters for $.get and pass the custom parameters after them.

Start a fragment via Intent within a Fragment

Try this it may help you:

public void ButtonClick(View view) {
    Fragment mFragment = new YourNextFragment(); 
    getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, mFragment).commit();
}

How to compare two List<String> to each other?

    private static bool CompareDictionaries(IDictionary<string, IEnumerable<string>> dict1, IDictionary<string, IEnumerable<string>> dict2)
    {
        if (dict1.Count != dict2.Count)
        {
            return false;
        }

        var keyDiff = dict1.Keys.Except(dict2.Keys);
        if (keyDiff.Any())
        {
            return false;
        }

        return (from key in dict1.Keys 
                let value1 = dict1[key] 
                let value2 = dict2[key] 
                select value1.Except(value2)).All(diffInValues => !diffInValues.Any());
    }

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

Sort dataGridView columns in C# ? (Windows Form)

This one is simplier :)

dataview dataview1; 
this.dataview1= dataset.tables[0].defaultview;
this.dataview1.sort = "[ColumnName] ASC, [ColumnName] DESC";
this.datagridview.datasource = dataview1;

How to get response from S3 getObject in Node.js?

Alternatively you could use minio-js client library get-object.js

var Minio = require('minio')

var s3Client = new Minio({
  endPoint: 's3.amazonaws.com',
  accessKey: 'YOUR-ACCESSKEYID',
  secretKey: 'YOUR-SECRETACCESSKEY'
})

var size = 0
// Get a full object.
s3Client.getObject('my-bucketname', 'my-objectname', function(e, dataStream) {
  if (e) {
    return console.log(e)
  }
  dataStream.on('data', function(chunk) {
    size += chunk.length
  })
  dataStream.on('end', function() {
    console.log("End. Total size = " + size)
  })
  dataStream.on('error', function(e) {
    console.log(e)
  })
})

Disclaimer: I work for Minio Its open source, S3 compatible object storage written in golang with client libraries available in Java, Python, Js, golang.

How to get JSON Key and Value?

First, I see you're using an explicit $.parseJSON(). If that's because you're manually serializing JSON on the server-side, don't. ASP.NET will automatically JSON-serialize your method's return value and jQuery will automatically deserialize it for you too.

To iterate through the first item in the array you've got there, use code like this:

var firstItem = response.d[0];

for(key in firstItem) {
  console.log(key + ':' + firstItem[key]);
}

If there's more than one item (it's hard to tell from that screenshot), then you can loop over response.d and then use this code inside that outer loop.

Firestore Getting documents id from collection

For angular6+

    this.shirtCollection = afs.collection<Shirt>('shirts');
    this.shirts = this.shirtCollection.snapshotChanges().pipe(
        map(actions => {
        return actions.map(a => {
            const data = a.payload.doc.data() as Shirt;
            const id = a.payload.doc.id;
            return { id, ...data };
        });
        })
    );

Trigger an action after selection select2

This worked for me (Select2 4.0.4):

$(document).on('change', 'select#your_id', function(e) {
    // your code
    console.log('this.value', this.value);
});

Outline effect to text

Multiple text-shadows..
Something like this:

var steps = 10,
    i,
    R = 0.6,
    x,
    y,
    theStyle = '1vw 1vw 3vw #005dab';
for (i = -steps; i <= steps; i += 1) {
    x = (i / steps) / 2;
    y = Math.sqrt(Math.pow(R, 2) - Math.pow(x, 2));
    theStyle = theStyle + ',' + x.toString() + 'vw ' + y.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',' + x.toString() + 'vw -' + y.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
    theStyle = theStyle + ',-' + y.toString() + 'vw ' + x.toString() + 'vw 0 #005dab';
}
document.getElementsByTagName("H1")[0].setAttribute("style", "text-shadow:" + theStyle);

Demo: http://jsfiddle.net/punosound/gv6zs58m/

How do I override nested NPM dependency versions?

I had an issue where one of the nested dependency had an npm audit vulnerability, but I still wanted to maintain the parent dependency version. the npm shrinkwrap solution didn't work for me, so what I did to override the nested dependency version:

  1. Remove the nested dependency under the 'requires' section in package-lock.json
  2. Add the updated dependency under DevDependencies in package.json, so that modules that require it will still be able to access it.
  3. npm i

How to check if the docker engine and a docker container are running?

For OS X users (Mojave 10.14.3)

Here is what i use in my Bash script to test if Docker is running or not

# Check if docker is running
if ! docker info >/dev/null 2>&1; then
    echo "Docker does not seem to be running, run it first and retry"
    exit 1
fi

changing permission for files and folder recursively using shell command in mac

You can just use the -R (recursive) flag.

chmod -R 777 /Users/Test/Desktop/PATH

How to submit a form when the return key is pressed?

Extending on the answers, this is what worked for me, maybe someone will find it useful.

Html

<form method="post" action="/url" id="editMeta">
   <textarea class="form-control" onkeypress="submitOnEnter(event)"></textarea>
</form>

Js

function submitOnEnter(e) {
  if (e.which == 13) {
    document.getElementById("editMeta").submit()
  }
}

How can I update a row in a DataTable in VB.NET?

You can access columns by index, by name and some other ways:

dtResult.Rows(i)("columnName") = strVerse

You should probably make sure your DataTable has some columns first...

Detecting an undefined object property

Introduced in ECMAScript 6, we can now deal with undefined in a new way using Proxies. It can be used to set a default value to any properties which doesn't exist so that we don't have to check each time whether it actually exists.

var handler = {
  get: function(target, name) {
    return name in target ? target[name] : 'N/A';
  }
};

var p = new Proxy({}, handler);
p.name = 'Kevin';
console.log('Name: ' +p.name, ', Age: '+p.age, ', Gender: '+p.gender)

Will output the below text without getting any undefined.

Name: Kevin , Age: N/A , Gender: N/A

Why is Github asking for username/password when following the instructions on screen and pushing a new repo?

Here is an official answer to this:

If Git prompts you for a username and password every time you try to interact with GitHub, you're probably using the HTTPS clone URL for your repository.

Using an HTTPS remote URL has some advantages: it's easier to set up than SSH, and usually works through strict firewalls and proxies. However, it also prompts you to enter your GitHub credentials every time you pull or push a repository.

You can configure Git to store your password for you. If you'd like to set that up, read all about setting up password caching.

Changing Tint / Background color of UITabBar

[v setBackgroundColor ColorwithRed: Green: Blue: ];

Do C# Timers elapse on a separate thread?

Each elapsed event will fire in the same thread unless a previous Elapsed is still running.

So it handles the collision for you

try putting this in a console

static void Main(string[] args)
{
    Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
    var timer = new Timer(1000);
    timer.Elapsed += timer_Elapsed;
    timer.Start();
    Console.ReadLine();
}

static void timer_Elapsed(object sender, ElapsedEventArgs e)
{
    Thread.Sleep(2000);
    Debug.WriteLine(Thread.CurrentThread.ManagedThreadId);
}

you will get something like this

10
6
12
6
12

where 10 is the calling thread and 6 and 12 are firing from the bg elapsed event. If you remove the Thread.Sleep(2000); you will get something like this

10
6
6
6
6

Since there are no collisions.

But this still leaves u with a problem. if u are firing the event every 5 seconds and it takes 10 seconds to edit u need some locking to skip some edits.

How to get rid of punctuation using NLTK tokenizer?

I think you need some sort of regular expression matching (the following code is in Python 3):

import string
import re
import nltk

s = "I can't do this now, because I'm so tired.  Please give me some time."
l = nltk.word_tokenize(s)
ll = [x for x in l if not re.fullmatch('[' + string.punctuation + ']+', x)]
print(l)
print(ll)

Output:

['I', 'ca', "n't", 'do', 'this', 'now', ',', 'because', 'I', "'m", 'so', 'tired', '.', 'Please', 'give', 'me', 'some', 'time', '.']
['I', 'ca', "n't", 'do', 'this', 'now', 'because', 'I', "'m", 'so', 'tired', 'Please', 'give', 'me', 'some', 'time']

Should work well in most cases since it removes punctuation while preserving tokens like "n't", which can't be obtained from regex tokenizers such as wordpunct_tokenize.

Can you get a Windows (AD) username in PHP?

We have multiple domains in our environment so I use preg_replace with regex to get just the username without DOMAIN\ .

preg_replace("/^.+\\\\/", "", $_SERVER["AUTH_USER"]);

Neatest way to remove linebreaks in Perl

Reading perlport I'd suggest something like

$line =~ s/\015?\012?$//;

to be safe for whatever platform you're on and whatever linefeed style you may be processing because what's in \r and \n may differ through different Perl flavours.

How to get the difference between two dictionaries in Python?

I think it's better to use the symmetric difference operation of sets to do that Here is the link to the doc.

>>> dict1 = {1:'donkey', 2:'chicken', 3:'dog'}
>>> dict2 = {1:'donkey', 2:'chimpansee', 4:'chicken'}
>>> set1 = set(dict1.items())
>>> set2 = set(dict2.items())
>>> set1 ^ set2
{(2, 'chimpansee'), (4, 'chicken'), (2, 'chicken'), (3, 'dog')}

It is symmetric because:

>>> set2 ^ set1
{(2, 'chimpansee'), (4, 'chicken'), (2, 'chicken'), (3, 'dog')}

This is not the case when using the difference operator.

>>> set1 - set2
{(2, 'chicken'), (3, 'dog')}
>>> set2 - set1
{(2, 'chimpansee'), (4, 'chicken')}

However it may not be a good idea to convert the resulting set to a dictionary because you may lose information:

>>> dict(set1 ^ set2)
{2: 'chicken', 3: 'dog', 4: 'chicken'}

How do I detect when someone shakes an iPhone?

From my Diceshaker application:

// Ensures the shake is strong enough on at least two axes before declaring it a shake.
// "Strong enough" means "greater than a client-supplied threshold" in G's.
static BOOL L0AccelerationIsShaking(UIAcceleration* last, UIAcceleration* current, double threshold) {
    double
        deltaX = fabs(last.x - current.x),
        deltaY = fabs(last.y - current.y),
        deltaZ = fabs(last.z - current.z);

    return
        (deltaX > threshold && deltaY > threshold) ||
        (deltaX > threshold && deltaZ > threshold) ||
        (deltaY > threshold && deltaZ > threshold);
}

@interface L0AppDelegate : NSObject <UIApplicationDelegate> {
    BOOL histeresisExcited;
    UIAcceleration* lastAcceleration;
}

@property(retain) UIAcceleration* lastAcceleration;

@end

@implementation L0AppDelegate

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    [UIAccelerometer sharedAccelerometer].delegate = self;
}

- (void) accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration {

    if (self.lastAcceleration) {
        if (!histeresisExcited && L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.7)) {
            histeresisExcited = YES;

            /* SHAKE DETECTED. DO HERE WHAT YOU WANT. */

        } else if (histeresisExcited && !L0AccelerationIsShaking(self.lastAcceleration, acceleration, 0.2)) {
            histeresisExcited = NO;
        }
    }

    self.lastAcceleration = acceleration;
}

// and proper @synthesize and -dealloc boilerplate code

@end

The histeresis prevents the shake event from triggering multiple times until the user stops the shake.

An object reference is required to access a non-static member

playSound is a static method in your class, but you are referring to members like audioSounds or minTime which are not declared static so they would require a SoundManager sm = new SoundManager(); to operate as sm.audioSounds or sm.minTime respectively

Solution:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

How can I see function arguments in IPython Notebook Server 3?

In 1.0, the functionality was bound to ( and tab and shift-tab, in 2.0 tab was deprecated but still functional in some unambiguous cases completing or inspecting were competing in many cases. Recommendation was to always use shift-Tab. ( was also added as deprecated as confusing in Haskell-like syntax to also push people toward Shift-Tab as it works in more cases. in 3.0 the deprecated bindings have been remove in favor of the official, present for 18+ month now Shift-Tab.

So press Shift-Tab.

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

Mysql service is missing

If you wish to have your config file on a different path you have to give your service a name:

mysqld --install NAME --defaults-file=C:\my-opts2.cnf

You can also use the name to install multiple mysql services listening on different sockets if you need that for some reason. You can see why it's failing by copying the execution path and adding --console to the end in the terminal. Finally, you can modify the starting path of a service by regediting:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\NAME

That works well but it isn't as useful because the windows service mechanism provides little logging capabilities.

Angular 2: import external js file into component

1) First Insert JS file path in an index.html file :

<script src="assets/video.js" type="text/javascript"></script>

2) Import JS file and declare the variable in component.ts :

  • import './../../../assets/video.js';
  • declare var RunPlayer: any;

    NOTE: Variable name should be same as the name of a function in js file

3) Call the js method in the component

ngAfterViewInit(){

    setTimeout(() => {
        new RunPlayer();
    });

}

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

I had different version of annotations jar. Changed all 3 jars to use SAME version of databind,annotations and core jackson jars

<dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
        <version>2.8.6</version>
</dependency>

Use bash to find first folder name that contains a string

You can use the -quit option of find:

find <dir> -maxdepth 1 -type d -name '*foo*' -print -quit

When increasing the size of VARCHAR column on a large table could there be any problems?

In my case alter column was not working so one can use 'Modify' command, like:

alter table [table_name] MODIFY column [column_name] varchar(1200);

Regex for remove everything after | (with | )

If you want to get everything after | excluding set character use this code.

[^|]*$

Others solutions \|.*$

Results : | mypcworld

This one [^|]*$

Results : mypcworld

http://regexr.com/3elkd

How to center an unordered list?

To center align an unordered list, you need to use the CSS text align property. In addition to this, you also need to put the unordered list inside the div element.

Now, add the style to the div class and use the text-align property with center as its value.

See the below example.

<style>
.myDivElement{
    text-align:center;
}
.myDivElement ul li{
   display:inline;

 }
</style>
<div class="myDivElement">
<ul>
    <li>Home</li>
    <li>About</li>
    <li>Gallery</li>
    <li>Contact</li>
</ul>
</div>

Here is the reference website Center Align Unordered List

Deserialize from string instead TextReader

1-liner, takes a XML string text and YourType as the expected object type. not very different from other answers, just compressed to 1 line:

var result =  (YourType)new XmlSerializer(typeof(YourType)).Deserialize(new StringReader(text));

Difference between string and StringBuilder in C#

String

A String instance is immutable, that is, we cannot change it after it was created. If we perform any operation on a String it will return a new instance (creates a new instance in memory) instead of modifying the existing instance value.

StringBuilder

StringBuilder is mutable, that is, if we perform any operation on StringBuilder it will update the existing instance value and it will not create new instance.

Difference between String and StringBuilder

Add string in a certain position in Python

I think the above answers are fine, but I would explain that there are some unexpected-but-good side effects to them...

def insert(string_s, insert_s, pos_i=0):
    return string_s[:pos_i] + insert_s + string_s[pos_i:]

If the index pos_i is very small (too negative), the insert string gets prepended. If too long, the insert string gets appended. If pos_i is between -len(string_s) and +len(string_s) - 1, the insert string gets inserted into the correct place.

How do I use cx_freeze?

I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)

  1. Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.

  2. Open the command line (Start -> Run -> "cmd")

  3. Go to the location of your setup.py file and run python setup.py build

Notes:

  1. There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.

  2. Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1

  3. Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.

Text not wrapping inside a div element

That's because there are no spaces in that long string so it has to break out of its container. Add word-break:break-all; to your .title rules to force a break.

#calendar_container > #events_container > .event_block > .title {
    width:400px;
    font-size:12px;
    word-break:break-all;
}

jsFiddle example

Detect Safari using jQuery

//Check if Safari
  function isSafari() {
      return /^((?!chrome).)*safari/i.test(navigator.userAgent);
  }
//Check if MAC
     if(navigator.userAgent.indexOf('Mac')>1){
        alert(isSafari());
     }

http://jsfiddle.net/s1o943gb/10/

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

php delete a single file in directory

<?php 
    if(isset($_GET['delete'])){
        $delurl=$_GET['delete'];
        unlink($delurl);
    }
?>
<?php
if ($handle = opendir('.')) {
    while (false !== ($entry = readdir($handle))) {
        if ($entry != "." && $entry != "..") {
            echo "<a href=\"$entry\">$entry</a> | <a href=\"?delete=$entry\">Delete</a><br>";
        }
    }
    closedir($handle);
}
?>

This is It

How does numpy.newaxis work and when to use it?

Simply put, numpy.newaxis is used to increase the dimension of the existing array by one more dimension, when used once. Thus,

  • 1D array will become 2D array

  • 2D array will become 3D array

  • 3D array will become 4D array

  • 4D array will become 5D array

and so on..

Here is a visual illustration which depicts promotion of 1D array to 2D arrays.

newaxis canva visualization


Scenario-1: np.newaxis might come in handy when you want to explicitly convert a 1D array to either a row vector or a column vector, as depicted in the above picture.

Example:

# 1D array
In [7]: arr = np.arange(4)
In [8]: arr.shape
Out[8]: (4,)

# make it as row vector by inserting an axis along first dimension
In [9]: row_vec = arr[np.newaxis, :]     # arr[None, :]
In [10]: row_vec.shape
Out[10]: (1, 4)

# make it as column vector by inserting an axis along second dimension
In [11]: col_vec = arr[:, np.newaxis]     # arr[:, None]
In [12]: col_vec.shape
Out[12]: (4, 1)

Scenario-2: When we want to make use of numpy broadcasting as part of some operation, for instance while doing addition of some arrays.

Example:

Let's say you want to add the following two arrays:

 x1 = np.array([1, 2, 3, 4, 5])
 x2 = np.array([5, 4, 3])

If you try to add these just like that, NumPy will raise the following ValueError :

ValueError: operands could not be broadcast together with shapes (5,) (3,)

In this situation, you can use np.newaxis to increase the dimension of one of the arrays so that NumPy can broadcast.

In [2]: x1_new = x1[:, np.newaxis]    # x1[:, None]
# now, the shape of x1_new is (5, 1)
# array([[1],
#        [2],
#        [3],
#        [4],
#        [5]])

Now, add:

In [3]: x1_new + x2
Out[3]:
array([[ 6,  5,  4],
       [ 7,  6,  5],
       [ 8,  7,  6],
       [ 9,  8,  7],
       [10,  9,  8]])

Alternatively, you can also add new axis to the array x2:

In [6]: x2_new = x2[:, np.newaxis]    # x2[:, None]
In [7]: x2_new     # shape is (3, 1)
Out[7]: 
array([[5],
       [4],
       [3]])

Now, add:

In [8]: x1 + x2_new
Out[8]: 
array([[ 6,  7,  8,  9, 10],
       [ 5,  6,  7,  8,  9],
       [ 4,  5,  6,  7,  8]])

Note: Observe that we get the same result in both cases (but one being the transpose of the other).


Scenario-3: This is similar to scenario-1. But, you can use np.newaxis more than once to promote the array to higher dimensions. Such an operation is sometimes needed for higher order arrays (i.e. Tensors).

Example:

In [124]: arr = np.arange(5*5).reshape(5,5)

In [125]: arr.shape
Out[125]: (5, 5)

# promoting 2D array to a 5D array
In [126]: arr_5D = arr[np.newaxis, ..., np.newaxis, np.newaxis]    # arr[None, ..., None, None]

In [127]: arr_5D.shape
Out[127]: (1, 5, 5, 1, 1)

As an alternative, you can use numpy.expand_dims that has an intuitive axis kwarg.

# adding new axes at 1st, 4th, and last dimension of the resulting array
In [131]: newaxes = (0, 3, -1)
In [132]: arr_5D = np.expand_dims(arr, axis=newaxes)
In [133]: arr_5D.shape
Out[133]: (1, 5, 5, 1, 1)

More background on np.newaxis vs np.reshape

newaxis is also called as a pseudo-index that allows the temporary addition of an axis into a multiarray.

np.newaxis uses the slicing operator to recreate the array while numpy.reshape reshapes the array to the desired layout (assuming that the dimensions match; And this is must for a reshape to happen).

Example

In [13]: A = np.ones((3,4,5,6))
In [14]: B = np.ones((4,6))
In [15]: (A + B[:, np.newaxis, :]).shape     # B[:, None, :]
Out[15]: (3, 4, 5, 6)

In the above example, we inserted a temporary axis between the first and second axes of B (to use broadcasting). A missing axis is filled-in here using np.newaxis to make the broadcasting operation work.


General Tip: You can also use None in place of np.newaxis; These are in fact the same objects.

In [13]: np.newaxis is None
Out[13]: True

P.S. Also see this great answer: newaxis vs reshape to add dimensions

How do I get the height and width of the Android Navigation Bar programmatically?

This is my code to add paddingRight and paddingBottom to a View to dodge the Navigation Bar. I combined some of the answers here and made a special clause for landscape orientation together with isInMultiWindowMode. The key is to read navigation_bar_height, but also check config_showNavigationBar to make sure we should actually use the height.

None of the previous solutions worked for me. As of Android 7.0 you have to take Multi Window Mode into consideration. This breaks the implementations comparing display.realSize with display.size since realSize gives you the dimensions of the whole screen (both split windows) and size only gives you the dimensions of your App window. Setting padding to this difference will leave your whole view being padding.

/** Adds padding to a view to dodge the navigation bar.

    Unfortunately something like this needs to be done since there
    are no attr or dimens value available to get the navigation bar
    height (as of December 2016). */
public static void addNavigationBarPadding(Activity context, View v) {
    Resources resources = context.getResources();
    if (hasNavigationBar(resources)) {
        int orientation = resources.getConfiguration().orientation;
        int size = getNavigationBarSize(resources);
        switch (orientation) {
        case Configuration.ORIENTATION_LANDSCAPE:
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N &&
                context.isInMultiWindowMode()) { break; }
            v.setPadding(v.getPaddingLeft(), v.getPaddingTop(),
                         v.getPaddingRight() + size, v.getPaddingBottom());
            break;
        case Configuration.ORIENTATION_PORTRAIT:
            v.setPadding(v.getPaddingLeft(), v.getPaddingTop(),
                         v.getPaddingRight(), v.getPaddingBottom() + size);
            break;
        }
    }
}

private static int getNavigationBarSize(Resources resources) {
    int resourceId = resources.getIdentifier("navigation_bar_height",
                                             "dimen", "android");
    return resourceId > 0 ? resources.getDimensionPixelSize(resourceId) : 0;
}

private static boolean hasNavigationBar(Resources resources) {
    int hasNavBarId = resources.getIdentifier("config_showNavigationBar",
                                              "bool", "android");
    return hasNavBarId > 0 && resources.getBoolean(hasNavBarId);
}

HTML Text with tags to formatted text in an Excel cell

Nice! Very slick.

I was disappointed that Excel doesn't let us paste to a merged cell and also pastes results containing a break into successive rows below the "target" cell though, as that meant it simply doesn't work for me. I tried a few tweaks (unmerge/remerge, etc.) but then Excel dropped anything below a break, so that was a dead end.

Ultimately, I came up with a routine that'll handle simple tags and not use the "native" Unicode converter that is causing the issue with merged fields. Hope others find this useful:

Public Sub AddHTMLFormattedText(rngA As Range, strHTML As String, Optional blnShowBadHTMLWarning As Boolean = False)
    ' Adds converts text formatted with basic HTML tags to formatted text in an Excel cell
    ' NOTE: Font Sizes not handled perfectly per HTML standard, but I find this method more useful!

    Dim strActualText As String, intSrcPos As Integer, intDestPos As Integer, intDestSrcEquiv() As Integer
    Dim varyTags As Variant, varTag As Variant, varEndTag As Variant, blnTagMatch As Boolean
    Dim intCtr As Integer
    Dim intStartPos As Integer, intEndPos As Integer, intActualStartPos As Integer, intActualEndPos As Integer
    Dim intFontSizeStartPos As Integer, intFontSizeEndPos As Integer, intFontSize As Integer

    varyTags = Array("<b>", "</b>", "<i>", "</i>", "<u>", "</u>", "<sub>", "</sub>", "<sup>", "</sup>")

    ' Remove unhandled/unneeded tags, convert <br> and <p> tags to line feeds
    strHTML = Trim(strHTML)
    strHTML = Replace(strHTML, "<html>", "")
    strHTML = Replace(strHTML, "</html>", "")
    strHTML = Replace(strHTML, "<p>", "")
    While LCase(Right$(strHTML, 4)) = "</p>" Or LCase(Right$(strHTML, 4)) = "<br>"
        strHTML = Left$(strHTML, Len(strHTML) - 4)
        strHTML = Trim(strHTML)
    Wend
    strHTML = Replace(strHTML, "<br>", vbLf)
    strHTML = Replace(strHTML, "</p>", vbLf)

    strHTML = Trim(strHTML)

    ReDim intDestSrcEquiv(1 To Len(strHTML))
    strActualText = ""
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        blnTagMatch = False
        For Each varTag In varyTags
            If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                blnTagMatch = True
                intSrcPos = intSrcPos + Len(varTag)
                If intSrcPos > Len(strHTML) Then Exit Do
                Exit For
            End If
        Next
        If blnTagMatch = False Then
            varTag = "<font size"
            If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                blnTagMatch = True
                intEndPos = InStr(intSrcPos, strHTML, ">")
                intSrcPos = intEndPos + 1
                If intSrcPos > Len(strHTML) Then Exit Do
            Else
                varTag = "</font>"
                If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                    blnTagMatch = True
                    intSrcPos = intSrcPos + Len(varTag)
                    If intSrcPos > Len(strHTML) Then Exit Do
                End If
            End If
        End If
        If blnTagMatch = False Then
            strActualText = strActualText & Mid$(strHTML, intSrcPos, 1)
            intDestSrcEquiv(intSrcPos) = intDestPos
            intDestPos = intDestPos + 1
            intSrcPos = intSrcPos + 1
        End If
    Loop

    ' Clear any bold/underline/italic/superscript/subscript formatting from cell
    rngA.Font.Bold = False
    rngA.Font.Underline = False
    rngA.Font.Italic = False
    rngA.Font.Subscript = False
    rngA.Font.Superscript = False

    rngA.Value = strActualText

    ' Now start applying Formats!"
    ' Start with Font Size first
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        varTag = "<font size"
        If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
            intFontSizeStartPos = InStr(intSrcPos, strHTML, """") + 1
            intFontSizeEndPos = InStr(intFontSizeStartPos, strHTML, """") - 1
            If intFontSizeEndPos - intFontSizeStartPos <= 3 And intFontSizeEndPos - intFontSizeStartPos > 0 Then
                Debug.Print Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                If Mid$(strHTML, intFontSizeStartPos, 1) = "+" Then
                    intFontSizeStartPos = intFontSizeStartPos + 1
                    intFontSize = 11 + 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                ElseIf Mid$(strHTML, intFontSizeStartPos, 1) = "-" Then
                    intFontSizeStartPos = intFontSizeStartPos + 1
                    intFontSize = 11 - 2 * Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                Else
                    intFontSize = Mid$(strHTML, intFontSizeStartPos, intFontSizeEndPos - intFontSizeStartPos + 1)
                End If
            Else
                ' Error!
                GoTo HTML_Err
            End If
            intEndPos = InStr(intSrcPos, strHTML, ">")
            intSrcPos = intEndPos + 1
            intStartPos = intSrcPos
            If intSrcPos > Len(strHTML) Then Exit Do
            While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
                intStartPos = intStartPos + 1
            Wend
            If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
            varEndTag = "</font>"
            intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
            If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
            While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
                intEndPos = intEndPos - 1
            Wend
            If intEndPos > intSrcPos Then
                intActualStartPos = intDestSrcEquiv(intStartPos)
                intActualEndPos = intDestSrcEquiv(intEndPos)
                rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1) _
                    .Font.Size = intFontSize
            End If
        End If
        intSrcPos = intSrcPos + 1
    Loop

    'Now do remaining tags
    intSrcPos = 1
    intDestPos = 1
    Do While intSrcPos <= Len(strHTML)
        If intDestSrcEquiv(intSrcPos) = 0 Then
            ' This must be a Tag!
            For intCtr = 0 To UBound(varyTags) Step 2
                varTag = varyTags(intCtr)
                intStartPos = intSrcPos + Len(varTag)
                While intDestSrcEquiv(intStartPos) = 0 And intStartPos < Len(strHTML)
                    intStartPos = intStartPos + 1
                Wend
                If intStartPos >= Len(strHTML) Then GoTo HTML_Err ' HTML is bad!
                If LCase(Mid$(strHTML, intSrcPos, Len(varTag))) = varTag Then
                    varEndTag = varyTags(intCtr + 1)
                    intEndPos = InStr(intSrcPos, LCase(strHTML), varEndTag)
                    If intEndPos = 0 Then GoTo HTML_Err ' HTML is bad!
                    While intDestSrcEquiv(intEndPos) = 0 And intEndPos > intSrcPos
                        intEndPos = intEndPos - 1
                    Wend
                    If intEndPos > intSrcPos Then
                        intActualStartPos = intDestSrcEquiv(intStartPos)
                        intActualEndPos = intDestSrcEquiv(intEndPos)
                        With rngA.Characters(intActualStartPos, intActualEndPos - intActualStartPos + 1).Font
                            If varTag = "<b>" Then
                                .Bold = True
                            ElseIf varTag = "<i>" Then
                                .Italic = True
                            ElseIf varTag = "<u>" Then
                                .Underline = True
                            ElseIf varTag = "<sup>" Then
                                .Superscript = True
                            ElseIf varTag = "<sub>" Then
                                .Subscript = True
                            End If
                        End With
                    End If
                    intSrcPos = intSrcPos + Len(varTag) - 1
                    Exit For
                End If
            Next
        End If
        intSrcPos = intSrcPos + 1
        intDestPos = intDestPos + 1
    Loop
Exit_Sub:
    Exit Sub
HTML_Err:
    ' There was an error with the Tags. Show warning if requested.
    If blnShowBadHTMLWarning Then
        MsgBox "There was an error with the Tags in the HTML file. Could not apply formatting."
    End If
End Sub

Note this doesn't care about tag nesting, instead only requiring a close tag for every open tag, and assuming the close tag nearest the opening tag applies to the opening tag. Properly nested tags will work fine, while improperly nested tags will not be rejected and may or may not work.

JTable - Selected Row click event

I would recommend using Glazed Lists for this. It makes it very easy to map a data structure to a table model.

To react to the mouseclick on the JTable, use an ActionListener: ActionListener on JLabel or JTable cell

How to parse a JSON Input stream

{
    InputStream is = HTTPClient.get(url);
    InputStreamReader reader = new InputStreamReader(is);
    JSONTokener tokenizer = new JSONTokener(reader);
    JSONObject jsonObject = new JSONObject(tokenizer);
}

How to create a jar with external libraries included in Eclipse?

If it is a standalone (Main method) java project then Not any specific path put all the jars inside the project not any specific path then right click on the project - > export - > Runnable jar --> Select the lunch configuration and Library handeling then choose the radio button option "Package required libraries into generated jar" -- > Finish.

Or

If you have a web project then put all the jars in web-inf/lib folder and do the same step.

Is it possible to specify the schema when connecting to postgres with JDBC?

Don't forget SET SCHEMA 'myschema' which you could use in a separate Statement

SET SCHEMA 'value' is an alias for SET search_path TO value. Only one schema can be specified using this syntax.

And since 9.4 and possibly earlier versions on the JDBC driver, there is support for the setSchema(String schemaName) method.

unable to install pg gem

Regardless of what OS you are running, look at the logs file of the "Makefile" to see what is going on, instead of blindly installing stuff.

In my case, MAC OS, the log file is here:

/Users/za/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-15/2.3.0-static/pg-1.0.0/mkmf.log

The logs indicated that the make file could not be created because of the following:

Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers

Inside the mkmf.log, you will see that it could not find required libraries, to finish the build.

checking for pg_config... no
Can't find the 'libpq-fe.h header
blah blah

After running "brew install postgresql", I can see all required libraries being there:

za:myapp za$ cat /Users/za/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/extensions/x86_64-darwin-15/2.3.0-static/pg-1.0.0/mkmf.log | grep yes
find_executable: checking for pg_config... -------------------- yes
find_header: checking for libpq-fe.h... -------------------- yes
find_header: checking for libpq/libpq-fs.h... -------------------- yes
find_header: checking for pg_config_manual.h... -------------------- yes
have_library: checking for PQconnectdb() in -lpq... -------------------- yes
have_func: checking for PQsetSingleRowMode()... -------------------- yes
have_func: checking for PQconninfo()... -------------------- yes
have_func: checking for PQsslAttribute()... -------------------- yes
have_func: checking for PQencryptPasswordConn()... -------------------- yes
have_const: checking for PG_DIAG_TABLE_NAME in libpq-fe.h... -------------------- yes
have_header: checking for unistd.h... -------------------- yes
have_header: checking for inttypes.h... -------------------- yes
checking for C99 variable length arrays... -------------------- yes

How to set my default shell on Mac?

You can use chsh to change a user's shell.

Run the following code, for instance, to change your shell to Zsh

chsh -s /bin/zsh

As described in the manpage, and by Lorin, if the shell is not known by the OS, you have to add it to its known list: /etc/shells.

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

If anyone experiences the error for the same reason why I experience it, here's my solution:

if you had Html.AntiForgeryToken();

change it to @Html.AntiForgeryToken()

Dots in URL causes 404 with ASP.NET mvc and IIS

I believe you have to set the property relaxedUrlToFileSystemMapping in your web.config. Haack wrote an article about this a little while ago (and there are some other SO posts asking the same types of question)

<system.web>
<httpRuntime relaxedUrlToFileSystemMapping="true" />

Edit From the comments below, later versions of .NET / IIS may require this to be in the system.WebServer element.

<system.webServer>
<httpRuntime relaxedUrlToFileSystemMapping="true" />

Space between two rows in a table?

The correct way to give spacing for tables is to use cellpadding and cellspacing e.g.

<table cellpadding="4">

Compiling dynamic HTML strings from database

In angular 1.2.10 the line scope.$watch(attrs.dynamic, function(html) { was returning an invalid character error because it was trying to watch the value of attrs.dynamic which was html text.

I fixed that by fetching the attribute from the scope property

 scope: { dynamic: '=dynamic'}, 

My example

angular.module('app')
  .directive('dynamic', function ($compile) {
    return {
      restrict: 'A',
      replace: true,
      scope: { dynamic: '=dynamic'},
      link: function postLink(scope, element, attrs) {
        scope.$watch( 'dynamic' , function(html){
          element.html(html);
          $compile(element.contents())(scope);
        });
      }
    };
  });

JavaScript OR (||) variable assignment explanation

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.

count number of characters in nvarchar column

Use the LEN function:

Returns the number of characters of the specified string expression, excluding trailing blanks.

ASP.NET MVC How to pass JSON object from View to Controller as Parameter

There is the JavaScriptSerializer class you can use too. That will let you deserialize the json to a .NET object. There's a generic Deserialize<T>, though you will need the .NET object to have a similar signature as the javascript one. Additionally there is also a DeserializeObject method that just makes a plain object. You can then use reflection to get at the properties you need.

If your controller takes a FormCollection, and you didn't add anything else to the data the json should be in form[0]:

public ActionResult Save(FormCollection forms) {
  string json = forms[0];
  // do your thing here.
}

How to check if "Radiobutton" is checked?

Check if they're checked with the el.checked attribute.

Docs or this Question

_x000D_
_x000D_
let radio1 = document.querySelector('.radio1');
let radio2 = document.querySelector('.radio2');
let output = document.querySelector('.output');

function update() {
  if (radio1.checked) {
    output.innerHTML = "radio1";
  }
  else {
    output.innerHTML = "radio2";
  }
}

update();
_x000D_
<div class="radios">
  <input class="radio1" type="radio" name="radios" onchange="update()" checked>
  <input class="radio2" type="radio" name="radios" onchange="update()">
</div>
<div class="output"></div>
_x000D_
_x000D_
_x000D_

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

How to install latest version of git on CentOS 7.x/6.x

Rackspace maintains the ius repository, which contains a reasonably up-to-date git, but the stock git has to first be removed.

CentOS 6 or 7 instructions (run as root or with sudo):

# retrieve and check CENTOS_MAIN_VERSION (6 or 7):
CENTOS_MAIN_VERSION=$(cat /etc/centos-release | awk -F 'release[ ]*' '{print $2}' | awk -F '.' '{print $1}')
echo $CENTOS_MAIN_VERSION
# output should be "6" or "7"

# Install IUS Repo and Epel-Release:
yum install -y https://repo.ius.io/ius-release-el${CENTOS_MAIN_VERSION}.rpm
yum install -y epel-release 

# re-install git:
yum erase -y git*
yum install -y git-core

# check version:
git --version
# output: git version 2.24.3

Note: git-all instead of git-core often installs an old version. Try e.g. git224-all instead.

The script is tested on a CentOS 7 docker image (7e6257c9f8d8) and on a CentOS 6 docker image (d0957ffdf8a2).

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

Skip download if files exist in wget?

Try the following parameter:

-nc, --no-clobber: skip downloads that would download to existing files.

Sample usage:

wget -nc http://example.com/pic.png

Git: How to remove file from index without deleting files from any repository

Had the very same issue this week when I accidentally committed, then tried to remove a build file from a shared repository, and this:

http://gitready.com/intermediate/2009/02/18/temporarily-ignoring-files.html

has worked fine for me and not mentioned so far.

git update-index --assume-unchanged <file>

To remove the file you're interested in from version control, then use all your other commands as normal.

git update-index --no-assume-unchanged <file>

If you ever wanted to put it back in.

Edit: please see comments from Chris Johnsen and KPM, this only works locally and the file remains under version control for other users if they don't also do it. The accepted answer gives more complete/correct methods for dealing with this. Also some notes from the link if using this method:

Obviously there’s quite a few caveats that come into play with this. If you git add the file directly, it will be added to the index. Merging a commit with this flag on will cause the merge to fail gracefully so you can handle it manually.

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

Countdown timer using Moment js

In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.

var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;

setInterval(function(){
  duration = moment.duration(duration - interval, 'milliseconds');
    $('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);

css transition opacity fade background

Wrap your image with a span element with a black background.

_x000D_
_x000D_
.img-wrapper {
  display: inline-block;
  background: #000;
}

.item-fade {
  vertical-align: top;
  transition: opacity 0.3s;
  -webkit-transition: opacity 0.3s;
  opacity: 1;
}

.item-fade:hover {
  opacity: 0.2;
}
_x000D_
<span class="img-wrapper">
   <img class="item-fade" src="http://placehold.it/100x100/cf5" />
</span>
_x000D_
_x000D_
_x000D_

converting a javascript string to a html object

You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..

string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call

but still, it would not be found by the getElementById because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.

You would need to use append or appendTo or after etc.. to put it in the dom first..

Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..

Delete all items from a c++ std::vector

If you keep pointers in container and don't want to bother with manually destroying of them, then use boost shared_ptr. Here is sample for std::vector, but you can use it for any other STL container (set, map, queue, ...)

#include <iostream>
#include <vector>
#include <boost/shared_ptr.hpp>

struct foo
{
    foo( const int i_x ) : d_x( i_x )
    {
        std::cout << "foo::foo " << d_x << std::endl;
    }

    ~foo()
    {
        std::cout << "foo::~foo " << d_x << std::endl;
    }

    int d_x;
};

typedef boost::shared_ptr< foo > smart_foo_t;

int main()
{
    std::vector< smart_foo_t > foos;
    for ( int i = 0; i < 10; ++i )
    {
        smart_foo_t f( new foo( i ) );
        foos.push_back( f );
    }

    foos.clear();

    return 0;
}

How to localise a string inside the iOS info.plist file?

In my case everything was set up correctly but still the InfoPlist.strings file was not found.

The only thing that really worked was, to remove and add the InfoPlist.strings files again to the project.

How to initialize List<String> object in Java?

List is an interface, and you can not initialize an interface. Instantiate an implementing class instead.

Like:

List<String> abc = new ArrayList<String>();
List<String> xyz = new LinkedList<String>();

Decode Hex String in Python 3

Something like:

>>> bytes.fromhex('4a4b4c').decode('utf-8')
'JKL'

Just put the actual encoding you are using.

Problems after upgrading to Xcode 10: Build input file cannot be found

I had a similar issue after upgrading to a new swift version recently. Moving files around caused my xcode project to reference items that were no longer in the project directory giving me the Error Code Build Input File Not Found.

In my situation I somehow had multiple files/images that were being referenced as described below:enter image description here

In the image above.

  • Navigate to your Targets page.
  • Then Click on the Build Phases tab on the top.
  • Scroll Down to Copy Bundle Resources
  • Find the affected files and remove them. (hit delete on them or select them and hit the minus button )

It was in here that I somehow had multiple files and images that were being referenced from other folders and the build would fail as they could no longer find them. And I could not find them either! or how Xcode was still referencing them

I hope this helps someone else !

Using lambda expressions for event handlers

Performance-wise it's the same as a named method. The big problem is when you do the following:

MyButton.Click -= (o, i) => 
{ 
    //snip 
} 

It will probably try to remove a different lambda, leaving the original one there. So the lesson is that it's fine unless you also want to be able to remove the handler.

Rounding numbers to 2 digits after comma

This worked for me:

var new_number = float.toFixed(2);

Example:

var my_float = 0.6666

my_float.toFixed(3) # => 0.667

jQuery and TinyMCE: textarea value doesn't submit

I just hide() the tinymce and submit form, the changed value of textarea missing. So I added this:

$("textarea[id='id_answer']").change(function(){
    var editor_id = $(this).attr('id');
    var editor = tinymce.get(editor_id);
    editor.setContent($(this).val()).save();
});

It works for me.

Directly export a query to CSV using SQL Developer

After Ctrl+End, you can do the Ctrl+A to select all in the buffer and then paste into Excel. Excel even put each Oracle column into its own column instead of squishing the whole row into one column. Nice..

Remove All Event Listeners of Specific Type

Remove all listeners in element by one js line:

element.parentNode.innerHTML += '';

Firefox Add-on RESTclient - How to input POST parameters?

Request header needs to be set as per below image.add request header

request body can be passed as json string in text area. enter image description here

How to use PowerShell select-string to find more than one pattern in a file?

You can specify multiple patterns in an array.

select-string VendorEnquiry,Failed C:\Logs

This works with -notmatch as well:

select-string -notmatch VendorEnquiry,Failed C:\Logs

How to convert unsigned long to string

For a long value you need to add the length info 'l' and 'u' for unsigned decimal integer,

as a reference of available options see sprintf

#include <stdio.h>

    int main ()
    {
      unsigned long lval = 123;
      char buffer [50];
      sprintf (buffer, "%lu" , lval );
     }

throw checked Exceptions from mocks with Mockito

There is the solution with Kotlin :

given(myObject.myCall()).willAnswer {
    throw IOException("Ooops")
}

Where given comes from

import org.mockito.BDDMockito.given

Using ALTER to drop a column if it exists in MySQL

Perhaps the simplest way to solve this (that will work) is:

  • CREATE new_table AS SELECT id, col1, col2, ... (only the columns you actually want in the final table) FROM my_table;

  • RENAME my_table TO old_table, new_table TO my_table;

  • DROP old_table;

Or keep old_table for a rollback if needed.

This will work but foreign keys will not be moved. You would have to re-add them to my_table later; also foreign keys in other tables that reference my_table will have to be fixed (pointed to the new my_table).

Good Luck...

How to reset a select element with jQuery

$('#baba').prop('selectedIndex',-1);

How to register multiple implementations of the same interface in Asp.Net Core?

While it seems @Miguel A. Arilla has pointed it out clearly and I voted up for him, I created on top of his useful solution another solution which looks neat but requires a lot more work.

It definitely depends on the above solution. So basically I created something similar to Func<string, IService>> and I called it IServiceAccessor as an interface and then I had to add a some more extensions to the IServiceCollection as such:

public static IServiceCollection AddSingleton<TService, TImplementation, TServiceAccessor>(
            this IServiceCollection services,
            string instanceName
        )
            where TService : class
            where TImplementation : class, TService
            where TServiceAccessor : class, IServiceAccessor<TService>
        {
            services.AddSingleton<TService, TImplementation>();
            services.AddSingleton<TServiceAccessor>();
            var provider = services.BuildServiceProvider();
            var implementationInstance = provider.GetServices<TService>().Last();
            var accessor = provider.GetServices<TServiceAccessor>().First();

            var serviceDescriptors = services.Where(d => d.ServiceType == typeof(TServiceAccessor));
            while (serviceDescriptors.Any())
            {
                services.Remove(serviceDescriptors.First());
            }

            accessor.SetService(implementationInstance, instanceName);
            services.AddSingleton<TServiceAccessor>(prvd => accessor);
            return services;
        }

The service Accessor looks like:

 public interface IServiceAccessor<TService>
    {
         void Register(TService service,string name);
         TService Resolve(string name);

    }

The end result,you will be able to register services with names or named instances like we used to do with other containers..for instance:

    services.AddSingleton<IEncryptionService, SymmetricEncryptionService, EncyptionServiceAccessor>("Symmetric");
    services.AddSingleton<IEncryptionService, AsymmetricEncryptionService, EncyptionServiceAccessor>("Asymmetric");

That is enough for now, but to make your work complete, it is better to add more extension methods as you can to cover all types of registrations following the same approach.

There was another post on stackoverflow, but I can not find it, where the poster has explained in details why this feature is not supported and how to work around it, basically similar to what @Miguel stated. It was nice post even though I do not agree with each point because I think there are situation where you really need named instances. I will post that link here once I find it again.

As a matter of fact, you do not need to pass that Selector or Accessor:

I am using the following code in my project and it worked well so far.

 /// <summary>
    /// Adds the singleton.
    /// </summary>
    /// <typeparam name="TService">The type of the t service.</typeparam>
    /// <typeparam name="TImplementation">The type of the t implementation.</typeparam>
    /// <param name="services">The services.</param>
    /// <param name="instanceName">Name of the instance.</param>
    /// <returns>IServiceCollection.</returns>
    public static IServiceCollection AddSingleton<TService, TImplementation>(
        this IServiceCollection services,
        string instanceName
    )
        where TService : class
        where TImplementation : class, TService
    {
        var provider = services.BuildServiceProvider();
        var implementationInstance = provider.GetServices<TService>().LastOrDefault();
        if (implementationInstance.IsNull())
        {
            services.AddSingleton<TService, TImplementation>();
            provider = services.BuildServiceProvider();
            implementationInstance = provider.GetServices<TService>().Single();
        }
        return services.RegisterInternal(instanceName, provider, implementationInstance);
    }

    private static IServiceCollection RegisterInternal<TService>(this IServiceCollection services,
        string instanceName, ServiceProvider provider, TService implementationInstance)
        where TService : class
    {
        var accessor = provider.GetServices<IServiceAccessor<TService>>().LastOrDefault();
        if (accessor.IsNull())
        {
            services.AddSingleton<ServiceAccessor<TService>>();
            provider = services.BuildServiceProvider();
            accessor = provider.GetServices<ServiceAccessor<TService>>().Single();
        }
        else
        {
            var serviceDescriptors = services.Where(d => d.ServiceType == typeof(IServiceAccessor<TService>));
            while (serviceDescriptors.Any())
            {
                services.Remove(serviceDescriptors.First());
            }
        }
        accessor.Register(implementationInstance, instanceName);
        services.AddSingleton<TService>(prvd => implementationInstance);
        services.AddSingleton<IServiceAccessor<TService>>(prvd => accessor);
        return services;
    }

    //
    // Summary:
    //     Adds a singleton service of the type specified in TService with an instance specified
    //     in implementationInstance to the specified Microsoft.Extensions.DependencyInjection.IServiceCollection.
    //
    // Parameters:
    //   services:
    //     The Microsoft.Extensions.DependencyInjection.IServiceCollection to add the service
    //     to.
    //   implementationInstance:
    //     The instance of the service.
    //   instanceName:
    //     The name of the instance.
    //
    // Returns:
    //     A reference to this instance after the operation has completed.
    public static IServiceCollection AddSingleton<TService>(
        this IServiceCollection services,
        TService implementationInstance,
        string instanceName) where TService : class
    {
        var provider = services.BuildServiceProvider();
        return RegisterInternal(services, instanceName, provider, implementationInstance);
    }

    /// <summary>
    /// Registers an interface for a class
    /// </summary>
    /// <typeparam name="TInterface">The type of the t interface.</typeparam>
    /// <param name="services">The services.</param>
    /// <returns>IServiceCollection.</returns>
    public static IServiceCollection As<TInterface>(this IServiceCollection services)
         where TInterface : class
    {
        var descriptor = services.Where(d => d.ServiceType.GetInterface(typeof(TInterface).Name) != null).FirstOrDefault();
        if (descriptor.IsNotNull())
        {
            var provider = services.BuildServiceProvider();
            var implementationInstance = (TInterface)provider?.GetServices(descriptor?.ServiceType)?.Last();
            services?.AddSingleton(implementationInstance);
        }
        return services;
    }

How to solve error "Missing `secret_key_base` for 'production' environment" (Rails 4.1)

You can export the secret keys to as environment variables on the ~/.bashrc or ~/.bash_profile of your server:

export SECRET_KEY_BASE = "YOUR_SECRET_KEY"

And then, you can source your .bashrc or .bash_profile:

source ~/.bashrc 
source ~/.bash_profile

Never commit your secrets.yml

SELECT * FROM multiple tables. MySQL

In order to get rid of duplicates, you can group by drinks.id. But that way you'll get only one photo for each drinks.id (which photo you'll get depends on database internal implementation).

Though it is not documented, in case of MySQL, you'll get the photo with lowest id (in my experience I've never seen other behavior).

SELECT name, price, photo 
FROM drinks, drinks_photos 
WHERE drinks.id = drinks_id
GROUP BY drinks.id

error: Your local changes to the following files would be overwritten by checkout

You can commit in the current branch, checkout to another branch, and finally cherry-pick that commit (in lieu of merge).

PHP: How to get referrer URL?

If $_SERVER['HTTP_REFERER'] variable doesn't seems to work, then you can either use Google Analytics or AddThis Analytics.

How to resolve 'npm should be run outside of the node repl, in your normal shell'

It's better to use the actual (msi) installer from nodejs.org instead of downloading the node executable only. The installer includes npm and makes it easier to manage your node installation. There is an installer for both 32-bit and 64-bit Windows.

Also a couple of other tidbits:

  • Installing modules globally doesn't do what you might expect. The only modules you should install globally (the -g flag in npm) are ones that install commands. So to install Express you would just do npm install express and that will install Express to your current working directory. If you were instead looking for the Express project generator (command), you need to do npm install -g express-generator for Express 4.

  • You can use node anywhere from your command prompt to execute scripts. For example if you have already written a separate script: node foo.js. Or you can open up the REPL (as you've already found out) by just selecting the node.js (start menu) shortcut or by just typing node in a command prompt.

Regular Expression to match string starting with a specific word

I'd advise against a simple regular expression approach to this problem. There are too many words that are substrings of other unrelated words, and you'll probably drive yourself crazy trying to overadapt the simpler solutions already provided.

You'll want at least a naive stemming algorithm (try the Porter stemmer; there's available, free code in most languages) to process text first. Keep this processed text and the preprocessed text in two separate space-split arrays. Make sure each non-alphabetical character also gets its own index in this array. Whatever list of words you're filtering, stem them also.

The next step would be to find the array indices which match to your list of stemmed 'stop' words. Remove those from the unprocessed array, and then rejoin on spaces.

This is only slightly more complicated, but will be much more reliable an approach. If you've got any doubts on the value of a more NLP-oriented approach, you might want to do some research into clbuttic mistakes.

Finding an elements XPath using IE Developer tool

You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder

The only restrictions/limitations:

  1. The browser should be started from the tool
  2. Internet Explorer Driver Server - IEDriverServer.exe - should be downloaded separately and placed near SwdPageRecorder.exe

How to run a method every X seconds

Use Timer for every second...

new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        //your method
    }
}, 0, 1000);//put here time 1000 milliseconds=1 second

Awaiting multiple Tasks with different results

Given three tasks - FeedCat(), SellHouse() and BuyCar(), there are two interesting cases: either they all complete synchronously (for some reason, perhaps caching or an error), or they don't.

Let's say we have, from the question:

Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();
    // what here?
}

Now, a simple approach would be:

Task.WhenAll(x, y, z);

but ... that isn't convenient for processing the results; we'd typically want to await that:

async Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    await Task.WhenAll(x, y, z);
    // presumably we want to do something with the results...
    return DoWhatever(x.Result, y.Result, z.Result);
}

but this does lots of overhead and allocates various arrays (including the params Task[] array) and lists (internally). It works, but it isn't great IMO. In many ways it is simpler to use an async operation and just await each in turn:

async Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    // do something with the results...
    return DoWhatever(await x, await y, await z);
}

Contrary to some of the comments above, using await instead of Task.WhenAll makes no difference to how the tasks run (concurrently, sequentially, etc). At the highest level, Task.WhenAll predates good compiler support for async/await, and was useful when those things didn't exist. It is also useful when you have an arbitrary array of tasks, rather than 3 discreet tasks.

But: we still have the problem that async/await generates a lot of compiler noise for the continuation. If it is likely that the tasks might actually complete synchronously, then we can optimize this by building in a synchronous path with an asynchronous fallback:

Task<string> DoTheThings() {
    Task<Cat> x = FeedCat();
    Task<House> y = SellHouse();
    Task<Tesla> z = BuyCar();

    if(x.Status == TaskStatus.RanToCompletion &&
       y.Status == TaskStatus.RanToCompletion &&
       z.Status == TaskStatus.RanToCompletion)
        return Task.FromResult(
          DoWhatever(a.Result, b.Result, c.Result));
       // we can safely access .Result, as they are known
       // to be ran-to-completion

    return Awaited(x, y, z);
}

async Task Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
    return DoWhatever(await x, await y, await z);
}

This "sync path with async fallback" approach is increasingly common especially in high performance code where synchronous completions are relatively frequent. Note it won't help at all if the completion is always genuinely asynchronous.

Additional things that apply here:

  1. with recent C#, a common pattern is for the async fallback method is commonly implemented as a local function:

    Task<string> DoTheThings() {
        async Task<string> Awaited(Task<Cat> a, Task<House> b, Task<Tesla> c) {
            return DoWhatever(await a, await b, await c);
        }
        Task<Cat> x = FeedCat();
        Task<House> y = SellHouse();
        Task<Tesla> z = BuyCar();
    
        if(x.Status == TaskStatus.RanToCompletion &&
           y.Status == TaskStatus.RanToCompletion &&
           z.Status == TaskStatus.RanToCompletion)
            return Task.FromResult(
              DoWhatever(a.Result, b.Result, c.Result));
           // we can safely access .Result, as they are known
           // to be ran-to-completion
    
        return Awaited(x, y, z);
    }
    
  2. prefer ValueTask<T> to Task<T> if there is a good chance of things ever completely synchronously with many different return values:

    ValueTask<string> DoTheThings() {
        async ValueTask<string> Awaited(ValueTask<Cat> a, Task<House> b, Task<Tesla> c) {
            return DoWhatever(await a, await b, await c);
        }
        ValueTask<Cat> x = FeedCat();
        ValueTask<House> y = SellHouse();
        ValueTask<Tesla> z = BuyCar();
    
        if(x.IsCompletedSuccessfully &&
           y.IsCompletedSuccessfully &&
           z.IsCompletedSuccessfully)
            return new ValueTask<string>(
              DoWhatever(a.Result, b.Result, c.Result));
           // we can safely access .Result, as they are known
           // to be ran-to-completion
    
        return Awaited(x, y, z);
    }
    
  3. if possible, prefer IsCompletedSuccessfully to Status == TaskStatus.RanToCompletion; this now exists in .NET Core for Task, and everywhere for ValueTask<T>

SQL: Group by minimum value in one field while selecting distinct rows

This does it simply:

select t2.id,t2.record_date,t2.other_cols 
from (select ROW_NUMBER() over(partition by id order by record_date)as rownum,id,record_date,other_cols from MyTable)t2 
where t2.rownum = 1

How to create helper file full of functions in react native?

Quick note: You are importing a class, you can't call properties on a class unless they are static properties. Read more about classes here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

There's an easy way to do this, though. If you are making helper functions, you should instead make a file that exports functions like this:

export function HelloChandu() {

}

export function HelloTester() {

}

Then import them like so:

import { HelloChandu } from './helpers'

or...

import functions from './helpers' then functions.HelloChandu

Disable cache for some images

If you need to do it dynamically in the browser using javascript, here is an example...

<img id=graph alt="" 
  src="http://www.kitco.com/images/live/gold.gif" 
  />

<script language="javascript" type="text/javascript">
    var d = new Date(); 
    document.getElementById("graph").src = 
      "http://www.kitco.com/images/live/gold.gif?ver=" + 
       d.getTime();
</script>

Bash Script : what does #!/bin/bash mean?

When the first characters in a script are #!, that is called the shebang. If your file starts with #!/path/to/something the standard is to run something and pass the rest of the file to that program as an input.

With that said, the difference between #!/bin/bash, #!/bin/sh, or even #!/bin/zsh is whether the bash, sh, or zsh programs are used to interpret the rest of the file. bash and sh are just different programs, traditionally. On some Linux systems they are two copies of the same program. On other Linux systems, sh is a link to dash, and on traditional Unix systems (Solaris, Irix, etc) bash is usually a completely different program from sh.

Of course, the rest of the line doesn't have to end in sh. It could just as well be #!/usr/bin/python, #!/usr/bin/perl, or even #!/usr/local/bin/my_own_scripting_language.

Show popup after page load

    <script type="text/javascript">
        $(window).on('load',function(){
            setTimeout(function(){ alert(" //show popup"); }, 5000); 
        });
    </script>

shared global variables in C

In the header file

header file

#ifndef SHAREFILE_INCLUDED
#define SHAREFILE_INCLUDED
#ifdef  MAIN_FILE
int global;
#else
extern int global;
#endif
#endif

In the file with the file you want the global to live:

#define MAIN_FILE
#include "share.h"

In the other files that need the extern version:

#include "share.h"

A table name as a variable

Declare @fs_e int, @C_Tables CURSOR, @Table varchar(50)

SET @C_Tables = CURSOR FOR
        select name from sysobjects where OBJECTPROPERTY(id, N'IsUserTable') = 1 AND name like 'TR_%'
OPEN @C_Tables
FETCH @C_Tables INTO @Table
    SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'

WHILE ( @fs_e <> -1)
    BEGIN
        exec('Select * from ' + @Table)
        FETCH @C_Tables INTO @Table
        SELECT @fs_e = sdec.fetch_Status FROM sys.dm_exec_cursors(0) as sdec where sdec.name = '@C_Tables'
    END

c# - approach for saving user settings in a WPF application?

You can store your settings info as Strings of XML in the Settings.Default. Create some classes to store your configuration data and make sure they are [Serializable]. Then, with the following helpers, you can serialize instances of these objects--or List<T> (or arrays T[], etc.) of them--to String. Store each of these various strings in its own respective Settings.Default slot in your WPF application's Settings.

To recover the objects the next time the app starts, read the Settings string of interest and Deserialize to the expected type T (which this time must be explcitly specified as a type argument to Deserialize<T>).

public static String Serialize<T>(T t)
{
    using (StringWriter sw = new StringWriter())
    using (XmlWriter xw = XmlWriter.Create(sw))
    {
        new XmlSerializer(typeof(T)).Serialize(xw, t);
        return sw.GetStringBuilder().ToString();
    }
}

public static T Deserialize<T>(String s_xml)
{
    using (XmlReader xw = XmlReader.Create(new StringReader(s_xml)))
        return (T)new XmlSerializer(typeof(T)).Deserialize(xw);
}

Class has been compiled by a more recent version of the Java Environment

I'm writing this because I found the other answers hard to understand.

Essentially your JRE is not updated and/or Eclipse is not configured to use the most recent JRE.

On Windows, go to Control Panel -> Programs -> Java -> update and proceed to update java

or if you don't have Java, go to Oracle's website and download the most recent JRE.

Once this is done, go into eclipse, and under the project view, right click on your project, select Java Build Path, double click on JRE System Library, then Select Workspace Default JRE 14.1.

If a recent version of Java doesn't show up here, it probably isn't installed. Check you JRE(NOT JDK) version and make sure it's recent. If it is, try restarting the computer then trying this again.

How to secure the ASP.NET_SessionId cookie?

To add the ; secure suffix to the Set-Cookie http header I simply used the <httpCookies> element in the web.config:

<system.web>
  <httpCookies httpOnlyCookies="true" requireSSL="true" />
</system.web>

IMHO much more handy than writing code as in the article of Anubhav Goyal.

See: http://msdn.microsoft.com/en-us/library/ms228262(v=vs.100).aspx

Twitter Bootstrap: div in container with 100% height

Set the class .fill to height: 100%

.fill { 
    min-height: 100%;
    height: 100%;
}

JSFiddle

(I put a red background for #map so you can see it takes up 100% height)

How to write a PHP ternary operator

In addition to all the other answers, you could use switch. But it does seem a bit long.

switch ($result->vocation) {
case 1:
    echo 'Sorcerer';
    break;

case 2:
    echo 'Druid';
    break;

case 3:
    echo 'Paladin';
    break;

case 4:
    echo 'Knight';
    break;

case 5:
    echo 'Master Sorcerer';
    break;

case 6:
    echo 'Elder Druid';
    break;

case 7:
    echo 'Royal Paladin';
    break;

default:
    echo 'Elite Knight';
    break;
}

Regex Named Groups in Java

Yes but its messy hacking the sun classes. There is a simpler way:

http://code.google.com/p/named-regexp/

named-regexp is a thin wrapper for the standard JDK regular expressions implementation, with the single purpose of handling named capturing groups in the .net style : (?...).

It can be used with Java 5 and 6 (generics are used).

Java 7 will handle named capturing groups , so this project is not meant to last.

creating Hashmap from a JSON String

Best way to parse Json to HashMap

public static HashMap<String, String> jsonToMap(JSONObject json) throws JSONException {
            HashMap<String, String> map = new HashMap<>();
            try {
                Iterator<String> iterator = json.keys();

                while (iterator.hasNext()) {
                    String key = iterator.next();
                    String value = json.getString(key);
                    map.put(key, value);
                }

                return map;
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

jQuery .css("margin-top", value) not updating in IE 8 (Standards mode)

Try marginTop in place of margin-top, eg:

$("#ActionBox").css("marginTop", foo);

Pythonic way to combine FOR loop and IF statement

Use intersection or intersection_update

  • intersection :

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    ans = sorted(set(a).intersection(set(xyz)))
    
  • intersection_update:

    a = [2,3,4,5,6,7,8,9,0]
    xyz = [0,12,4,6,242,7,9]
    b = set(a)
    b.intersection_update(xyz)
    

    then b is your answer

How to write :hover using inline style?

Not gonna happen with CSS only

Inline javascript

<a href='index.html' 
    onmouseover='this.style.textDecoration="none"' 
    onmouseout='this.style.textDecoration="underline"'>
    Click Me
</a>

In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:

<a href="http://www.w3.org/Style/CSS"
   style="{color: blue; background: white}  /* a+=0 b+=0 c+=0 */
      :visited {color: green}           /* a+=0 b+=1 c+=0 */
      :hover {background: yellow}       /* a+=0 b+=1 c+=0 */
      :visited:hover {color: purple}    /* a+=0 b+=2 c+=0 */
     ">
</a>

but it was never implemented in the release of the spec as far as I know.

http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules

How to get a path to a resource in a Java JAR file

This is same code from user Tombart with stream flush and close to avoid incomplete temporary file content copy from jar resource and to have unique temp file names.

File file = null;
String resource = "/view/Trial_main.html" ;
URL res = getClass().getResource(resource);
if (res.toString().startsWith("jar:")) {
    try {
        InputStream input = getClass().getResourceAsStream(resource);
        file = File.createTempFile(new Date().getTime()+"", ".html");
        OutputStream out = new FileOutputStream(file);
        int read;
        byte[] bytes = new byte[1024];

        while ((read = input.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
        input.close();
        file.deleteOnExit();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
} else {
    //this will probably work in your IDE, but not from a JAR
    file = new File(res.getFile());
}
         

NSURLErrorDomain error codes description

IN SWIFT 3. Here are the NSURLErrorDomain error codes description in a Swift 3 enum: (copied from answer above and converted what i can).

enum NSURLError: Int {
    case unknown = -1
    case cancelled = -999
    case badURL = -1000
    case timedOut = -1001
    case unsupportedURL = -1002
    case cannotFindHost = -1003
    case cannotConnectToHost = -1004
    case connectionLost = -1005
    case lookupFailed = -1006
    case HTTPTooManyRedirects = -1007
    case resourceUnavailable = -1008
    case notConnectedToInternet = -1009
    case redirectToNonExistentLocation = -1010
    case badServerResponse = -1011
    case userCancelledAuthentication = -1012
    case userAuthenticationRequired = -1013
    case zeroByteResource = -1014
    case cannotDecodeRawData = -1015
    case cannotDecodeContentData = -1016
    case cannotParseResponse = -1017
    //case NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022
    case fileDoesNotExist = -1100
    case fileIsDirectory = -1101
    case noPermissionsToReadFile = -1102
    //case NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103

    // SSL errors
    case secureConnectionFailed = -1200
    case serverCertificateHasBadDate = -1201
    case serverCertificateUntrusted = -1202
    case serverCertificateHasUnknownRoot = -1203
    case serverCertificateNotYetValid = -1204
    case clientCertificateRejected = -1205
    case clientCertificateRequired = -1206
    case cannotLoadFromNetwork = -2000

    // Download and file I/O errors
    case cannotCreateFile = -3000
    case cannotOpenFile = -3001
    case cannotCloseFile = -3002
    case cannotWriteToFile = -3003
    case cannotRemoveFile = -3004
    case cannotMoveFile = -3005
    case downloadDecodingFailedMidStream = -3006
    case downloadDecodingFailedToComplete = -3007

    /*
     case NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018
     case NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019
     case NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020
     case NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021

     case NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995
     case NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996
     case NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997
     */
}

Direct link to URLError.Code in the Swift github repository, which contains the up to date list of error codes being used (github link).

Storing and retrieving datatable from session

this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.

for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.

PS: but like I said, this might be totally unrelated to your query :)

Add new value to an existing array in JavaScript

Indeed, you must initialize your array then right after that use array.push() command line.

var array = new Array();
array.push("first value");
array.push("second value");

Getting a HeadlessException: No X11 DISPLAY variable was set

I think you are trying to run some utility or shell script from UNIX\LINUX which has some GUI. Anyways

SOLUTION: dude all you need is an XServer & X11 forwarding enabled. I use XMing (XServer). You are already enabling X11 forwarding. Just Install it(XMing) and keep it running when you create the session with PuTTY.

How to correctly save instance state of Fragments in back stack?

To correctly save the instance state of Fragment you should do the following:

1. In the fragment, save instance state by overriding onSaveInstanceState() and restore in onActivityCreated():

class MyFragment extends Fragment {

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        ...
        if (savedInstanceState != null) {
            //Restore the fragment's state here
        }
    }
    ...
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //Save the fragment's state here
    }

}

2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState() and restore in onCreate().

class MyActivity extends Activity {

    private MyFragment 

    public void onCreate(Bundle savedInstanceState) {
        ...
        if (savedInstanceState != null) {
            //Restore the fragment's instance
            mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
            ...
        }
        ...
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        //Save the fragment's instance
        getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
    }

}

Hope this helps.

Laravel orderBy on a relationship

Try this solution.

$mainModelData = mainModel::where('column', $value)
    ->join('relationModal', 'main_table_name.relation_table_column', '=', 'relation_table.id')
    ->orderBy('relation_table.title', 'ASC')
    ->with(['relationModal' => function ($q) {
        $q->where('column', 'value');
    }])->get();

Example:

$user = User::where('city', 'kullu')
    ->join('salaries', 'users.id', '=', 'salaries.user_id')
    ->orderBy('salaries.amount', 'ASC')
    ->with(['salaries' => function ($q) {
        $q->where('amount', '>', '500000');
    }])->get();

You can change the column name in join() as per your database structure.

How do you import an Eclipse project into Android Studio now?

Simple steps: 1.Go to Android Studio. 2.Close all open projects if any. 3.There will be an option which says import non Android Studio Projects(Eclipse ect). 4.Click on it and choose ur project Thats't it enjoy!!!

SaveFileDialog setting default path and file type?

Here's an example that actually filters for BIN files. Also Windows now want you to save files to user locations, not system locations, so here's an example (you can use intellisense to browse the other options):

            var saveFileDialog = new Microsoft.Win32.SaveFileDialog()
            {
                DefaultExt = "*.xml",
                Filter = "BIN Files (*.bin)|*.bin",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
            };

            var result = saveFileDialog.ShowDialog();
            if (result != null && result == true)
            {
                // Save the file here
            }

What is the easiest/best/most correct way to iterate through the characters of a string in Java?

There are some dedicated classes for this:

import java.text.*;

final CharacterIterator it = new StringCharacterIterator(s);
for(char c = it.first(); c != CharacterIterator.DONE; c = it.next()) {
   // process c
   ...
}

Reverse of JSON.stringify?

How about this

var parsed = new Function('return ' + stringifiedJSON )();

This is a safer alternative for eval.

_x000D_
_x000D_
var stringifiedJSON = '{"hello":"world"}';_x000D_
var parsed = new Function('return ' + stringifiedJSON)();_x000D_
alert(parsed.hello);
_x000D_
_x000D_
_x000D_

How to convert "Mon Jun 18 00:00:00 IST 2012" to 18/06/2012?

I hope following program will solve your problem

String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);        

Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" +         cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);    

ArrayList insertion and retrieval order

Yes it remains the same. but why not easily test it? Make an ArrayList, fill it and then retrieve the elements!

How to get the day of week and the month of the year?

Yes, you'll need arrays.

var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];
var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

var day = days[ now.getDay() ];
var month = months[ now.getMonth() ];

Or you can use the date.js library.


EDIT:

If you're going to use these frequently, you may want to extend Date.prototype for accessibility.

(function() {
    var days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'];

    var months = ['January','February','March','April','May','June','July','August','September','October','November','December'];

    Date.prototype.getMonthName = function() {
        return months[ this.getMonth() ];
    };
    Date.prototype.getDayName = function() {
        return days[ this.getDay() ];
    };
})();

var now = new Date();

var day = now.getDayName();
var month = now.getMonthName();

What is PAGEIOLATCH_SH wait type in SQL Server?

From Microsoft documentation:

PAGEIOLATCH_SH

Occurs when a task is waiting on a latch for a buffer that is in an I/O request. The latch request is in Shared mode. Long waits may indicate problems with the disk subsystem.

In practice, this almost always happens due to large scans over big tables. It almost never happens in queries that use indexes efficiently.

If your query is like this:

Select * from <table> where <col1> = <value> order by <PrimaryKey>

, check that you have a composite index on (col1, col_primary_key).

If you don't have one, then you'll need either a full INDEX SCAN if the PRIMARY KEY is chosen, or a SORT if an index on col1 is chosen.

Both of them are very disk I/O consuming operations on large tables.

How can a Java program get its own process ID?

Here's a backdoor method which might not work with all VMs but should work on both linux and windows (original example here):

java.lang.management.RuntimeMXBean runtime = 
    java.lang.management.ManagementFactory.getRuntimeMXBean();
java.lang.reflect.Field jvm = runtime.getClass().getDeclaredField("jvm");
jvm.setAccessible(true);
sun.management.VMManagement mgmt =  
    (sun.management.VMManagement) jvm.get(runtime);
java.lang.reflect.Method pid_method =  
    mgmt.getClass().getDeclaredMethod("getProcessId");
pid_method.setAccessible(true);

int pid = (Integer) pid_method.invoke(mgmt);

Counting the number of elements in array

This expands on the answer by Denis Bubnov.

I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.

{% set count = 0 %}
{% for anchor in items %}
    {% if anchor.content['#paragraph'].field_anchor_link.0.value %}
        {% set count = count + 1 %}
    {% endif %}
{% endfor %}

{% if count > 0 %}
 ---  build the toc here --
{% endif %}

How to open a new file in vim in a new window

I use this subtle alias:

alias vim='gnome-terminal -- vim'

-x is deprecated now. We need to use -- instead

ORA-00054: resource busy and acquire with NOWAIT specified

Depending on your situation, the table being locked may just be part of a normal operation & you don't want to just kill the blocking transaction. What you want to do is have your statement wait for the other resource. Oracle 11g has DDL timeouts which can be set to deal with this.

If you're dealing with 10g then you have to get more creative and write some PL/SQL to handle the re-try. Look at Getting around ORA-00054 in Oracle 10g This re-runs your statement when a resource_busy exception occurs.

How to set TextView textStyle such as bold, italic

Best way is to define it in styles.xml

<style name="common_txt_style_heading" parent="android:style/Widget.TextView">
        <item name="android:textSize">@dimen/common_txtsize_heading</item>
        <item name="android:textColor">@color/color_black</item>
        <item name="android:textStyle">bold|italic</item>
</style>

And update it in TextView

  <TextView
     android:id="@+id/txt_userprofile"
     style="@style/common_txt_style_heading"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="@dimen/margin_small"
     android:text="@string/some_heading" />

How to exit from ForEach-Object in PowerShell

Item #1. Putting a break within the foreach loop does exit the loop, but it does not stop the pipeline. It sounds like you want something like this:

$todo=$project.PropertyGroup 
foreach ($thing in $todo){
    if ($thing -eq 'some_condition'){
        break
    }
}

Item #2. PowerShell lets you modify an array within a foreach loop over that array, but those changes do not take effect until you exit the loop. Try running the code below for an example.

$a=1,2,3
foreach ($value in $a){
  Write-Host $value
}
Write-Host $a

I can't comment on why the authors of PowerShell allowed this, but most other scripting languages (Perl, Python and shell) allow similar constructs.

jQuery UI Dialog OnBeforeUnload

For ASP.NET MVC if you want to make an exception for leaving the page via submitting a particular form:

Set a form id:

@using (Html.BeginForm("Create", "MgtJob", FormMethod.Post, new { id = "createjob" }))
{
  // Your code
}



<script type="text/javascript">

  // Without submit form
   $(window).bind('beforeunload', function () {
        if ($('input').val() !== '') {
            return "It looks like you have input you haven't submitted."
        }
    });

    // this will call before submit; and it will unbind beforeunload
    $(function () {
        $("#createjob").submit(function (event) {
            $(window).unbind("beforeunload");
        });
    });

</script>

CodeIgniter - accessing $config variable in view

Example, if you have:

$config['base_url'] = 'www.example.com'

set in your config.php then

echo base_url();

This works very well almost at every place.
/* Edit */
This might work for the latest versions of codeigniter (4 and above).

Is there a java setting for disabling certificate validation?

Use cli utility keytool from java software distribution for import (and trust!) needed certificates

Sample:

  1. From cli change dir to jre\bin

  2. Check keystore (file found in jre\bin directory)
    keytool -list -keystore ..\lib\security\cacerts
    Enter keystore password: changeit

  3. Download and save all certificates chain from needed server.

  4. Add certificates (before need to remove "read-only" attribute on file "..\lib\security\cacerts") keytool -alias REPLACE_TO_ANY_UNIQ_NAME -import -keystore ..\lib\security\cacerts -file "r:\root.crt"

accidentally I found such a simple tip. Other solutions require the use of InstallCert.Java and JDK

source: http://www.java-samples.com/showtutorial.php?tutorialid=210

What's the meaning of System.out.println in Java?

System.out.println("...") in Java code is translated into JVM. Looking into the JVM gave me better understanding what is going on behind the hood.

From the book Programming form the Java Virtual Machine. This code is copied from https://github.com/ymasory/programming-for-the-jvm/blob/master/examples/HelloWorld.j.

This is the JVM source code.

.class public HelloWorld
.super java/lang/Object

.method public static main([Ljava/lang/String;)V
.limit stack 2
.limit locals 1
  getstatic java/lang/System/out Ljava/io/PrintStream;
  ldc "Hello, world"
  invokevirtual java/io/PrintStream/println
    (Ljava/lang/String;)V
  return

.end method
.end class

As "The JVM doesn't permit byte-level access to memory" the out object in type Ljava/io/PrintSteram; is stored in a stack with getstatic JVM command. Then the argument is pushed on the stack before called a method println of the java/io/PrintStream class from an instance named out. The method's parameter is (Ljava/lang/String;) and output type is void (V).

Scala: join an iterable of strings

How about mkString ?

theStrings.mkString(",")

A variant exists in which you can specify a prefix and suffix too.

See here for an implementation using foldLeft, which is much more verbose, but perhaps worth looking at for education's sake.

How to detect scroll position of page using jQuery

Store the value of the scroll as changes in HiddenField when around the PostBack retrieves the value and adds the scroll.

//jQuery

jQuery(document).ready(function () {

    $(window).scrollTop($("#<%=hidScroll.ClientID %>").val());

    $(window).scroll(function (event) {
        $("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
    });
});

var prm = Sys.WebForms.PageRequestManager.getInstance();

prm.add_endRequest(function () {

    $(window).scrollTop($("#<%=hidScroll.ClientID %>").val());

    $(window).scroll(function (event) {
        $("#<%=hidScroll.ClientID %>").val($(window).scrollTop());
    });
});

//Page Asp.Net
<asp:HiddenField ID="hidScroll" runat="server" Value="0" />

How to expand textarea width to 100% of parent (or how to expand any HTML element to 100% of parent width)?

_x000D_
_x000D_
<div>_x000D_
  <div style="width: 20%; float: left;">_x000D_
    <p>Some Contentsssssssssss</p>_x000D_
  </div>_x000D_
  <div style="float: left; width: 80%;">_x000D_
    <textarea style="width: 100%; max-width: 100%;"></textarea>_x000D_
  </div>_x000D_
  <div style="clear: both;"></div>_x000D_
</div>_x000D_
_x000D_
 
_x000D_
_x000D_
_x000D_

How to get current date in 'YYYY-MM-DD' format in ASP.NET?

Which WebControl are you using? Did you try?

DateTime.Now.ToString("yyyy-MM-dd");

How to copy static files to build directory with Webpack?

Above suggestions are good. But to try to answer your question directly I'd suggest using cpy-cli in a script defined in your package.json.

This example expects node to somewhere on your path. Install cpy-cli as a development dependency:

npm install --save-dev cpy-cli

Then create a couple of nodejs files. One to do the copy and the other to display a checkmark and message.

copy.js

#!/usr/bin/env node

var shelljs = require('shelljs');
var addCheckMark = require('./helpers/checkmark');
var path = require('path');

var cpy = path.join(__dirname, '../node_modules/cpy-cli/cli.js');

shelljs.exec(cpy + ' /static/* /build/', addCheckMark.bind(null, callback));

function callback() {
  process.stdout.write(' Copied /static/* to the /build/ directory\n\n');
}

checkmark.js

var chalk = require('chalk');

/**
 * Adds mark check symbol
 */
function addCheckMark(callback) {
  process.stdout.write(chalk.green(' ?'));
  callback();
}

module.exports = addCheckMark;

Add the script in package.json. Assuming scripts are in <project-root>/scripts/

...
"scripts": {
  "copy": "node scripts/copy.js",
...

To run the sript:

npm run copy

Bootstrap Element 100% Width

There is a workaround using vw. Is useful when you can't create a new fluid container. This, inside a classic 'container' div will be full size.

.row-full{
 width: 100vw;
 position: relative;
 margin-left: -50vw;
 left: 50%;
}

After this there is the sidebar problem (thanks to @Typhlosaurus), solved with this js function, calling it on document load and resize:

function full_row_resize(){
    var body_width = $('body').width();
    $('.row-full').css('width', (body_width));
    $('.row-full').css('margin-left', ('-'+(body_width/2)+'px'));
    return false;
}

New Line Issue when copying data from SQL Server 2012 to Excel

Once Data is exported to excel, highlight the date column and format to fit your needs or use the custom field. Worked for me like a charm!

JavaScript TypeError: Cannot read property 'style' of null

This happens because document.write would overwrite your existing code therefore place your div before your javascript code. e.g.:

CSS:

#mydiv { 
  visibility:hidden;
 }

Inside your html file

<div id="mydiv">
   <p>Hello world</p>
</div>
<script type="text/javascript">
   document.getElementById('mydiv').style.visibility='visible';
</script>

Hope this was helpful

disable past dates on datepicker

this works for me,

$(function() { $('.datepicker').datepicker({ startDate: '-0m', autoclose: true }); });

Should URL be case sensitive?

The domain name portion of a URL is not case sensitive since DNS ignores case: http://en.example.org/ and HTTP://EN.EXAMPLE.ORG/ both open the same page.

The path is used to specify and perhaps find the resource requested. It is case-sensitive, though it may be treated as case-insensitive by some servers, especially those based on Microsoft Windows.

If the server is case sensitive and http://en.example.org/wiki/URL is correct, then http://en.example.org/WIKI/URL or http://en.example.org/wiki/url will display an HTTP 404 error page, unless these URLs point to valid resources themselves.

How to disable Django's CSRF validation?

To disable CSRF for class based views the following worked for me.
Using django 1.10 and python 3.5.2

from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator

@method_decorator(csrf_exempt, name='dispatch')
class TestView(View):
    def post(self, request, *args, **kwargs):
        return HttpResponse('Hello world')

How to access my localhost from another PC in LAN?

Actualy you don't need an internet connection to use ip address. Each computer in LAN has an internal IP address you can discover by runing

ipconfig /all

in cmd.

You can use the ip address of the server (probabily something like 192.168.0.x or 10.0.0.x) to access the website remotely.

If you found the ip and still cannot access the website, it means WAMP is not configured to respond to that name ( what did you call me? 192.168.0.3? That's not my name. I'm Localhost ) and you have to modify ....../apache/config/httpd.conf

Listen *:80

Removing an item from a select box

To Remove an Item

$("select#mySelect option[value='option1']").remove(); 

To Add an item

$("#mySelect").append('<option value="option1">Option</option>');

To Check for an option

$('#yourSelect option[value=yourValue]').length > 0;

To remove a selected option

$('#mySelect :selected').remove(); 

Android Studio - mergeDebugResources exception

It could be a faulty name of a drawable file. I had an image I was using that was named Untitled. Changing the name solved my problem.

Codeigniter - no input file specified

My site is hosted on MochaHost, i had a tough time to setup the .htaccess file so that i can remove the index.php from my urls. However, after some googling, i combined the answer on this thread and other answers. My final working .htaccess file has the following contents:

<IfModule mod_rewrite.c>
    # Turn on URL rewriting
    RewriteEngine On

    # If your website begins from a folder e.g localhost/my_project then 
    # you have to change it to: RewriteBase /my_project/
    # If your site begins from the root e.g. example.local/ then
    # let it as it is
    RewriteBase /

    # Protect application and system files from being viewed when the index.php is missing
    RewriteCond $1 ^(application|system|private|logs)

    # Rewrite to index.php/access_denied/URL
    RewriteRule ^(.*)$ index.php/access_denied/$1 [PT,L]

    # Allow these directories and files to be displayed directly:
    RewriteCond $1 ^(index\.php|robots\.txt|favicon\.ico|public|app_upload|assets|css|js|images)

    # No rewriting
    RewriteRule ^(.*)$ - [PT,L]

    # Rewrite to index.php/URL
    RewriteRule ^(.*)$ index.php?/$1 [PT,L]
</IfModule>

Which rows are returned when using LIMIT with OFFSET in MySQL?

It will return 18 results starting on record #9 and finishing on record #26.

Start by reading the query from offset. First you offset by 8, which means you skip the first 8 results of the query. Then you limit by 18. Which means you consider records 9, 10, 11, 12, 13, 14, 15, 16....24, 25, 26 which are a total of 18 records.

Check this out.

And also the official documentation.

MySQL: ALTER TABLE if column not exists

Add field if not exist:

CALL addFieldIfNotExists ('settings', 'multi_user', 'TINYINT(1) NOT NULL DEFAULT 1');

addFieldIfNotExists code:

DELIMITER $$

DROP PROCEDURE IF EXISTS addFieldIfNotExists 
$$

DROP FUNCTION IF EXISTS isFieldExisting 
$$

CREATE FUNCTION isFieldExisting (table_name_IN VARCHAR(100), field_name_IN VARCHAR(100)) 
RETURNS INT
RETURN (
    SELECT COUNT(COLUMN_NAME) 
    FROM INFORMATION_SCHEMA.columns 
    WHERE TABLE_SCHEMA = DATABASE() 
    AND TABLE_NAME = table_name_IN 
    AND COLUMN_NAME = field_name_IN
)
$$

CREATE PROCEDURE addFieldIfNotExists (
    IN table_name_IN VARCHAR(100)
    , IN field_name_IN VARCHAR(100)
    , IN field_definition_IN VARCHAR(100)
)
BEGIN

    SET @isFieldThere = isFieldExisting(table_name_IN, field_name_IN);
    IF (@isFieldThere = 0) THEN

        SET @ddl = CONCAT('ALTER TABLE ', table_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', 'ADD COLUMN') ;
        SET @ddl = CONCAT(@ddl, ' ', field_name_IN);
        SET @ddl = CONCAT(@ddl, ' ', field_definition_IN);

        PREPARE stmt FROM @ddl;
        EXECUTE stmt;
        DEALLOCATE PREPARE stmt;

    END IF;

END;
$$

IOException: Too many open files

You can handle the fds yourself. The exec in java returns a Process object. Intermittently check if the process is still running. Once it has completed close the processes STDERR, STDIN, and STDOUT streams (e.g. proc.getErrorStream.close()). That will mitigate the leaks.

How can I find my php.ini on wordpress?

Wordpress dont have a php.ini file. It just a cms, look into your server. for example if you use XAMPP in windows xampp\php\php.ini is the location.

Find document with array that contains a specific value

If you'd want to use something like a "contains" operator through javascript, you can always use a Regular expression for that...

eg. Say you want to retrieve a customer having "Bartolomew" as name

async function getBartolomew() {
    const custStartWith_Bart = await Customers.find({name: /^Bart/ }); // Starts with Bart
    const custEndWith_lomew = await Customers.find({name: /lomew$/ }); // Ends with lomew
    const custContains_rtol = await Customers.find({name: /.*rtol.*/ }); // Contains rtol

    console.log(custStartWith_Bart);
    console.log(custEndWith_lomew);
    console.log(custContains_rtol);
}

How to SUM parts of a column which have same text value in different column in the same row

If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name

=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))

See screenshot

enter image description here

Monitor the Graphics card usage

From Unix.SE: A simple command-line utility called gpustat now exists: https://github.com/wookayin/gpustat.

It is free software (MIT license) and is packaged in pypi. It is a wrapper of nvidia-smi.

Show a number to two decimal places

$retailPrice = 5.989;
echo number_format(floor($retailPrice*100)/100,2, '.', ''); 

It will return 5.98 without rounding the number.

Memcached vs. Redis?

It would not be wrong, if we say that redis is combination of (cache + data structure) while memcached is just a cache.

Permanently add a directory to PYTHONPATH?

This works on Windows

  1. On Windows, with Python 2.7 go to the Python setup folder.
  2. Open Lib/site-packages.
  3. Add an example.pth empty file to this folder.
  4. Add the required path to the file, one per each line.

Then you'll be able to see all modules within those paths from your scripts.

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

As of ES 7, mapping types have been removed. You can read more details here

If you are using Ruby On Rails this means that you may need to remove document_type from your model or concern.

As an alternative to mapping types one solution is to use an index per document type.

Before:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore].join('_')
    document_type self.name.downcase
  end
end

After:

module Searchable
  extend ActiveSupport::Concern

  included do
    include Elasticsearch::Model
    include Elasticsearch::Model::Callbacks
    index_name [Rails.env, Rails.application.class.module_parent_name.underscore, self.name.downcase].join('_')
  end
end

Encoding an image file with base64

The first answer will print a string with prefix b'. That means your string will be like this b'your_string' To solve this issue please add the following line of code.

encoded_string= base64.b64encode(img_file.read())
print(encoded_string.decode('utf-8'))

Mockito: Trying to spy on method is calling the original method

My case was different from the accepted answer. I was trying to mock a package-private method for an instance that did not live in that package

package common;

public class Animal {
  void packageProtected();
}

package instances;

class Dog extends Animal { }

and the test classes

package common;

public abstract class AnimalTest<T extends Animal> {
  @Before
  setup(){
    doNothing().when(getInstance()).packageProtected();
  }

  abstract T getInstance();
}

package instances;

class DogTest extends AnimalTest<Dog> {
  Dog getInstance(){
    return spy(new Dog());
  }

  @Test
  public void myTest(){}
}

The compilation is correct, but when it tries to setup the test, it invokes the real method instead.

Declaring the method protected or public fixes the issue, tho it's not a clean solution.

Blur or dim background when Android PopupWindow active

In your xml file add something like this with width and height as 'match_parent'.

<RelativeLayout
        android:id="@+id/bac_dim_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#C0000000"
        android:visibility="gone" >
</RelativeLayout>

In your activity oncreate

//setting background dim when showing popup
back_dim_layout = (RelativeLayout) findViewById(R.id.share_bac_dim_layout);

Finally make visible when you show your popupwindow and make its visible gone when you exit popupwindow.

back_dim_layout.setVisibility(View.VISIBLE);
back_dim_layout.setVisibility(View.GONE);

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

The error you are getting is either because you are doing TO_DATE on a column that's already a date, and you're using a format mask that is different to your nls_date_format parameter[1] or because the event_occurrence column contains data that isn't a number.

You need to a) correct your query so that it's not using TO_DATE on the date column, and b) correct your data, if event_occurrence is supposed to be just numbers.

And fix the datatype of that column to make sure you can only store numbers.



[1] What Oracle does when you do: TO_DATE(date_column, non_default_format_mask) is: TO_DATE(TO_CHAR(date_column, nls_date_format), non_default_format_mask)

Generally, the default nls_date_format parameter is set to dd-MON-yy, so in your query, what is likely to be happening is your date column is converted to a string in the format dd-MON-yy, and you're then turning it back to a date using the format MMDD. The string is not in this format, so you get an error.

How to remove an element from an array in Swift

To remove elements from an array, use the remove(at:), removeLast() and removeAll().

yourArray = [1,2,3,4]

Remove the value at 2 position

yourArray.remove(at: 2)

Remove the last value from array

yourArray.removeLast()

Removes all members from the set

yourArray.removeAll()

Min/Max-value validators in asp.net mvc

jQuery Validation Plugin already implements min and max rules, we just need to create an adapter for our custom attribute:

public class MaxAttribute : ValidationAttribute, IClientValidatable
{
    private readonly int maxValue;

    public MaxAttribute(int maxValue)
    {
        this.maxValue = maxValue;
    }

    public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
    {
        var rule = new ModelClientValidationRule();

        rule.ErrorMessage = ErrorMessageString, maxValue;

        rule.ValidationType = "max";
        rule.ValidationParameters.Add("max", maxValue);
        yield return rule;
    }

    public override bool IsValid(object value)
    {
        return (int)value <= maxValue;
    }
}

Adapter:

$.validator.unobtrusive.adapters.add(
   'max',
   ['max'],
   function (options) {
       options.rules['max'] = parseInt(options.params['max'], 10);
       options.messages['max'] = options.message;
   });

Min attribute would be very similar.

Spark - load CSV file as DataFrame?

It's for whose Hadoop is 2.6 and Spark is 1.6 and without "databricks" package.

import org.apache.spark.sql.types.{StructType,StructField,StringType,IntegerType};
import org.apache.spark.sql.Row;

val csv = sc.textFile("/path/to/file.csv")
val rows = csv.map(line => line.split(",").map(_.trim))
val header = rows.first
val data = rows.filter(_(0) != header(0))
val rdd = data.map(row => Row(row(0),row(1).toInt))

val schema = new StructType()
    .add(StructField("id", StringType, true))
    .add(StructField("val", IntegerType, true))

val df = sqlContext.createDataFrame(rdd, schema)

Is there a C# case insensitive equals operator?

Try this:

string.Equals(a, b, StringComparison.CurrentCultureIgnoreCase);

HTTP 400 (bad request) for logical error, not malformed request syntax

Status 422 (RFC 4918, Section 11.2) comes to mind:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

HTML - Display image after selecting filename

Here You Go:

HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

Script:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

Live Demo

Responsive design with media query : screen size?

i will provide mine because @muni s solution was a bit overkill for me

note: if you want to add custom definitions for several resolutions together, say something like this:

//mobile generally   
 @media screen and (max-width: 1199)  {

      .irns-desktop{
        display: none;
      }

      .irns-mobile{
        display: initial;
      }

    }

Be sure to add those definitions on top of the accurate definitions, so it cascades correctly (e.g. 'smartphone portrait' must win versus 'mobile generally')

//here all definitions to apply globally


//desktop
@media only screen
and (min-width : 1200) {


}

//tablet landscape
@media screen and (min-width: 1024px) and (max-width: 1600px)  {

} // end media query

//tablet portrait
@media screen and (min-width: 768px) and (max-width: 1023px)  {

}//end media definition


//smartphone landscape
@media screen and (min-width: 480px) and (max-width: 767px)  {

}//end media query



//smartphone portrait
@media screen /*and (min-width: 320px)*/
and (max-width: 479px) {

}

//end media query

The best node module for XML parsing

This answer concerns developers for Windows. You want to pick an XML parsing module that does NOT depend on node-expat. Node-expat requires node-gyp and node-gyp requires you to install Visual Studio on your machine. If your machine is a Windows Server, you definitely don't want to install Visual Studio on it.

So, which XML parsing module to pick?

Save yourself a lot of trouble and use either xml2js or xmldoc. They depend on sax.js which is a pure Javascript solution that doesn't require node-gyp.

Both libxmljs and xml-stream require node-gyp. Don't pick these unless you already have Visual Studio on your machine installed or you don't mind going down that road.

Update 2015-10-24: it seems somebody found a solution to use node-gyp on Windows without installing VS: https://github.com/nodejs/node-gyp/issues/629#issuecomment-138276692

Git credential helper - update password

Solution using command line for Windows, Linux, and MacOS

If you have updated your GitHub password on the GitHub server, in the first attempt of the git fetch/pull/push command it generates the authentication failed message.

Execute the same git fetch/pull/push command a second time and it prompts for credentials (username and password). Enter the username and the new updated password of the GitHub server and login will be successful.

Even I had this problem, and I performed the above steps and done!!

Easy way to dismiss keyboard?

It's not pretty, but the way I resign the firstResponder when I don't know what that the responder is:

Create an UITextField, either in IB or programmatically. Make it Hidden. Link it up to your code if you made it in IB. Then, when you want to dismiss the keyboard, you switch the responder to the invisible text field, and immediately resign it:

  [self.invisibleField becomeFirstResponder];
  [self.invisibleField resignFirstResponder];

What is pluginManagement in Maven's pom.xml?

You still need to add

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-dependency-plugin</artifactId>
    </plugin>
</plugins>

in your build, because pluginManagement is only a way to share the same plugin configuration across all your project modules.

From Maven documentation:

pluginManagement: is an element that is seen along side plugins. Plugin Management contains plugin elements in much the same way, except that rather than configuring plugin information for this particular project build, it is intended to configure project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.

Best Practice: Initialize JUnit class fields in setUp() or at declaration?

I prefer readability first which most often does not use the setup method. I make an exception when a basic setup operation takes a long time and is repeated within each test.
At that point I move that functionality into a setup method using the @BeforeClass annotation (optimize later).

Example of optimization using the @BeforeClass setup method: I use dbunit for some database functional tests. The setup method is responsible for putting the database in a known state (very slow... 30 seconds - 2 minutes depending on amount of data). I load this data in the setup method annotated with @BeforeClass and then run 10-20 tests against the same set of data as opposed to re-loading/initializing the database inside each test.

Using Junit 3.8 (extending TestCase as shown in your example) requires writing a little more code than just adding an annotation, but the "run once before class setup" is still possible.

How to negate code in "if" statement block in JavaScript -JQuery like 'if not then..'

Try negation operator ! before $(this):

if (!$(this).parent().next().is('ul')){

How to create a localhost server to run an AngularJS project

You can also setup the environment in visual studio code. Run Ctrl + Shift + P, Then type ctr in the box that appears and select tasks:Configure Task Runner, Then change the task.json file to this: { "version": "0.1.0", "command": "explorer", "windows": { "command": "explorer.exe" }, "args": ["index.html"] }, save your changes, Then select your index.html file and type Ctrl + Shift + B. This will open the project with your default browser.

Fade In on Scroll Down, Fade Out on Scroll Up - based on element position in window

The reason your attempt wasn't working, is because the two animations (fade-in and fade-out) were working against each other.

Right before an object became visible, it was still invisible and so the animation for fading-out would run. Then, the fraction of a second later when that same object had become visible, the fade-in animation would try to run, but the fade-out was still running. So they would work against each other and you would see nothing.

Eventually the object would become visible (most of the time), but it would take a while. And if you would scroll down by using the arrow-button at the button of the scrollbar, the animation would sort of work, because you would scroll using bigger increments, creating less scroll-events.


Enough explanation, the solution (JS, CSS, HTML):

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  $(window).scroll(function() {_x000D_
    var windowBottom = $(this).scrollTop() + $(this).innerHeight();_x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")==0) {$(this).fadeTo(500,1);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")==1) {$(this).fadeTo(500,0);}_x000D_
      }_x000D_
    });_x000D_
  }).scroll(); //invoke scroll-handler on page-load_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/2/)

  • I wrapped the fade-codeline in an if-clause: if ($(this).css("opacity")==0) {...}. This makes sure the object is only faded in when the opacity is 0. Same goes for fading out. And this prevents the fade-in and fade-out from working against each other, because now there's ever only one of the two running at one time on an object.
  • I changed .animate() to .fadeTo(). It's jQuery's specialized function for opacity, a lot shorter to write and probably lighter than animate.
  • I changed .position() to .offset(). This always calculates relative to the body, whereas position is relative to the parent. For your case I believe offset is the way to go.
  • I changed $(window).height() to $(window).innerHeight(). The latter is more reliable in my experience.
  • Directly after the scroll-handler, I invoke that handler once on page-load with $(window).scroll();. Now you can give all desired objects on the page the .fade class, and objects that should be invisible at page-load, will be faded out immediately.
  • I removed #container from both HTML and CSS, because (at least for this answer) it isn't necessary. (I thought maybe you needed the height:2000px because you used .position() instead of .offset(), otherwise I don't know. Feel free of course to leave it in your code.)

UPDATE

If you want opacity values other than 0 and 1, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowBottom = $(window).scrollTop() + $(window).innerHeight();_x000D_
    var min = 0.3;_x000D_
    var max = 0.7;_x000D_
    var threshold = 0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectBottom = $(this).offset().top + $(this).outerHeight();_x000D_
      _x000D_
      /* If the element is completely within bounds of the window, fade it in */_x000D_
      if (objectBottom < windowBottom) { //object comes into view (scrolling down)_x000D_
        if ($(this).css("opacity")<=min+threshold || pageLoad) {$(this).fadeTo(500,max);}_x000D_
      } else { //object goes out of view (scrolling up)_x000D_
        if ($(this).css("opacity")>=max-threshold || pageLoad) {$(this).fadeTo(500,min);}_x000D_
      }_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/3/)

  • I added a threshold to the if-clause, see explanation below.
  • I created variables for the threshold and for min/max at the start of the function. In the rest of the function these variables are referenced. This way, if you ever want to change the values again, you only have to do it in one place.
  • I also added || pageLoad to the if-clause. This was necessary to make sure all objects are faded to the correct opacity on page-load. pageLoad is a boolean that is send along as an argument when fade() is invoked.
    I had to put the fade-code inside the extra function fade() {...}, in order to be able to send along the pageLoad boolean when the scroll-handler is invoked.
    I did't see any other way to do this, if anyone else does, please leave a comment.

Explanation:
The reason the code in your fiddle didn't work, is because the actual opacity values are always a little off from the value you set it to. So if you set the opacity to 0.3, the actual value (in this case) is 0.300000011920929. That's just one of those little bugs you have to learn along the way by trail and error. That's why this if-clause won't work: if ($(this).css("opacity") == 0.3) {...}.

I added a threshold, to take that difference into account: == 0.3 becomes <= 0.31.
(I've set the threshold to 0.01, this can be changed of course, just as long as the actual opacity will fall between the set value and this threshold.)

The operators are now changed from == to <= and >=.


UPDATE 2:

If you want to fade the elements based on their visible percentage, use the following code:

_x000D_
_x000D_
$(window).on("load",function() {_x000D_
  function fade(pageLoad) {_x000D_
    var windowTop=$(window).scrollTop(), windowBottom=windowTop+$(window).innerHeight();_x000D_
    var min=0.3, max=0.7, threshold=0.01;_x000D_
    _x000D_
    $(".fade").each(function() {_x000D_
      /* Check the location of each desired element */_x000D_
      var objectHeight=$(this).outerHeight(), objectTop=$(this).offset().top, objectBottom=$(this).offset().top+objectHeight;_x000D_
      _x000D_
      /* Fade element in/out based on its visible percentage */_x000D_
      if (objectTop < windowTop) {_x000D_
        if (objectBottom > windowTop) {$(this).fadeTo(0,min+((max-min)*((objectBottom-windowTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if (objectBottom > windowBottom) {_x000D_
        if (objectTop < windowBottom) {$(this).fadeTo(0,min+((max-min)*((windowBottom-objectTop)/objectHeight)));}_x000D_
        else if ($(this).css("opacity")>=min+threshold || pageLoad) {$(this).fadeTo(0,min);}_x000D_
      } else if ($(this).css("opacity")<=max-threshold || pageLoad) {$(this).fadeTo(0,max);}_x000D_
    });_x000D_
  } fade(true); //fade elements on page-load_x000D_
  $(window).scroll(function(){fade(false);}); //fade elements on scroll_x000D_
});
_x000D_
.fade {_x000D_
  margin: 50px;_x000D_
  padding: 50px;_x000D_
  background-color: lightgreen;_x000D_
  opacity: 1;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
  <div class="fade">Fade In 01</div>_x000D_
  <div class="fade">Fade In 02</div>_x000D_
  <div class="fade">Fade In 03</div>_x000D_
  <div class="fade">Fade In 04</div>_x000D_
  <div class="fade">Fade In 05</div>_x000D_
  <div class="fade">Fade In 06</div>_x000D_
  <div class="fade">Fade In 07</div>_x000D_
  <div class="fade">Fade In 08</div>_x000D_
  <div class="fade">Fade In 09</div>_x000D_
  <div class="fade">Fade In 10</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_ (fiddle: http://jsfiddle.net/eLwex993/5/)

How to kill MySQL connections

mysql> SHOW PROCESSLIST;
+-----+------+-----------------+------+---------+------+-------+---------------+
| Id  | User | Host            | db   | Command | Time | State | Info      |
+-----+------+-----------------+------+---------+------+-------+----------------+
| 143 | root | localhost:61179 | cds  | Query   |    0 | init  | SHOW PROCESSLIST |
| 192 | root | localhost:53793 | cds  | Sleep   |    4 |       | NULL      |
+-----+------+-----------------+------+---------+------+-------+----------------+
2 rows in set (0.00 sec)

mysql> KILL 192;
Query OK, 0 rows affected (0.00 sec)

USER 192 :

mysql> SELECT * FROM exept;
+----+
| id |
+----+
|  1 |
+----+
1 row in set (0.00 sec)

mysql> SELECT * FROM exept;
ERROR 2013 (HY000): Lost connection to MySQL server during query

How to add external JS scripts to VueJS Components

This can be simply done like this.

  created() {
    var scripts = [
      "https://cloudfront.net/js/jquery-3.4.1.min.js",
      "js/local.js"
    ];
    scripts.forEach(script => {
      let tag = document.createElement("script");
      tag.setAttribute("src", script);
      document.head.appendChild(tag);
    });
  }

How to create/make rounded corner buttons in WPF?

You can use attached properties for setting button border radius (also the same will work for textboxes).

Create class for attached property

public class CornerRadiusSetter
{
    public static CornerRadius GetCornerRadius(DependencyObject obj) => (CornerRadius)obj.GetValue(CornerRadiusProperty);

    public static void SetCornerRadius(DependencyObject obj, CornerRadius value) => obj.SetValue(CornerRadiusProperty, value);

    public static readonly DependencyProperty CornerRadiusProperty =
        DependencyProperty.RegisterAttached(nameof(Border.CornerRadius), typeof(CornerRadius),
            typeof(CornerRadiusSetter), new UIPropertyMetadata(new CornerRadius(), CornerRadiusChangedCallback));

    public static void CornerRadiusChangedCallback(object sender, DependencyPropertyChangedEventArgs e)
    {
        Control control = sender as Control;

        if (control == null) return;

        control.Loaded -= Control_Loaded;
        control.Loaded += Control_Loaded;
    }

    private static void Control_Loaded(object sender, EventArgs e)
    {
        Control control = sender as Control;

        if (control == null || control.Template == null) return;

        control.ApplyTemplate();

        Border border = control.Template.FindName("border", control) as Border;

        if (border == null) return;

        border.CornerRadius = GetCornerRadius(control);
    }
}

Then you can use attached property syntax for multiple buttons without style duplicates:

<Button local:CornerRadiusSetter.CornerRadius="10">Click me!</Button>
<Button local:CornerRadiusSetter.CornerRadius="5, 0, 0, 5">Click me!</Button>
<Button local:CornerRadiusSetter.CornerRadius="3, 20, 8, 15">Click me!</Button>

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

You can also use evalAsync. It will run sometime after digest has finished!

scope.evalAsync(function(scope){
    //use the scope...
});

Automatically get loop index in foreach loop in Perl

perldoc perlvar does not seem to suggest any such variable.

MVC 4 Data Annotations "Display" Attribute

In addition to the other answers, there is a big benefit to using the DisplayAttribute when you want to localize the fields. You can lookup the name in a localization database using the DisplayAttribute and it will use whatever translation you wish.

Also, you can let MVC generate the templates for you by using Html.EditorForModel() and it will generate the correct label for you.

Ultimately, it's up to you. But the MVC is very "Model-centric", which is why data attributes are applied to models, so that metadata exists in a single place. It's not like it's a huge amount of extra typing you have to do.

Paging with LINQ for objects

_x000D_
_x000D_
var results = (medicineInfo.OrderBy(x=>x.id)_x000D_
                       .Skip((pages -1) * 2)_x000D_
                       .Take(2));
_x000D_
_x000D_
_x000D_

Move a view up only when the keyboard covers an input field

Your problem is well explained in this document by Apple. Example code on this page (at Listing 4-1) does exactly what you need, it will scroll your view only when the current editing should be under the keyboard. You only need to put your needed controls in a scrollViiew. The only problem is that this is Objective-C and I think you need it in Swift..so..here it is:

Declare a variable

var activeField: UITextField?

then add these methods

 func registerForKeyboardNotifications()
{
    //Adding notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}


func deregisterFromKeyboardNotifications()
{
    //Removing notifies on keyboard appearing
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillShowNotification, object: nil)
    NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillHideNotification, object: nil)
}

func keyboardWasShown(notification: NSNotification)
{
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.scrollEnabled = true
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, keyboardSize!.height, 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeFieldPresent = activeField
    {
        if (!CGRectContainsPoint(aRect, activeField!.frame.origin))
        {
            self.scrollView.scrollRectToVisible(activeField!.frame, animated: true)
        }
    }


}


func keyboardWillBeHidden(notification: NSNotification)
{
    //Once keyboard disappears, restore original positions
    var info : NSDictionary = notification.userInfo!
    var keyboardSize = (info[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue().size
    var contentInsets : UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, -keyboardSize!.height, 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.scrollEnabled = false

}

func textFieldDidBeginEditing(textField: UITextField!)
{
    activeField = textField
}

func textFieldDidEndEditing(textField: UITextField!)
{
    activeField = nil
}

Be sure to declare your ViewController as UITextFieldDelegate and set correct delegates in your initialization methods: ex:

self.you_text_field.delegate = self

And remember to call registerForKeyboardNotifications on viewInit and deregisterFromKeyboardNotifications on exit.

Edit/Update: Swift 4.2 Syntax

func registerForKeyboardNotifications(){
    //Adding notifies on keyboard appearing
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWasShown(notification:)), name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillBeHidden(notification:)), name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

func deregisterFromKeyboardNotifications(){
    //Removing notifies on keyboard appearing
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillShowNotification, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIResponder.keyboardWillHideNotification, object: nil)
}

@objc func keyboardWasShown(notification: NSNotification){
    //Need to calculate keyboard exact size due to Apple suggestions
    self.scrollView.isScrollEnabled = true
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: keyboardSize!.height, right: 0.0)

    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets

    var aRect : CGRect = self.view.frame
    aRect.size.height -= keyboardSize!.height
    if let activeField = self.activeField {
        if (!aRect.contains(activeField.frame.origin)){
            self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
        }
    }
}

@objc func keyboardWillBeHidden(notification: NSNotification){
    //Once keyboard disappears, restore original positions
    var info = notification.userInfo!
    let keyboardSize = (info[UIResponder.keyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue.size
    let contentInsets : UIEdgeInsets = UIEdgeInsets(top: 0.0, left: 0.0, bottom: -keyboardSize!.height, right: 0.0)
    self.scrollView.contentInset = contentInsets
    self.scrollView.scrollIndicatorInsets = contentInsets
    self.view.endEditing(true)
    self.scrollView.isScrollEnabled = false
}

func textFieldDidBeginEditing(_ textField: UITextField){
    activeField = textField
}

func textFieldDidEndEditing(_ textField: UITextField){
    activeField = nil
}