Programs & Examples On #Path separator

File path issues in R using Windows ("Hex digits in character string" error)

replace all the \ with \\.

it's trying to escape the next character in this case the U so to insert a \ you need to insert an escaped \ which is \\

When should I use File.separator and when File.pathSeparator?

java.io.File class contains four static separator variables. For better understanding, Let's understand with the help of some code

  1. separator: Platform dependent default name-separator character as String. For windows, it’s ‘\’ and for unix it’s ‘/’
  2. separatorChar: Same as separator but it’s char
  3. pathSeparator: Platform dependent variable for path-separator. For example PATH or CLASSPATH variable list of paths separated by ‘:’ in Unix systems and ‘;’ in Windows system
  4. pathSeparatorChar: Same as pathSeparator but it’s char

Note that all of these are final variables and system dependent.

Here is the java program to print these separator variables. FileSeparator.java

import java.io.File;

public class FileSeparator {

    public static void main(String[] args) {
        System.out.println("File.separator = "+File.separator);
        System.out.println("File.separatorChar = "+File.separatorChar);
        System.out.println("File.pathSeparator = "+File.pathSeparator);
        System.out.println("File.pathSeparatorChar = "+File.pathSeparatorChar);
    }

}

Output of above program on Unix system:

File.separator = /
File.separatorChar = /
File.pathSeparator = :
File.pathSeparatorChar = :

Output of the program on Windows system:

File.separator = \
File.separatorChar = \
File.pathSeparator = ;
File.pathSeparatorChar = ;

To make our program platform independent, we should always use these separators to create file path or read any system variables like PATH, CLASSPATH.

Here is the code snippet showing how to use separators correctly.

//no platform independence, good for Unix systems
File fileUnsafe = new File("tmp/abc.txt");
//platform independent and safe to use across Unix and Windows
File fileSafe = new File("tmp"+File.separator+"abc.txt");

JavaFX "Location is required." even though it is in the same package

This problem can be caused by incorrect path to the FXML file.

If you're using absolute paths (my/package/views/view.fxml), you have to precede then with a slash:

getClass().getResource("/my/package/views/view.fxml")

You can use relative paths as well:

getClass().getResource("views/view.fxml")

rejected master -> master (non-fast-forward)

If git pull does not help, then probably you have pushed your changes (A) and after that had used git commit --amend to add some more changes (B). Therefore, git thinks that you can lose the history - it interprets B as a different commit despite it contains all changes from A.

             B
            /
        ---X---A

If nobody changes the repo after A, then you can do git push --force.

However, if there are changes after A from other person:

             B
            /
        ---X---A---C

then you must rebase that persons changes from A to B (C->D).

             B---D
            /
        ---X---A---C

or fix the problem manually. I didn't think how to do that yet.

What is the difference between task and thread?

I usually use Task to interact with Winforms and simple background worker to make it not freezing the UI. here an example when I prefer using Task

private async void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    await Task.Run(() => {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
    })
    buttonDownload.Enabled = true;
}

VS

private void buttonDownload_Click(object sender, EventArgs e)
{
    buttonDownload.Enabled = false;
    Thread t = new Thread(() =>
    {
        using (var client = new WebClient())
        {
            client.DownloadFile("http://example.com/file.mpeg", "file.mpeg");
        }
        this.Invoke((MethodInvoker)delegate()
        {
            buttonDownload.Enabled = true;
        });
    });
    t.IsBackground = true;
    t.Start();
}

the difference is you don't need to use MethodInvoker and shorter code.

Printing without newline (print 'a',) prints a space, how to remove?

WOW!!!

It's pretty long time ago

Now, In python 3.x it will be pretty easy

code:

for i in range(20):
      print('a',end='') # here end variable will clarify what you want in 
                        # end of the code

output:

aaaaaaaaaaaaaaaaaaaa 

More about print() function

print(value1,value2,value3,sep='-',end='\n',file=sys.stdout,flush=False)

Here:

value1,value2,value3

you can print multiple values using commas

sep = '-'

3 values will be separated by '-' character

you can use any character instead of that even string like sep='@' or sep='good'

end='\n'

by default print function put '\n' charater at the end of output

but you can use any character or string by changing end variale value

like end='$' or end='.' or end='Hello'

file=sys.stdout

this is a default value, system standard output

using this argument you can create a output file stream like

print("I am a Programmer", file=open("output.txt", "w"))

by this code you will create a file named output.txt where your output I am a Programmer will be stored

flush = False

It's a default value using flush=True you can forcibly flush the stream

Resolving instances with ASP.NET Core DI from within ConfigureServices

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc();

    services.AddDbContext<ConfigurationRepository>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("SqlConnectionString")));

    services.AddScoped<IConfigurationBL, ConfigurationBL>();
    services.AddScoped<IConfigurationRepository, ConfigurationRepository>();
}

Why can I not switch branches?

If you don't care about the changes that git says are outstanding, then you can do a force checkout.

git checkout -f {{insert your branch name here}}

Disable activity slide-in animation when launching new activity?

IMHO this answer here solve issue in the most elegant way..

Developer should create a style,

<style name="noAnimTheme" parent="android:Theme">
  <item name="android:windowAnimationStyle">@null</item>
</style>

then in manifest set it as theme for activity or whole application.

<activity android:name=".ui.ArticlesActivity" android:theme="@style/noAnimTheme">
</activity>

Voila! Nice and easy..

P.S. credits to original author please

How to make one Observable sequence wait for another to complete before emitting?

You can use result emitted from previous Observable thanks to mergeMap (or his alias flatMap) operator like this:

 const one = Observable.of('https://api.github.com/users');
 const two = (c) => ajax(c);//ajax from Rxjs/dom library

 one.mergeMap(two).subscribe(c => console.log(c))

How do I filter query objects by date range in Django?

You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:

start = date(2012, 12, 11)
end = date(2012, 12, 18)
new_end = end + datetime.timedelta(days=1)

ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])

As discussed previously, without doing something like this, records are ignored on the last day.

Edited to avoid the use of datetime.combine -- seems more logical to stick with date instances when comparing against a DateTimeField, instead of messing about with throwaway (and confusing) datetime objects. See further explanation in comments below.

Python: read all text file lines in loop

There's no need to check for EOF in python, simply do:

with open('t.ini') as f:
   for line in f:
       # For Python3, use print(line)
       print line
       if 'str' in line:
          break

Why the with statement:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way.

How can I fix assembly version conflicts with JSON.NET after updating NuGet package references in a new ASP.NET MVC 5 project?

I updated my package and even reinstalled it - but I was still getting the exact same error as the OP mentioned. I manually edited the referenced dll by doing the following.

I removed the newtonsoft.json.dll from my reference, then manually deleted the .dll from the bin directoy. Then i manually copied the newtonsoft.json.dll from the nuget package folder into the project bin, then added the reference by browsing to the .dll file.

Now my project builds again.

Load CSV data into MySQL in Python

using pymsql if it helps

import pymysql
import csv
db = pymysql.connect("localhost","root","12345678","data" )

cursor = db.cursor()
csv_data = csv.reader(open('test.csv'))
next(csv_data)
for row in csv_data:
    cursor.execute('INSERT INTO PM(col1,col2) VALUES(%s, %s)',row)

db.commit()
cursor.close()

How do I make a MySQL database run completely in memory?

Assuming you understand the consequences of using the MEMORY engine as mentioned in comments, and here, as well as some others you'll find by searching about (no transaction safety, locking issues, etc) - you can proceed as follows:

MEMORY tables are stored differently than InnoDB, so you'll need to use an export/import strategy. First dump each table separately to a file using SELECT * FROM tablename INTO OUTFILE 'table_filename'. Create the MEMORY database and recreate the tables you'll be using with this syntax: CREATE TABLE tablename (...) ENGINE = MEMORY;. You can then import your data using LOAD DATA INFILE 'table_filename' INTO TABLE tablename for each table.

Clicking submit button of an HTML form by a Javascript code

document.getElementById('loginSubmit').submit();

or, use the same code as the onclick handler:

changeAction('submitInput','loginForm');
document.forms['loginForm'].submit();

(Though that onclick handler is kind of stupidly-written: document.forms['loginForm'] could be replaced with this.)

Setting values of input fields with Angular 6

As an alternate you can use reactive forms. Here is an example: https://stackblitz.com/edit/angular-pqb2xx

Template

<form [formGroup]="mainForm" ng-submit="submitForm()">
  Global Price: <input type="number" formControlName="globalPrice">
  <button type="button" [disabled]="mainForm.get('globalPrice').value === null" (click)="applyPriceToAll()">Apply to all</button>
  <table border formArrayName="orderLines">
  <ng-container *ngFor="let orderLine of orderLines let i=index" [formGroupName]="i">
    <tr>
       <td>{{orderLine.time | date}}</td>
       <td>{{orderLine.quantity}}</td>
       <td><input formControlName="price" type="number"></td>
    </tr>
</ng-container>
  </table>
</form>

Component

import { Component } from '@angular/core';
import { FormGroup, FormControl, FormArray } from '@angular/forms';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular 6';
  mainForm: FormGroup;
  orderLines = [
    {price: 10, time: new Date(), quantity: 2},
    {price: 20, time: new Date(), quantity: 3},
    {price: 30, time: new Date(), quantity: 3},
    {price: 40, time: new Date(), quantity: 5}
    ]
  constructor() {
    this.mainForm = this.getForm();
  }

  getForm(): FormGroup {
    return new FormGroup({
      globalPrice: new FormControl(),
      orderLines: new FormArray(this.orderLines.map(this.getFormGroupForLine))
    })
  }

  getFormGroupForLine(orderLine: any): FormGroup {
    return new FormGroup({
      price: new FormControl(orderLine.price)
    })
  }

  applyPriceToAll() {
    const formLines = this.mainForm.get('orderLines') as FormArray;
    const globalPrice = this.mainForm.get('globalPrice').value;
    formLines.controls.forEach(control => control.get('price').setValue(globalPrice));
    // optionally recheck value and validity without emit event.
  }

  submitForm() {

  }
}

Sort columns of a dataframe by column name

Here's the obligatory dplyr answer in case somebody wants to do this with the pipe.

test %>% 
    select(sort(names(.)))

^[A-Za-Z ][A-Za-z0-9 ]* regular expression?

A lot of the answers given so far are pretty good, but you must clearly define what it is exactly that you want.

If you would like a alphabetical character followed by any number of non-white-space characters (note that it would also include numbers!) then you should use this:

^[A-Za-z]\S*$

If you would like to include only alpha-numeric characters and certain symbols, then use this:

^[A-Za-z][A-Za-z0-9!@#$%^&*]*$

Your original question looks like you are trying to include the space character as well, so you probably want something like this:

^[A-Za-z ][A-Za-z0-9!@#$%^&* ]*$

And that is my final answer!

I suggest taking some time to learn more about regular expressions. They are the greatest thing since sliced bread!

Try this syntax reference page (that site in general is very good).

How to format JSON in notepad++

Try with JSToolNpp and follow the snap like this then Plugins | JSTool | JSFormat.

enter image description here

How to move git repository with all branches from bitbucket to github?

Here are the steps to move a private Git repository:

Step 1: Create Github repository

First, create a new private repository on Github.com. It’s important to keep the repository empty, e.g. don’t check option Initialize this repository with a README when creating the repository.

Step 2: Move existing content

Next, we need to fill the Github repository with the content from our Bitbucket repository:

  1. Check out the existing repository from Bitbucket:
    $ git clone https://[email protected]/USER/PROJECT.git
  1. Add the new Github repository as upstream remote of the repository checked out from Bitbucket:
    $ cd PROJECT
    $ git remote add upstream https://github.com:USER/PROJECT.git
  1. Push all branches (below: just master) and tags to the Github repository:
    $ git push upstream master
    $ git push --tags upstream

Step 3: Clean up old repository

Finally, we need to ensure that developers don’t get confused by having two repositories for the same project. Here is how to delete the Bitbucket repository:

  1. Double-check that the Github repository has all content

  2. Go to the web interface of the old Bitbucket repository

  3. Select menu option Setting > Delete repository

  4. Add the URL of the new Github repository as redirect URL

With that, the repository completely settled into its new home at Github. Let all the developers know!

How do I check if file exists in Makefile so I can delete it?

The problem is when you split your command over multiple lines. So, you can either use the \ at the end of lines for continuation as above or you can get everything on one line with the && operator in bash.

Then you can use a test command to test if the file does exist, e.g.:

test -f myApp && echo File does exist

-f file True if file exists and is a regular file.

-s file True if file exists and has a size greater than zero.

or does not:

test -f myApp || echo File does not exist
test ! -f myApp && echo File does not exist

The test is equivalent to [ command.

[ -f myApp ] && rm myApp   # remove myApp if it exists

and it would work as in your original example.

See: help [ or help test for further syntax.

java.lang.RuntimeException: Unable to instantiate activity ComponentInfo

Ok, I am fairly experienced on the iPhone but new to android. I got this issue when I had:

Button infoButton = (Button)findViewById(R.id.InfoButton);

this line of code above:

@Override
public void onCreate (Bundle savedInstanceState) {
}

May be I am sleep deprived :P

Strange problem with Subversion - "File already exists" when trying to recreate a directory that USED to be in my repository

  1. rename the new path to temp
  2. revert the new path (not temp!) so svn does not try to commit it
  3. commit the rest of your changes
  4. copy the path inside the repository: svn copy -m "copied path" -r
  5. update your working copy
  6. mv all files from temp to the new path, which comes from the update
  7. commit your local changes since revision
  8. Have a nice Day including history ;-)

Is there any way to return HTML in a PHP function? (without building the return value as a string)

Another way to do is is to use file_get_contents() and have a template HTML page

TEMPLATE PAGE

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head><title>$title</title></head>
<body>$content</body>
</html>

PHP Function

function YOURFUNCTIONNAME($url){

$html_string = file_get_contents($url);
return $html_string;

}

INSERT INTO TABLE from comma separated varchar-list

Something like this should work:

INSERT INTO #IMEIS (imei) VALUES ('val1'), ('val2'), ...

UPDATE:

Apparently this syntax is only available starting on SQL Server 2008.

How to set TextView textStyle such as bold, italic

try this to set your TextView style by java code

txt1.setTypeface(null,Typeface.BOLD_ITALIC);

How to Bootstrap navbar static to fixed on scroll?

Set on nav

style="position:fixed; width:100%;"

Set cellpadding and cellspacing in CSS?

I suggest this and all the cells for the particular table are effected.

table.tbl_classname td, th {
    padding: 5px 5px 5px 4px;
 }

Where can I find Android's default icons?

you can use

android.R.drawable.xxx

(use autocomplete to see whats in there)

Or download the stuff from http://developer.android.com/design/downloads/index.html

Best practice when adding whitespace in JSX

Because &nbsp causes you to have non-breaking spaces, you should only use it where necessary. In most cases, this will have unintended side effects.

Older versions of React, I believe all those before v14, would automatically insert <span> </span> when you had a newline inside of a tag.

While they no longer do this, that's a safe way to handle this in your own code. Unless you have styling that specifically targets span (bad practice in general), then this is the safest route.

Per your example, you can put them on a single line together as it's pretty short. In longer-line scenarios, this is how you should probably do it:

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    <span> </span>
    So much more text in this box that it really needs to be on another line.
  </div>

This method is also safe against auto-trimming text editors.

The other method is using {' '} which doesn't insert random HTML tags. This could be more useful when styling, highlighting elements, and removes clutter from the DOM. If you don't need backwards compatibility with React v14 or earlier, this should be your preferred method.

  <div className="top-element-formatting">
    Hello <span className="second-word-formatting">World!</span>
    {' '}
    So much more text in this box that it really needs to be on another line.
  </div>

Error: could not find function ... in R

This error can occur even if the name of the function is valid if some mandatory arguments are missing (i.e you did not provide enough arguments).
I got this in an Rcpp context, where I wrote a C++ function with optionnal arguments, and did not provided those arguments in R. It appeared that optionnal arguments from the C++ were seen as mandatory by R. As a result, R could not find a matching function for the correct name but an incorrect number of arguments.

Rcpp Function : SEXP RcppFunction(arg1, arg2=0) {}
R Calls :
RcppFunction(0) raises the error
RcppFunction(0, 0) does not

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

How to change a string into uppercase

>>> s = 'sdsd'
>>> s.upper()
'SDSD'

See String Methods.

Zsh: Conda/Pip installs command not found

For Linux

  1. Open .bashrc
  2. Copy the code for conda initialize and paste it to .zshrc file
  3. Finally run source .zshrc

Removing spaces from a variable input using PowerShell 4.0

If the string is

$STR = 'HELLO WORLD'

and you want to remove the empty space between 'HELLO' and 'WORLD'

$STR.replace(' ','')

replace takes the string and replaces white space with empty string (of length 0), in other words the white space is just deleted.

Invoke native date picker from web-app on iOS/Android

Since some years some devices support <input type="date"> but others don't, so one needs to be careful. Here are some observations from 2012, which still might be valid today:

  • One can detect if type="date" is supported by setting that attribute and then reading back its value. Browsers/devices that don't support it will ignore setting the type to date and return text when reading back that attribute. Alternatively, Modernizr can be used for detection. Beware that it's not enough to check for some Android version; like the Samsung Galaxy S2 on Android 4.0.3 does support type="date", but the Google/Samsung Nexus S on the more recent Android 4.0.4 does not.

  • When presetting the date for the native date picker, be sure to use a format the device recognizes. When not doing that, devices might silently reject it, leaving one with an empty input field when trying to show an existing value. Like using the date picker on a Galaxy S2 running Android 4.0.3 might itself set the <input> to 2012-6-1 for June 1st. However, when setting the value from JavaScript, it needs leading zeroes: 2012-06-01.

  • When using things like Cordova (PhoneGap) to display the native date picker on devices that don't support type="date":

    • Be sure to properly detect built-in support. Like in 2012 on the Galaxy S2 running Android 4.0.3, erroneously also using the Cordova Android plugin would result in showing the date picker twice in a row: once again after clicking "set" in its first occurrence.

    • When there's multiple inputs on the same page, some devices show "previous" and "next" to get into another form field. On iOS 4, this does not trigger the onclick handler and hence gives the user a regular input. Using onfocus to trigger the plugin seemed to work better.

    • On iOS 4, using onclick or onfocus to trigger the 2012 iOS plugin first made the regular keyboard show, after which the date picker was placed on top of that. Next, after using the date picker, one still needed to close the regular keyboard. Using $(this).blur() to remove focus before the date picker was shown helped for iOS 4 and did not affect other devices I tested. But it introduced some quick flashing of the keyboard on iOS, and things could be even more confusing on first usage as then the date picker was slower. One could fully disable the regular keyboard by making the input readonly if one were using the plugin, but that disabled the "previous" and "next" buttons when typing in other inputs on the same screen. It also seems the iOS 4 plugin did not make the native date picker show "cancel" or "clear".

    • On an iOS 4 iPad (simulator), in 2012 the Cordova plugin did not seem to render correctly, basically not giving the user any option to enter or change a date. (Maybe iOS 4 doesn't render its native date picker nicely on top of a web view, or maybe my web view's CSS styling has some effect, and surely this might be different on a real device: please comment or edit!)

    • Though, again in 2012, the Android date picker plugin tried to use the same JavaScript API as the iOS plugin, and its example used allowOldDates, the Android version actually did not support that. Also, it returned the new date as 2012/7/2 while the iOS version returned Mon Jul 02 2012 00:00:00 GMT+0200 (CEST).

  • Even when <input type="date"> is supported, things might look messy:

    • iOS 5 nicely displays 2012-06-01 in a localized format, like 1 Jun. 2012 or June 1, 2012 (and even updates that immediately while still operating the date picker). However, the Galaxy S2 running Android 4.0.3 shows the ugly 2012-6-1 or 2012-06-01, no matter which locale is used.

    • iOS 5 on an iPad (simulator) does not hide the keyboard when that is already visible when touching the date input, or when using "previous" or "next" in another input. It then simultaneously shows the date picker below the input and the keyboard at the bottom, and seems to allow any input from both. However, though it does change the visible value, the keyboard input is actually ignored. (Shown when reading back the value, or when invoking the date picker again.) When the keyboard was not yet shown, then touching the date input only shows the date picker, not the keyboard. (This might be different on a real device, please comment or edit!)

    • Devices might show a cursor in the input field, and a long press might trigger the clipboard options, possibly showing the regular keyboard too. When clicking, some devices might even show the regular keyboard for a split second, before changing to show the date picker.

Use a.any() or a.all()

You comment:

valeur is a vector equal to [ 0. 1. 2. 3.] I am interested in each single term. For the part below 0.6, then return "this works"....

If you are interested in each term, then write the code so it deals with each. For example.

for b in valeur<=0.6:
    if b:
        print ("this works")
    else:   
        print ("valeur is too high")

This will write 2 lines.

The error is produced by numpy code when you try to use it a context that expects a single, scalar, value. if b:... can only do one thing. It does not, by itself, iterate through the elements of b doing a different thing for each.

You could also cast that iteration as list comprehension, e.g.

['yes' if b else 'no' for b in np.array([True, False, True])]

Pass data to layout that are common to all pages

You can use like this:

 @{ 
    ApplicationDbContext db = new ApplicationDbContext();
    IEnumerable<YourModel> bd_recent = db.YourModel.Where(m => m.Pin == true).OrderByDescending(m=>m.ID).Select(m => m);
}
<div class="col-md-12">
    <div class="panel panel-default">
        <div class="panel-body">
            <div class="baner1">
                <h3 class="bb-hred">Recent Posts</h3>
                @foreach(var item in bd_recent)
                {
                    <a href="/BaiDangs/BaiDangChiTiet/@item.ID">@item.Name</a>
                }
            </div>
        </div>
    </div>
</div>

Scheduling recurring task in Android

I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.

 import java.text.SimpleDateFormat;
 import java.util.Calendar;
 import java.util.Timer;
 import java.util.TimerTask;

 import android.os.Bundle;
 import android.view.View;
 import android.view.View.OnClickListener;
 import android.widget.Button;
 import android.widget.CheckBox;
 import android.widget.TextView;
 import android.app.Activity;
 import android.content.Intent;

 public class MainActivity extends Activity {

     CheckBox optSingleShot;
     Button btnStart, btnCancel;
     TextView textCounter;

     Timer timer;
     MyTimerTask myTimerTask;

     int tobeShown = 0  ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    optSingleShot = (CheckBox)findViewById(R.id.singleshot);
    btnStart = (Button)findViewById(R.id.start);
    btnCancel = (Button)findViewById(R.id.cancel);
    textCounter = (TextView)findViewById(R.id.counter);
    tobeShown = 1;

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }

    btnStart.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {


            Intent i = new Intent(MainActivity.this, ActivityB.class);
            startActivity(i);

            /*if(timer != null){
                timer.cancel();
            }

            //re-schedule timer here
            //otherwise, IllegalStateException of
            //"TimerTask is scheduled already" 
            //will be thrown
            timer = new Timer();
            myTimerTask = new MyTimerTask();

            if(optSingleShot.isChecked()){
                //singleshot delay 1000 ms
                timer.schedule(myTimerTask, 1000);
            }else{
                //delay 1000ms, repeat in 5000ms
                timer.schedule(myTimerTask, 1000, 1000);
            }*/
        }});

    btnCancel.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View v) {
            if (timer!=null){
                timer.cancel();
                timer = null;
            }
        }
    });

}

@Override
protected void onResume() {
    super.onResume();

    if(timer != null){
        timer.cancel();
    }

    //re-schedule timer here
    //otherwise, IllegalStateException of
    //"TimerTask is scheduled already" 
    //will be thrown
    timer = new Timer();
    myTimerTask = new MyTimerTask();

    if(optSingleShot.isChecked()){
        //singleshot delay 1000 ms
        timer.schedule(myTimerTask, 1000);
    }else{
        //delay 1000ms, repeat in 5000ms
        timer.schedule(myTimerTask, 1000, 1000);
    }
}


@Override
protected void onPause() {
    super.onPause();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

@Override
protected void onStop() {
    super.onStop();

    if (timer!=null){
        timer.cancel();
        timer = null;
    }

}

class MyTimerTask extends TimerTask {

    @Override
    public void run() {

        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat simpleDateFormat = 
                new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
        final String strDate = simpleDateFormat.format(calendar.getTime());

        runOnUiThread(new Runnable(){

            @Override
            public void run() {
                textCounter.setText(strDate);
            }});
    }
}

}

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

Using Spring 3 autowire in a standalone Java application

A nice solution would be to do following,

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class SpringContext implements ApplicationContextAware {

private static ApplicationContext context;

/**
 * Returns the Spring managed bean instance of the given class type if it exists.
 * Returns null otherwise.
 * @param beanClass
 * @return
 */
public static <T extends Object> T getBean(Class<T> beanClass) {
    return context.getBean(beanClass);
}

@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {

    // store ApplicationContext reference to access required beans later on
    SpringContext.context = context;
}
}

Then you can use it like:

YourClass yourClass = SpringContext.getBean(YourClass.class);

I found this very nice solution in the following website: https://confluence.jaytaala.com/pages/viewpage.action?pageId=18579463

How do I run a bat file in the background from another bat file?

Other than foreground/background term. Another way to hide running window is via vbscript, if is is still available in your system.

DIM objShell
set objShell=wscript.createObject("wscript.shell")
iReturn=objShell.Run("yourcommand.exe", 0, TRUE)

name it as sth.vbs and call it from bat, put in sheduled task, etc. PersonallyI'll disable vbs with no haste at any Windows system I manage :)

Jquery validation plugin - TypeError: $(...).validate is not a function

I had the same problem. I am using jquery-validation as an npm module and the fix for me was to require the module at the start of my js file:

require('jquery-validation');

SQL Inner join more than two tables

The right syntax is like:

SELECT * FROM table1 INNER JOIN table2 ON table1.primaryKey = table2.ForeignKey
INNER JOIN table3 ON table3.primaryKey = table2.ForeignKey

Orthe last line joining table3 on table1 like:

ON table3.ForeignKey= table1.PrimaryKey

How can I tell which button was clicked in a PHP form submit?

All you need to give the name attribute to the each button. And you need to address each button press from the PHP script. But be careful to give each button a unique name. Because the PHP script only take care of the name most of the time

<input type="submit" name="Submit_this" id="This" />

What is the difference between "Rollback..." and "Back Out Submitted Changelist #####" in Perforce P4V

At its simplest, the difference is one of plurality:

  • Backout backs out of a single changelist (whether the most recent or not). i.e. it undoes a single changelist.
  • Rollback rolls back changes as much as it needs to in order to get to a previous changelist. i.e. it undoes multiple changelists.

I used to forget which one is which and end up having to look it up many times. To fix this problem, imagine rolling back as several rotations then hopefully the fact that rollback is plural will help you (and me!) remember which one is which. Backout sounds 'less plural' than rollback to me. Imagine backing out of a single parking space.

So, the mnemonic is:

  • Rollback → multiple rotations
  • Backout → back out of a single car parking space

I hope this helps!

Change navbar color in Twitter Bootstrap

It took me a while, but I discovered that including the following was what made it possible to change the navbar color:

.navbar{ 
    background-image: none;
}

How to use FormData in react-native?

You can use react-native-image-picker and axios (form-data)

uploadS3 = (path) => {
    var data = new FormData();

    data.append('files',
        { uri: path, name: 'image.jpg', type: 'image/jpeg' }
    );

    var config = {
        method: 'post',
        url: YOUR_URL,
        headers: {
            Accept: "application/json",
            "Content-Type": "multipart/form-data",
        },
        data: data,
    };

    axios(config)
        .then((response) => {
            console.log(JSON.stringify(response.data));
        })
        .catch((error) => {
            console.log(error);
        });
}

react-native-image-picker

selectPhotoTapped() {
    const options = {
        quality: 1.0,
        maxWidth: 500,
        maxHeight: 500,
        storageOptions: {
            skipBackup: true,
        },
    };

    ImagePicker.showImagePicker(options, response => {
        //console.log('Response = ', response);

        if (response.didCancel) {
            //console.log('User cancelled photo picker');
        } else if (response.error) {
            //console.log('ImagePicker Error: ', response.error);
        } else if (response.customButton) {
            //console.log('User tapped custom button: ', response.customButton);
        } else {
            let source = { uri: response.uri };
             
            // Call Upload Function
            this.uploadS3(source.uri)

            // You can also display the image using data:
            // let source = { uri: 'data:image/jpeg;base64,' + response.data };
            this.setState({
                avatarSource: source,
            });
            // this.imageUpload(source);
        }
    });
}

Best way to pass parameters to jQuery's .load()

In the first case, the data are passed to the script via GET, in the second via POST.

http://docs.jquery.com/Ajax/load#urldatacallback

I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.

Equivalent of varchar(max) in MySQL?

For Sql Server

alter table prg_ar_report_colors add Text_Color_Code VARCHAR(max);

For MySql

alter table prg_ar_report_colors add Text_Color_Code longtext;

For Oracle

alter table prg_ar_report_colors add Text_Color_Code CLOB;

How to find which columns contain any NaN value in Pandas dataframe

In datasets having large number of columns its even better to see how many columns contain null values and how many don't.

print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))

print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))

print("Total no. of columns in the dataframe")
print(len(df.columns))

For example in my dataframe it contained 82 columns, of which 19 contained at least one null value.

Further you can also automatically remove cols and rows depending on which has more null values
Here is the code which does this intelligently:

df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)

Note: Above code removes all of your null values. If you want null values, process them before.

how to set windows service username and password through commandline

This works:

sc.exe config "[servicename]" obj= "[.\username]" password= "[password]"

Where each of the [bracketed] items are replaced with the true arguments. (Keep the quotes, but don't keep the brackets.)

Just keep in mind that:

  • The spacing in the above example matters. obj= "foo" is correct; obj="foo" is not.
  • '.' is an alias to the local machine, you can specify a domain there (or your local computer name) if you wish.
  • Passwords aren't validated until the service is started
  • Quote your parameters, as above. You can sometimes get by without quotes, but good luck.

Laravel 5 How to switch from Production mode

What you could also have a look at is the exposed method Application->loadEnvironmentFrom($file)

I needed one application to run on multiple subdomains. So in bootstrap/app.php I added something like:

$envFile = '.env';
// change $envFile conditionally here
$app->loadEnvironmentFrom($envFile);

Display loading image while post with ajax

$.ajax(
{
    type: 'post',
    url: 'mail.php',
    data: form.serialize(),
    beforeSend: function()
    {
        $('.content').html('loading...');
    },
    success: function(data)
    {
        $('.content').html(data);
    },
    error: function()
    {
        $('.content').html('error');
    }
});

have fun playing arround!

if you should have quick loading times which prevent te loading showing, you can add a timeout of some sort.

Understanding [TCP ACKed unseen segment] [TCP Previous segment not captured]

Another cause of "TCP ACKed Unseen" is the number of packets that may get dropped in a capture. If I run an unfiltered capture for all traffic on a busy interface, I will sometimes see a large number of 'dropped' packets after stopping tshark.

On the last capture I did when I saw this, I had 2893204 packets captured, but once I hit Ctrl-C, I got a 87581 packets dropped message. Thats a 3% loss, so when wireshark opens the capture, its likely to be missing packets and report "unseen" packets.

As I mentioned, I captured a really busy interface with no capture filter, so tshark had to sort all packets, when I use a capture filter to remove some of the noise, I no longer get the error.

Checking out Git tag leads to "detached HEAD state"

Okay, first a few terms slightly oversimplified.

In git, a tag (like many other things) is what's called a treeish. It's a way of referring to a point in in the history of the project. Treeishes can be a tag, a commit, a date specifier, an ordinal specifier or many other things.

Now a branch is just like a tag but is movable. When you are "on" a branch and make a commit, the branch is moved to the new commit you made indicating it's current position.

Your HEAD is pointer to a branch which is considered "current". Usually when you clone a repository, HEAD will point to master which in turn will point to a commit. When you then do something like git checkout experimental, you switch the HEAD to point to the experimental branch which might point to a different commit.

Now the explanation.

When you do a git checkout v2.0, you are switching to a commit that is not pointed to by a branch. The HEAD is now "detached" and not pointing to a branch. If you decide to make a commit now (as you may), there's no branch pointer to update to track this commit. Switching back to another commit will make you lose this new commit you've made. That's what the message is telling you.

Usually, what you can do is to say git checkout -b v2.0-fixes v2.0. This will create a new branch pointer at the commit pointed to by the treeish v2.0 (a tag in this case) and then shift your HEAD to point to that. Now, if you make commits, it will be possible to track them (using the v2.0-fixes branch) and you can work like you usually would. There's nothing "wrong" with what you've done especially if you just want to take a look at the v2.0 code. If however, you want to make any alterations there which you want to track, you'll need a branch.

You should spend some time understanding the whole DAG model of git. It's surprisingly simple and makes all the commands quite clear.

Extracting an attribute value with beautifulsoup

You could try to use the new powerful package called requests_html:

from requests_html import HTMLSession
session = HTMLSession()

r = session.get("https://www.bbc.co.uk/news/technology-54448223")
date = r.html.find('time', first = True) # finding a "tag" called "time"
print(date)  # you will have: <Element 'time' datetime='2020-10-07T11:41:22.000Z'>
# To get the text inside the "datetime" attribute use:
print(date.attrs['datetime']) # you will get '2020-10-07T11:41:22.000Z'

Caused By: java.lang.NoClassDefFoundError: org/apache/log4j/Logger

Had the same problem, it was indeed caused by weblogic stupidly using its own opensaml implementation. To solve it, you have to tell it to load classes from WEB-INF/lib for this package in weblogic.xml:

    <prefer-application-packages>
        <package-name>org.opensaml.*</package-name>
    </prefer-application-packages>

maybe <prefer-web-inf-classes>true</prefer-web-inf-classes> would work too.

Get IP address of visitors using Flask for Python

httpbin.org uses this method:

return jsonify(origin=request.headers.get('X-Forwarded-For', request.remote_addr))

Display Adobe pdf inside a div

I think its not working, because you z-index property not applied on pdf(any outside object). So when you add any control in PDF view boundary,its appear behind of pdf view.

Generating Random Number In Each Row In Oracle Query

At first I thought that this would work:

select DBMS_Random.Value(1,9) output
from   ...

However, this does not generate an even distribution of output values:

select output,
       count(*)
from   (
       select round(dbms_random.value(1,9)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   62423
2   125302
3   125038
4   125207
5   124892
6   124235
7   124832
8   125514
9   62557

The reasons are pretty obvious I think.

I'd suggest using something like:

floor(dbms_random.value(1,10))

Hence:

select output,
       count(*)
from   (
       select floor(dbms_random.value(1,10)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   111038
2   110912
3   111155
4   111125
5   111084
6   111328
7   110873
8   111532
9   110953

Why do I have ORA-00904 even when the column is present?

This happened to me when I accidentally defined two entities with the same persistent database table. In one of the tables the column in question did exist, in the other not. When attempting to persist an object (of the type referring to the wrong underlying database table), this error occurred.

How do you kill all current connections to a SQL Server 2005 database?

I'm using SQL Server 2008 R2, my DB was already set for single user and there was a connection that restricted any action on the database. Thus the recommended SQLMenace's solution responded with error. Here is one that worked in my case.

Nginx location priority

From the HTTP core module docs:

  1. Directives with the "=" prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the "^~" prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

Example from the documentation:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

If it's still confusing, here's a longer explanation.

HTML 5 video recording and storing a stream

RecordRTC: WebRTC audio/video recording

https://github.com/muaz-khan/WebRTC-Experiment/tree/master/RecordRTC

  • Audio recording both for Chrome and Firefox
  • Video/Gif recording for Chrome; (Firefox has a little bit issues, will be recovered soon)

Demo : https://www.webrtc-experiment.com/RecordRTC/


Creating .webm video from getUserMedia()

http://ericbidelman.tumblr.com/post/31486670538/creating-webm-video-from-getusermedia

Demo : http://html5-demos.appspot.com/static/getusermedia/record-user-webm.html


Capturing Audio & Video in HTML5

http://www.html5rocks.com/en/tutorials/getusermedia/intro/

How can I send cookies using PHP curl in addition to CURLOPT_COOKIEFILE?

I think the only cookie you need is JSESSIONID=xxx..

Also NEVER share your cookies, becasuse someone may access your personal data that way. Specially when the cookies are session. These cookies will stop working once you logout the site.

What are the differences between struct and class in C++?

It's just a convention. Structs can be created to hold simple data but later evolve time with the addition of member functions and constructors. On the other hand it's unusual to see anything other than public: access in a struct.

REST response code for invalid data

I would recommend 422. It's not part of the main HTTP spec, but it is defined by a public standard (WebDAV) and it should be treated by browsers the same as any other 4xx status code.

From RFC 4918:

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.

How to rotate a 3D object on axis three.js?

In Three.js R59, object.rotation.setEulerFromRotationMatrix(object.matrix); has been changed to object.rotation.setFromRotationMatrix(object.matrix);

3js is changing so rapidly :D

How can I put strings in an array, split by new line?

Picked this up in the php docs:

<?php
  // split the phrase by any number of commas or space characters,
  // which include " ", \r, \t, \n and \f

  $keywords = preg_split("/[\s,]+/", "hypertext language, programming");
  print_r($keywords);
?>

Drop-down box dependent on the option selected in another drop-down box

    function dropdownlist(listindex)
    {
         document.getElementById("ddlCity").options.length = 0;
         switch (listindex) 
         {
             case "Karnataka":
                     document.getElementById("ddlCity").options[0] = new Option("--select--", "");
                     document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
                     document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
                     document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
                     document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");

                 break;

             case "Tamilnadu":
                 document.getElementById("ddlCity").options[0] = new Option("--select--", "");
                 document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
                 document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");


                 break;
         }

    }

* State: --Select-- Karnataka Tamilnadu Andra pradesh Telngana

    <div>
        <p>

            <label id="lblCt">
            <span class="red">*</span>
                City:</label>
            <select id="ddlCity">
               <!-- <option>--Select--</option>
                <option value="1">Dharawad</option>
                <option value="2">Belgum</option>
                <option value="3">Bagalkot</option>
                <option value="4">Haveri</option>
                <option>Hydrabadh</option>
                <option>Vijat vada</option>-->
            </select>
            <label id="lblCity"></label>
        </p>
    </div>

"application blocked by security settings" prevent applets running using oracle SE 7 update 51 on firefox on Linux mint

The application that you are running is blocked because the application does not comply with security guidelines implemented in Java 7 Update 51

How to $watch multiple variable change in angular

No one has mentioned the obvious:

var myCallback = function() { console.log("name or age changed"); };
$scope.$watch("name", myCallback);
$scope.$watch("age", myCallback);

This might mean a little less polling. If you watch both name + age (for this) and name (elsewhere) then I assume Angular will effectively look at name twice to see if it's dirty.

It's arguably more readable to use the callback by name instead of inlining it. Especially if you can give it a better name than in my example.

And you can watch the values in different ways if you need to:

$scope.$watch("buyers", myCallback, true);
$scope.$watchCollection("sellers", myCallback);

$watchGroup is nice if you can use it, but as far as I can tell, it doesn't let you watch the group members as a collection or with object equality.

If you need the old and new values of both expressions inside one and the same callback function call, then perhaps some of the other proposed solutions are more convenient.

Paramiko's SSHClient with SFTP

If you have a SSHClient, you can also use open_sftp():

import paramiko


# lets say you have SSH client...
client = paramiko.SSHClient()

sftp = client.open_sftp()

# then you can use upload & download as shown above
...

scipy.misc module has no attribute imread?

The solution that work for me in python 3.6 is the following

py -m pip install Pillow

Android View shadow

Create card_background.xml in the res/drawable folder with the following code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">

<item>
    <shape android:shape="rectangle">
        <solid android:color="#BDBDBD"/>
        <corners android:radius="5dp"/>
    </shape>
</item>

<item
    android:left="0dp"
    android:right="0dp"
    android:top="0dp"
    android:bottom="2dp">
    <shape android:shape="rectangle">
        <solid android:color="#ffffff"/>
        <corners android:radius="5dp"/>
    </shape>
</item>
</layer-list>

Then add the following code to the element to which you want the card layout

android:background="@drawable/card_background"

the following line defines the color of the shadow for the card

<solid android:color="#BDBDBD"/>

How to solve "Connection reset by peer: socket write error"?

The socket has been closed by the client (browser).

A bug in your code:

byte[] outputByte=new byte[4096];
while(in.read(outputByte,0,4096)!=-1){
   output.write(outputByte,0,4096);
}

The last packet read, then write may have a length < 4096, so I suggest:

byte[] outputByte=new byte[4096];
int len;
while(( len = in.read(outputByte, 0, 4096 )) > 0 ) {
   output.write( outputByte, 0, len );
}

It's not your question, but it's my answer... ;-)

C# get string from textbox

I show you this with an example:

string userName= textBox1.text;

and then use it as you wish

How to generate a core dump in Linux on a segmentation fault?

Better to turn on core dump programmatically using system call setrlimit.

example:

#include <sys/resource.h>

bool enable_core_dump(){    
    struct rlimit corelim;

    corelim.rlim_cur = RLIM_INFINITY;
    corelim.rlim_max = RLIM_INFINITY;

    return (0 == setrlimit(RLIMIT_CORE, &corelim));
}

How to find a user's home directory on linux or unix?

Can you parse /etc/passwd?

e.g.:

 cat /etc/passwd | awk -F: '{printf "User %s Home %s\n",  $1, $6}'

How to compare two date values with jQuery

var startDt=document.getElementById("startDateId").value;
var endDt=document.getElementById("endDateId").value;

if( (new Date(startDt).getTime() > new Date(endDt).getTime()))
{
    ----------------------------------
}

Temporarily change current working directory in bash to run a command

bash has a builtin

pushd SOME_PATH
run_stuff
...
...
popd 

Android Studio doesn't recognize my device

If you have Mi Device than you need to enable this two option after enabling Developer Mode.

  1. USB Debugging (Enable = True)
  2. Install via USB (Enable = True)

See this screenshot.

enter image description here

How to find out which JavaScript events fired?

You can use getEventListeners in your Google Chrome developer console.

getEventListeners(object) returns the event listeners registered on the specified object.

getEventListeners(document.querySelector('option[value=Closed]'));

Creating and Naming Worksheet in Excel VBA

Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.

A better way to do this is to pop up a dialog box and get the name you wish to use.

Converting Select results into Insert script - SQL Server

SSMS Toolpack (which is FREE as in beer) has a variety of great features - including generating INSERT statements from tables.

Update: for SQL Server Management Studio 2012 (and newer), SSMS Toolpack is no longer free, but requires a modest licensing fee.

UDP vs TCP, how much faster is it?

with loss tolerant

Do you mean "with loss tolerance" ?

Basically, UDP is not "loss tolerant". You can send 100 packets to someone, and they might only get 95 of those packets, and some might be in the wrong order.

For things like video streaming, and multiplayer gaming, where it is better to miss a packet than to delay all the other packets behind it, this is the obvious choice

For most other things though, a missing or 'rearranged' packet is critical. You'd have to write some extra code to run on top of UDP to retry if things got missed, and enforce correct order. This would add a small bit of overhead in certain places.

Thankfully, some very very smart people have done this, and they called it TCP.

Think of it this way: If a packet goes missing, would you rather just get the next packet as quickly as possible and continue (use UDP), or do you actually need that missing data (use TCP). The overhead won't matter unless you're in a really edge-case scenario.

Get screen width and height in Android

Two steps. First, extend Activity class

class Example extends Activity

Second: Use this code

 DisplayMetrics displayMetrics = new DisplayMetrics();
 WindowManager windowmanager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
 windowmanager.getDefaultDisplay().getMetrics(displayMetrics);
 int deviceWidth = displayMetrics.widthPixels;
 int deviceHeight = displayMetrics.heightPixels;

JavaScript single line 'if' statement - best syntax, this alternative?

I've seen the short-circuiting behaviour of the && operator used to achieve this, although people who are not accustomed to this may find it hard to read or even call it an anti-pattern:

lemons && document.write("foo gave me a bar");  

Personally, I'll often use single-line if without brackets, like this:

if (lemons) document.write("foo gave me a bar");

If I need to add more statements in, I'll put the statements on the next line and add brackets. Since my IDE does automatic indentation, the maintainability objections to this practice are moot.

Android, How can I Convert String to Date?

It could be a good idea to be careful with the Locale upon which c.getTime().toString(); depends.

One idea is to store the time in seconds (e.g. UNIX time). As an int you can easily compare it, and then you just convert it to string when displaying it to the user.

Android: Cancel Async Task

From SDK:

Cancelling a task

A task can be cancelled at any time by invoking cancel(boolean). Invoking this method will cause subsequent calls to isCancelled() to return true.

After invoking this method, onCancelled(Object), instead of onPostExecute(Object) will be invoked after doInBackground(Object[]) returns.

To ensure that a task is cancelled as quickly as possible, you should always check the return value of isCancelled() periodically from doInBackground(Object[]), if possible (inside a loop for instance.)

So your code is right for dialog listener:

uploadingDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
    public void onCancel(DialogInterface dialog) {
        myTask.cancel(true);
        //finish();
    }
});

Now, as I have mentioned earlier from SDK, you have to check whether the task is cancelled or not, for that you have to check isCancelled() inside the onPreExecute() method.

For example:

if (isCancelled()) 
    break;
else
{
   // do your work here
}

Get current working directory in a Qt application

Have you tried QCoreApplication::applicationDirPath()

qDebug() << "App path : " << qApp->applicationDirPath();

CodeIgniter Active Record not equal

$this->db->where('emailsToCampaigns.campaignId !=' , $campaignId);

This should work (which you have tried)

To debug you might place this code just after you execute your query to see what exact SQL it is producing, this might give you clues, you might add that to the question to allow for further help.

$this->db->get();              // your query executing

echo '<pre>';                  // to preserve formatting
die($this->db->last_query());  // halt execution and print last ran query.

A transport-level error has occurred when receiving results from the server

I faced the same issue recently, but i was not able to get answer in google. So thought of sharing it here, so that it can help someone in future.

Error:

While executing query the query will provide few output then it will throw below error.

"Transport level error has occurred when receiving output from server(TCP:provider,error:0- specified network name is no longer available"

Solution:

  1. Check the provider of that linked server
  2. In that provider properties ,Enable "Allow inprocess" option for that particular provider to fix the issue.

Concatenate rows of two dataframes in pandas

call concat and pass param axis=1 to concatenate column-wise:

In [5]:

pd.concat([df_a,df_b], axis=1)
Out[5]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

There is a useful guide to the various methods of merging, joining and concatenating online.

For example, as you have no clashing columns you can merge and use the indices as they have the same number of rows:

In [6]:

df_a.merge(df_b, left_index=True, right_index=True)
Out[6]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

And for the same reasons as above a simple join works too:

In [7]:

df_a.join(df_b)
Out[7]:
        AAseq Biorep  Techrep Treatment     mz      AAseq1 Biorep1  Techrep1  \
0  ELVISLIVES      A        1         C  500.0  ELVISLIVES       A         1   
1  ELVISLIVES      A        1         C  500.5  ELVISLIVES       A         1   
2  ELVISLIVES      A        1         C  501.0  ELVISLIVES       A         1   

  Treatment1  inte1  
0          C   1100  
1          C   1050  
2          C   1010  

Make a directory and copy a file

Use the FileSystemObject object, namely, its CreateFolder and CopyFile methods. Basically, this is what your script will look like:

Dim oFSO
Set oFSO = CreateObject("Scripting.FileSystemObject")

' Create a new folder
oFSO.CreateFolder "C:\MyFolder"

' Copy a file into the new folder
' Note that the destination folder path must end with a path separator (\)
oFSO.CopyFile "\\server\folder\file.ext", "C:\MyFolder\"

You may also want to add additional logic, like checking whether the folder you want to create already exists (because CreateFolder raises an error in this case) or specifying whether or not to overwrite the file being copied. So, you can end up with this:

Const strFolder = "C:\MyFolder\", strFile = "\\server\folder\file.ext"
Const Overwrite = True
Dim oFSO

Set oFSO = CreateObject("Scripting.FileSystemObject")

If Not oFSO.FolderExists(strFolder) Then
  oFSO.CreateFolder strFolder
End If

oFSO.CopyFile strFile, strFolder, Overwrite

Change font-weight of FontAwesome icons?

.star-light::after {
    content: "\f005";
    font-family: "FontAwesome";
    font-size: 3.2rem;
    color: #fff;
    font-weight: 900;
    background-color: red;
}

Axios get in url works but with second parameter as object it doesn't

axios.get accepts a request config as the second parameter (not query string params).

You can use the params config option to set query string params as follows:

axios.get('/api', {
  params: {
    foo: 'bar'
  }
});

Best way to iterate through a Perl array

  • In terms of speed: #1 and #4, but not by much in most instances.

    You could write a benchmark to confirm, but I suspect you'll find #1 and #4 to be slightly faster because the iteration work is done in C instead of Perl, and no needless copying of the array elements occurs. ($_ is aliased to the element in #1, but #2 and #3 actually copy the scalars from the array.)

    #5 might be similar.

  • In terms memory usage: They're all the same except for #5.

    for (@a) is special-cased to avoid flattening the array. The loop iterates over the indexes of the array.

  • In terms of readability: #1.

  • In terms of flexibility: #1/#4 and #5.

    #2 does not support elements that are false. #2 and #3 are destructive.

AngularJS Uploading An Image With ng-upload

        var app = angular.module('plunkr', [])
    app.controller('UploadController', function($scope, fileReader) {
        $scope.imageSrc = "";

        $scope.$on("fileProgress", function(e, progress) {
        $scope.progress = progress.loaded / progress.total;
        });
    });




    app.directive("ngFileSelect", function(fileReader, $timeout) {
        return {
        scope: {
            ngModel: '='
        },
        link: function($scope, el) {
            function getFile(file) {
            fileReader.readAsDataUrl(file, $scope)
                .then(function(result) {
                $timeout(function() {
                    $scope.ngModel = result;
                });
                });
            }

            el.bind("change", function(e) {
            var file = (e.srcElement || e.target).files[0];
            getFile(file);
            });
        }
        };
    });

    app.factory("fileReader", function($q, $log) {
    var onLoad = function(reader, deferred, scope) {
        return function() {
        scope.$apply(function() {
            deferred.resolve(reader.result);
        });
        };
    };

    var onError = function(reader, deferred, scope) {
        return function() {
        scope.$apply(function() {
            deferred.reject(reader.result);
        });
        };
    };

    var onProgress = function(reader, scope) {
        return function(event) {
        scope.$broadcast("fileProgress", {
            total: event.total,
            loaded: event.loaded
        });
        };
    };

    var getReader = function(deferred, scope) {
        var reader = new FileReader();
        reader.onload = onLoad(reader, deferred, scope);
        reader.onerror = onError(reader, deferred, scope);
        reader.onprogress = onProgress(reader, scope);
        return reader;
    };

    var readAsDataURL = function(file, scope) {
        var deferred = $q.defer();

        var reader = getReader(deferred, scope);
        reader.readAsDataURL(file);

        return deferred.promise;
    };

    return {
        readAsDataUrl: readAsDataURL
    };
    });



    *************** CSS ****************

    img{width:200px; height:200px;}

    ************** HTML ****************

    <div ng-app="app">
    <div ng-controller="UploadController ">
        <form>
        <input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc">
                <input type="file" ng-file-select="onFileSelect($files)" ng-model="imageSrc2">
        <!--  <input type="file" ng-file-select="onFileSelect($files)" multiple> -->
        </form>

        <img ng-src="{{imageSrc}}" />
    <img ng-src="{{imageSrc2}}" />

    </div>
    </div>

Java null check why use == instead of .equals()

In Java 0 or null are simple types and not objects.

The method equals() is not built for simple types. Simple types can be matched with ==.

How can I print variable and string on same line in Python?

Slightly different: Using Python 3 and print several variables in the same line:

print("~~Create new DB:",argv[5],"; with user:",argv[3],"; and Password:",argv[4]," ~~")

Maximum concurrent connections to MySQL

I can assure you that raw speed ultimately lies in the non-standard use of Indexes for blazing speed using large tables.

Putting a password to a user in PhpMyAdmin in Wamp

i have some problems with it, and fixed it my using another config variable

$cfg['Servers'][$i]['AllowNoPassword'] = true;
instead
$cfg['Servers'][$i]['AllowNoPasswordRoot'] = true;

may be it will helpfull ot someone

"android.view.WindowManager$BadTokenException: Unable to add window" on buider.show()

  • first you cannot extend AsyncTask without override doInBackground
  • second try to create AlterDailog from the builder then call show().

    private boolean visible = false;
    class chkSubscription extends AsyncTask<String, Void, String>
    {
    
        protected void onPostExecute(String result)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
            builder.setCancelable(true);
            builder.setMessage(sucObject);
            builder.setInverseBackgroundForced(true);
            builder.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton)
                {
                    dialog.dismiss();
                }
            });
    
            AlertDialog myAlertDialog = builder.create();
            if(visible) myAlertDialog.show();
        }
    
        @Override
        protected String doInBackground(String... arg0)
        {
            // TODO Auto-generated method stub
            return null;
        }
    }
    
    
    @Override
    protected void onResume()
    {
        // TODO Auto-generated method stub
        super.onResume();
        visible = true;
    }
    
    @Override
    protected void onStop()
    {
        visible = false; 
        super.onStop();
    }
    

Ruby: How to turn a hash into HTTP parameters?

{:a=>"a", :b=>"b", :c=>"c"}.map{ |x,v| "#{x}=#{v}" }.reduce{|x,v| "#{x}&#{v}" }

"a=a&b=b&c=c"

Here's another way. For simple queries.

How to enable GZIP compression in IIS 7.5

If anyone runs across this and is looking for a bit more up-to-date answer or copy-paste answer or answer targeting multiple versions than JC Raja's post, here's what I've found:

Google's got a pretty solid, easy-to-understand introduction to how this works and what is advantageous and not. https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/optimize-encoding-and-transfer They recommend the HTML5 Boilerplate project, which has solutions for different versions of IIS:

  • .NET version 3
  • .NET version 4
  • .NET version 4.5 / MVC 5

Available here: https://github.com/h5bp/server-configs-iis They have web.configs that you can copy and paste changes from theirs to yours and see the changes, much easier than digging through a bunch of blog posts.

Here's the web.config settings for .NET version 4.5: https://github.com/h5bp/server-configs-iis/blob/master/dotnet%204.5/MVC5/Web.config

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <!--
            Set compilation debug="true" to insert debugging
            symbols into the compiled page. Because this
            affects performance, set this value to true only
            during development.
    -->
    <compilation debug="true" targetFramework="4.5" />

    <!-- Security through obscurity, removes  X-AspNet-Version HTTP header from the response -->
    <!-- Allow zombie DOS names to be captured by ASP.NET (/con, /com1, /lpt1, /aux, /prt, /nul, etc) -->
    <httpRuntime targetFramework="4.5" requestValidationMode="2.0" requestPathInvalidCharacters="" enableVersionHeader="false" relaxedUrlToFileSystemMapping="true" />

    <!-- httpCookies httpOnlyCookies setting defines whether cookies 
             should be exposed to client side scripts
             false (Default): client side code can access cookies
             true: client side code cannot access cookies
             Require SSL is situational, you can also define the 
             domain of cookies with optional "domain" property -->
    <httpCookies httpOnlyCookies="true" requireSSL="false" />

    <trace writeToDiagnosticsTrace="false" enabled="false" pageOutput="false" localOnly="true" />
  </system.web>


  <system.webServer>
    <!-- GZip static file content.  Overrides the server default which only compresses static files over 2700 bytes -->
    <httpCompression directory="%SystemDrive%\websites\_compressed" minFileSizeForComp="1024">
      <scheme name="gzip" dll="%Windir%\system32\inetsrv\gzip.dll" />
      <staticTypes>
        <add mimeType="text/*" enabled="true" />
        <add mimeType="message/*" enabled="true" />
        <add mimeType="application/javascript" enabled="true" />
        <add mimeType="application/json" enabled="true" />
        <add mimeType="*/*" enabled="false" />
      </staticTypes>
    </httpCompression>

    <httpErrors existingResponse="PassThrough" errorMode="Custom">
      <!-- Catch IIS 404 error due to paths that exist but shouldn't be served (e.g. /controllers, /global.asax) or IIS request filtering (e.g. bin, web.config, app_code, app_globalresources, app_localresources, app_webreferences, app_data, app_browsers) -->
      <remove statusCode="404" subStatusCode="-1" />
      <error statusCode="404" subStatusCode="-1" path="/notfound" responseMode="ExecuteURL" />
      <remove statusCode="500" subStatusCode="-1" />
      <error statusCode="500" subStatusCode="-1" path="/error" responseMode="ExecuteURL" />
    </httpErrors>

    <directoryBrowse enabled="false" />
    <validation validateIntegratedModeConfiguration="false" />

    <!-- Microsoft sets runAllManagedModulesForAllRequests to true by default
             You should handle this according to need but consider the performance hit.
             Good source of reference on this matter: http://www.west-wind.com/weblog/posts/2012/Oct/25/Caveats-with-the-runAllManagedModulesForAllRequests-in-IIS-78
        -->
    <modules runAllManagedModulesForAllRequests="false" />

    <urlCompression doStaticCompression="true" doDynamicCompression="true" />
    <staticContent>
      <!-- Set expire headers to 30 days for static content-->
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="30.00:00:00" />
      <!-- use utf-8 encoding for anything served text/plain or text/html -->
      <remove fileExtension=".css" />
      <mimeMap fileExtension=".css" mimeType="text/css" />
      <remove fileExtension=".js" />
      <mimeMap fileExtension=".js" mimeType="text/javascript" />
      <remove fileExtension=".json" />
      <mimeMap fileExtension=".json" mimeType="application/json" />
      <remove fileExtension=".rss" />
      <mimeMap fileExtension=".rss" mimeType="application/rss+xml; charset=UTF-8" />
      <remove fileExtension=".html" />
      <mimeMap fileExtension=".html" mimeType="text/html; charset=UTF-8" />
      <remove fileExtension=".xml" />
      <mimeMap fileExtension=".xml" mimeType="application/xml; charset=UTF-8" />
      <!-- HTML5 Audio/Video mime types-->
      <remove fileExtension=".mp3" />
      <mimeMap fileExtension=".mp3" mimeType="audio/mpeg" />
      <remove fileExtension=".mp4" />
      <mimeMap fileExtension=".mp4" mimeType="video/mp4" />
      <remove fileExtension=".ogg" />
      <mimeMap fileExtension=".ogg" mimeType="audio/ogg" />
      <remove fileExtension=".ogv" />
      <mimeMap fileExtension=".ogv" mimeType="video/ogg" />
      <remove fileExtension=".webm" />
      <mimeMap fileExtension=".webm" mimeType="video/webm" />
      <!-- Proper svg serving. Required for svg webfonts on iPad -->
      <remove fileExtension=".svg" />
      <mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
      <remove fileExtension=".svgz" />
      <mimeMap fileExtension=".svgz" mimeType="image/svg+xml" />
      <!-- HTML4 Web font mime types -->
      <!-- Remove default IIS mime type for .eot which is application/octet-stream -->
      <remove fileExtension=".eot" />
      <mimeMap fileExtension=".eot" mimeType="application/vnd.ms-fontobject" />
      <remove fileExtension=".ttf" />
      <mimeMap fileExtension=".ttf" mimeType="application/x-font-ttf" />
      <remove fileExtension=".ttc" />
      <mimeMap fileExtension=".ttc" mimeType="application/x-font-ttf" />
      <remove fileExtension=".otf" />
      <mimeMap fileExtension=".otf" mimeType="font/opentype" />
      <remove fileExtension=".woff" />
      <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
      <remove fileExtension=".crx" />
      <mimeMap fileExtension=".crx" mimeType="application/x-chrome-extension" />
      <remove fileExtension=".xpi" />
      <mimeMap fileExtension=".xpi" mimeType="application/x-xpinstall" />
      <remove fileExtension=".safariextz" />
      <mimeMap fileExtension=".safariextz" mimeType="application/octet-stream" />
      <!-- Flash Video mime types-->
      <remove fileExtension=".flv" />
      <mimeMap fileExtension=".flv" mimeType="video/x-flv" />
      <remove fileExtension=".f4v" />
      <mimeMap fileExtension=".f4v" mimeType="video/mp4" />
      <!-- Assorted types -->
      <remove fileExtension=".ico" />
      <mimeMap fileExtension=".ico" mimeType="image/x-icon" />
      <remove fileExtension=".webp" />
      <mimeMap fileExtension=".webp" mimeType="image/webp" />
      <remove fileExtension=".htc" />
      <mimeMap fileExtension=".htc" mimeType="text/x-component" />
      <remove fileExtension=".vcf" />
      <mimeMap fileExtension=".vcf" mimeType="text/x-vcard" />
      <remove fileExtension=".torrent" />
      <mimeMap fileExtension=".torrent" mimeType="application/x-bittorrent" />
      <remove fileExtension=".cur" />
      <mimeMap fileExtension=".cur" mimeType="image/x-icon" />
      <remove fileExtension=".webapp" />
      <mimeMap fileExtension=".webapp" mimeType="application/x-web-app-manifest+json; charset=UTF-8" />
    </staticContent>
    <httpProtocol>
      <customHeaders>

        <!--#### SECURITY Related Headers ###
            More information: https://www.owasp.org/index.php/List_of_useful_HTTP_headers
        -->
        <!--
                # Access-Control-Allow-Origin
                The 'Access Control Allow Origin' HTTP header is used to control which
                sites are allowed to bypass same-origin policies and send cross-origin requests.

                Secure configuration: Either do not set this header or return the 'Access-Control-Allow-Origin'
                header restricting it to only a trusted set of sites.
                http://enable-cors.org/

                <add name="Access-Control-Allow-Origin" value="*" />
                -->

        <!--
                # Cache-Control
                The 'Cache-Control' response header controls how pages can be cached
                either by proxies or the user's browser.
                This response header can provide enhanced privacy by not caching
                sensitive pages in the user's browser cache.

                <add name="Cache-Control" value="no-store, no-cache"/>
                -->

        <!--
                # Strict-Transport-Security
                The HTTP Strict Transport Security header is used to control
                if the browser is allowed to only access a site over a secure connection
                and how long to remember the server response for, forcing continued usage.
                Note* Currently a draft standard which only Firefox and Chrome support. But is supported by sites like PayPal.
                <add name="Strict-Transport-Security" value="max-age=15768000"/>
                -->

        <!--
                # X-Frame-Options
                The X-Frame-Options header indicates whether a browser should be allowed
                to render a page within a frame or iframe.
                The valid options are DENY (deny allowing the page to exist in a frame)
                or SAMEORIGIN (allow framing but only from the originating host)
                Without this option set, the site is at a higher risk of click-jacking.

                <add name="X-Frame-Options" value="SAMEORIGIN" />
                -->

        <!--
                # X-XSS-Protection
                The X-XSS-Protection header is used by Internet Explorer version 8+
                The header instructs IE to enable its inbuilt anti-cross-site scripting filter.
                If enabled, without 'mode=block', there is an increased risk that
                otherwise, non-exploitable cross-site scripting vulnerabilities may potentially become exploitable

                <add name="X-XSS-Protection" value="1; mode=block"/>
                -->

        <!--    
                # MIME type sniffing security protection
                Enabled by default as there are very few edge cases where you wouldn't want this enabled.
                Theres additional reading below; but the tldr, it reduces the ability of the browser (mostly IE) 
                being tricked into facilitating driveby attacks.
                http://msdn.microsoft.com/en-us/library/ie/gg622941(v=vs.85).aspx
                http://blogs.msdn.com/b/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx
        -->
        <add name="X-Content-Type-Options" value="nosniff" />

        <!-- A little extra security (by obscurity), removings fun but adding your own is better -->
        <remove name="X-Powered-By" />
        <add name="X-Powered-By" value="My Little Pony" />

        <!--
                 With Content Security Policy (CSP) enabled (and a browser that supports it (http://caniuse.com/#feat=contentsecuritypolicy),
         you can tell the browser that it can only download content from the domains you explicitly allow
         CSP can be quite difficult to configure, and cause real issues if you get it wrong
         There is website that helps you generate a policy here http://cspisawesome.com/
         <add name="Content-Security-Policy" "default-src 'self'; style-src 'self' 'unsafe-inline'; script-src 'self' https://www.google-analytics.com;" />
                -->

        <!--//#### SECURITY Related Headers ###-->

        <!--
                Force the latest IE version, in various cases when it may fall back to IE7 mode
                github.com/rails/rails/commit/123eb25#commitcomment-118920
                Use ChromeFrame if it's installed for a better experience for the poor IE folk
                -->
        <add name="X-UA-Compatible" value="IE=Edge,chrome=1" />
        <!--
                Allow cookies to be set from iframes (for IE only)
                If needed, uncomment and specify a path or regex in the Location directive

                <add name="P3P" value="policyref=&quot;/w3c/p3p.xml&quot;, CP=&quot;IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT&quot;" />
                -->

      </customHeaders>
    </httpProtocol>

    <!--
        <rewrite>
            <rules>

            Remove/force the WWW from the URL.
            Requires IIS Rewrite module http://learn.iis.net/page.aspx/460/using-the-url-rewrite-module/
            Configuration lifted from http://nayyeri.net/remove-www-prefix-from-urls-with-url-rewrite-module-for-iis-7-0

            NOTE* You need to install the IIS URL Rewriting extension (Install via the Web Platform Installer)
            http://www.microsoft.com/web/downloads/platform.aspx

            ** Important Note
            using a non-www version of a webpage will set cookies for the whole domain making cookieless domains
            (eg. fast CD-like access to static resources like CSS, js, and images) impossible.

            # IMPORTANT: THERE ARE TWO RULES LISTED. NEVER USE BOTH RULES AT THE SAME TIME!

                <rule name="Remove WWW" stopProcessing="true">
                    <match url="^(.*)$" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^(www\.)(.*)$" />
                    </conditions>
                    <action type="Redirect" url="http://example.com{PATH_INFO}" redirectType="Permanent" />
                </rule>
                <rule name="Force WWW" stopProcessing="true">
                    <match url=".*" />
                    <conditions>
                        <add input="{HTTP_HOST}" pattern="^example.com$" />
                    </conditions>
                    <action type="Redirect" url="http://www.example.com/{R:0}" redirectType="Permanent" />
                </rule>


                # E-TAGS
                E-Tags are actually quite useful in cache management especially if you have a front-end caching server such as Varnish. http://en.wikipedia.org/wiki/HTTP_ETag / http://developer.yahoo.com/performance/rules.html#etags
                But in load balancing and simply most cases ETags are mishandled in IIS, and it can be advantageous to remove them.
        # removed as in https://stackoverflow.com/questions/7947420/iis-7-5-remove-etag-headers-from-response

        <rewrite>
           <outboundRules>
              <rule name="Remove ETag">
                 <match serverVariable="RESPONSE_ETag" pattern=".+" />
                 <action type="Rewrite" value="" />
              </rule>
           </outboundRules>
        </rewrite>

            -->
    <!--
            ### Built-in filename-based cache busting

            In a managed language such as .net, you should really be using the internal bundler for CSS + js
            or get cassette or similar.

            If you're not using the build script to manage your filename version revving,
            you might want to consider enabling this, which will route requests for
            /css/style.20110203.css to /css/style.css

            To understand why this is important and a better idea than all.css?v1231,
            read: github.com/h5bp/html5-boilerplate/wiki/Version-Control-with-Cachebusting

                <rule name="Cachebusting">
                    <match url="^(.+)\.\d+(\.(js|css|png|jpg|gif)$)" />
                    <action type="Rewrite" url="{R:1}{R:2}" />
                </rule>

            </rules>
        </rewrite>-->

  </system.webServer>

  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

Edit: One update if you need Gzip compression on WebAPI responses. I wasn't aware our WebAPI wasn't returning Gzipped responses until recently and scratched my head for a while because we had dynamic and static compression turned on in web.config. We looked at writing our own compression services and response handlers (still on WebAPI 2 not on .NET Core where it's easier now), but that was too cumbersome for what seemed like something we should just be able to turn on.

(If you're interested here's what we were looking at for our own compression service https://krzysztofjakielaszek.com/2017/03/26/webapi2-response-compression-gzip-brotli-deflate/ EDIT: Link is now offline, but you can view the code/content here: https://web.archive.org/web/20190608161201/https://krzysztofjakielaszek.com/2017/03/26/webapi2-response-compression-gzip-brotli-deflate/ )

Instead, we found this great post by Ben Foster (http://benfoster.io/blog/aspnet-web-api-compression) If you can modify applicationHost.config (running your own servers), you can pop that config file open and add the mimeTypes you want to compress (I pulled the relevant ones based on what our API was returning to clients from our Web.Config). Save that file, IIS will pickup your changes, recycle app pools, and your WebAPI will start returning gzip compressed responses to clients who request it.

If you don't see gzipped responses, check the response content type with Fiddler or Chrome/Firefox Dev Tools, and ensure it matches what you added. I had to change the view mode (use large request rows) in Chrome Dev Tools to ensure it showed the total size vs transferred size. If everything validates, try rebooting the server once to just ensure it was properly applied. I did have one syntax error where when I opened up the site in IIS, IIS poppped open a message about a parsing error that I had to fix in the config file.

<httpCompression directory="%TEMP%\iisexpress\IIS Temporary Compressed Files">
    <scheme name="gzip" dll="%IIS_BIN%\gzip.dll" />
    <dynamicTypes>
        ...

        <!-- compress JSON responses from Web API -->           
        <add mimeType="application/json" enabled="true" /> 

        ...
    </dynamicTypes>
    <staticTypes>
        ...
    </staticTypes>
</httpCompression>

How to save all console output to file in R?

You have to sink "output" and "message" separately (the sink function only looks at the first element of type)

Now if you want the input to be logged too, then put it in a script:

script.R

1:5 + 1:3   # prints and gives a warning
stop("foo") # an error

And at the prompt:

con <- file("test.log")
sink(con, append=TRUE)
sink(con, append=TRUE, type="message")

# This will echo all input and not truncate 150+ character lines...
source("script.R", echo=TRUE, max.deparse.length=10000)

# Restore output to console
sink() 
sink(type="message")

# And look at the log...
cat(readLines("test.log"), sep="\n")

Get hostname of current request in node.js Express

Here's an alternate

req.hostname

Read about it in the Express Docs.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I had a similar use case where I wanted to test a Spring Boot configured repository in isolation (in my case without Spring Security autoconfiguration which was failing my test). @SpringApplicationConfiguration uses SpringApplicationContextLoader and that has a JavaDoc stating

Can be used to test non-web features (like a repository layer) or start an fully-configured embedded servlet container.

However, like yourself, I could not work out how you are meant to configure the test to only test the repository layer using the main configuration entry point i.e. using your approach of @SpringApplicationConfiguration(classes = Application.class).

My solution was to create a completely new application context exclusive for testing. So in src/test/java I have two files in a sub-package called repo

  1. RepoIntegrationTest.java
  2. TestRepoConfig.java

where RepoIntegrationTest.java has

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = TestRepoConfig.class)
public class RepoIntegrationTest {

and TestRepoConfig.java has

@SpringBootApplication(exclude = SecurityAutoConfiguration.class)
public class TestRepoConfig {

It got me out of trouble but it would be really useful if anyone from the Spring Boot team could provide an alternative recommended solution

What is the quickest way to HTTP GET in Python?

How to also send headers

Python 3:

import urllib.request
contents = urllib.request.urlopen(urllib.request.Request(
    "https://api.github.com/repos/cirosantilli/linux-kernel-module-cheat/releases/latest",
    headers={"Accept" : 'application/vnd.github.full+json"text/html'}
)).read()
print(contents)

Python 2:

import urllib2
contents = urllib2.urlopen(urllib2.Request(
    "https://api.github.com",
    headers={"Accept" : 'application/vnd.github.full+json"text/html'}
)).read()
print(contents)

Dropping Unique constraint from MySQL table

To add UNIQUE constraint using phpmyadmin, go to the structure of that table and find below and click that,

enter image description here

To remove the UNIQUE constraint, same way, go to the structure and scroll down till Indexes Tab and find below and click drop, enter image description here

Hope this works.

Enjoy ;)

How to check edittext's text is email address or not?

Please follow the following Steps

Step 1 :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >

    <EditText
        android:id="@+id/editText_email"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_below="@+id/textView_email"
        android:layout_marginTop="40dp"
        android:hint="Email Adderess"
        android:inputType="textEmailAddress" />

    <TextView
        android:id="@+id/textView_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="30dp"
        android:text="Email Validation Example" />

</RelativeLayout>

Step 2:

import android.app.Activity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.EditText;

Step 3:

public class MainActivity extends Activity {

private EditText email;

private String valid_email;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    initilizeUI();
}

/**
 * This method is used to initialize UI Components
 */
private void initilizeUI() {
    // TODO Auto-generated method stub

    email = (EditText) findViewById(R.id.editText_email);

    email.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
            // TODO Auto-generated method stub

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

            // TODO Auto-generated method stub
            Is_Valid_Email(email); // pass your EditText Obj here.
        }

        public void Is_Valid_Email(EditText edt) {
            if (edt.getText().toString() == null) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else if (isEmailValid(edt.getText().toString()) == false) {
                edt.setError("Invalid Email Address");
                valid_email = null;
            } else {
                valid_email = edt.getText().toString();
            }
        }

        boolean isEmailValid(CharSequence email) {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(email)
                    .matches();
        } // end of TextWatcher (email)
    });

}

}

Get the difference between two dates both In Months and days in sql

is this what you've ment ?

select trunc(months_between(To_date('20120325', 'YYYYMMDD'),to_date('20120101','YYYYMMDD'))) months,
             round(To_date('20120325', 'YYYYMMDD')-add_months(to_date('20120101','YYYYMMDD'),
                           trunc(months_between(To_date('20120325', 'YYYYMMDD'),to_date('20120101','YYYYMMDD'))))) days
        from dual;

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

How to add buttons like refresh and search in ToolBar in Android?

OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom" instead of app:showAsAction="ifRoom" since i am using v7 library.

However the title is coming at center of extended toolbar. How to make it appear at the top?

PHP Fatal error: Uncaught exception 'Exception'

Just adding a bit of extra information here in case someone has the same issue as me.

I use namespaces in my code and I had a class with a function that throws an Exception.

However my try/catch code in another class file was completely ignored and the normal PHP error for an uncatched exception was thrown.

Turned out I forgot to add "use \Exception;" at the top, adding that solved the error.

How to list all users in a Linux group?

lid -g groupname | cut -f1 -d'(' 

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

This bug is filed here. This is a bug of android devices having API level less than 12. You've to put correct versions of your layouts in drawable-v12 folder which will be used for API level 12 or higher. And an erroneous version(corners switched/reversed) of the same layout will be put in the default drawable folder which will be used by the devices having API level less than 12.

For example: I had to design a button with rounded corner at bottom-right.

In 'drawable' folder - button.xml: I had to make bottom-left corner rounded.

<shape>
    <corners android:bottomLeftRadius="15dp"/>
</shape>

In 'drawable-v12' folder - button.xml: Correct version of the layout was placed here to be used for API level 12 or higher.

<shape>
    <corners android:bottomLeftRadius="15dp"/>
</shape>

A fast way to delete all rows of a datatable at once

If you are really concerned about speed and not worried about the data you can do a Truncate. But this is assuming your DataTable is on a database and not just a memory object.

TRUNCATE TABLE tablename

The difference is this removes all rows without logging the row deletes making the transaction faster.

JPA Criteria API - How to add JOIN clause (as general sentence as possible)

Maybe the following extract from the Chapter 23 - Using the Criteria API to Create Queries of the Java EE 6 tutorial will throw some light (actually, I suggest reading the whole Chapter 23):

Querying Relationships Using Joins

For queries that navigate to related entity classes, the query must define a join to the related entity by calling one of the From.join methods on the query root object, or another join object. The join methods are similar to the JOIN keyword in JPQL.

The target of the join uses the Metamodel class of type EntityType<T> to specify the persistent field or property of the joined entity.

The join methods return an object of type Join<X, Y>, where X is the source entity and Y is the target of the join.

Example 23-10 Joining a Query

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Pet, Owner> owner = pet.join(Pet_.owners);

Joins can be chained together to navigate to related entities of the target entity without having to create a Join<X, Y> instance for each join.

Example 23-11 Chaining Joins Together in a Query

CriteriaQuery<Pet> cq = cb.createQuery(Pet.class);
Metamodel m = em.getMetamodel();
EntityType<Pet> Pet_ = m.entity(Pet.class);
EntityType<Owner> Owner_ = m.entity(Owner.class);

Root<Pet> pet = cq.from(Pet.class);
Join<Owner, Address> address = cq.join(Pet_.owners).join(Owner_.addresses);

That being said, I have some additional remarks:

First, the following line in your code:

Root entity_ = cq.from(this.baseClass);

Makes me think that you somehow missed the Static Metamodel Classes part. Metamodel classes such as Pet_ in the quoted example are used to describe the meta information of a persistent class. They are typically generated using an annotation processor (canonical metamodel classes) or can be written by the developer (non-canonical metamodel). But your syntax looks weird, I think you are trying to mimic something that you missed.

Second, I really think you should forget this assay_id foreign key, you're on the wrong path here. You really need to start to think object and association, not tables and columns.

Third, I'm not really sure to understand what you mean exactly by adding a JOIN clause as generical as possible and what your object model looks like, since you didn't provide it (see previous point). It's thus just impossible to answer your question more precisely.

To sum up, I think you need to read a bit more about JPA 2.0 Criteria and Metamodel API and I warmly recommend the resources below as a starting point.

See also

Related question

Set element width or height in Standards Mode

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS

Date Difference in php on days?

strtotime will convert your date string to a unix time stamp. (seconds since the unix epoch.

$ts1 = strtotime($date1);
$ts2 = strtotime($date2);

$seconds_diff = $ts2 - $ts1;

bitwise XOR of hex numbers in python

If the strings are the same length, then I would go for '%x' % () of the built-in xor (^).

Examples -

>>>a = '290b6e3a'
>>>b = 'd6f491c5'
>>>'%x' % (int(a,16)^int(b,16))
'ffffffff'
>>>c = 'abcd'
>>>d = '12ef'
>>>'%x' % (int(a,16)^int(b,16))
'b922'

If the strings are not the same length, truncate the longer string to the length of the shorter using a slice longer = longer[:len(shorter)]

Text blinking jQuery

$.fn.blink = function (delay) {
  delay = delay || 500;
  return this.each(function () {
    var element = $(this);
    var interval = setInterval(function () {
      element.fadeOut((delay / 3), function() {
        element.fadeIn(delay / 3);
      })
    }, delay);
    element.data('blinkInterval', interval);
  });
};

$.fn.stopBlinking = function() {
  return this.each(function() {
    var element = $(this);
    element.stop(true, true);
    clearInterval(element.data('blinkInterval'));
  });
};

How to get two or more commands together into a batch file

If you are creating other batch files from your outputs then put a line like this in your batch file

echo %pathname%\foo.exe >part2.txt

then you can have your defined part1.txt and part3.txt already done and have your batch

copy part1.txt + part2.txt +part3.txt thebatyouwanted.bat

call a function in success of datatable ajax call

Based on the docs, xhr Ajax event would fire when an Ajax request is completed. So you can do something like this:

let data_table = $('#example-table').dataTable({
        ajax: "data.json"
    });

data_table.on('xhr.dt', function ( e, settings, json, xhr ) {
        // Do some staff here...
        $('#status').html( json.status );
    } )

java.lang.ClassNotFoundException: org.apache.jsp.index_jsp

It's been a while since I posted this, but I thought I would show how I figured it out (as best as I recall now).

I did a Maven dependency tree to find dependency conflicts, and I removed all conflicts with exclusions in dependencies, e.g.:

<dependency>
    <groupId>commons-logging</groupId>
    <artifactId>commons-logging-api</artifactId>
    <version>1.1</version>
    <exclusions>
        <exclusion>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
        </exclusion>
    </exclusions>
</dependency>

Also, I used the provided scope for javax.servlet dependencies so as not to introduce an additional conflict with what is provided by Tomcat when I run the app.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
    <scope>provided</scope>
</dependency>
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>jsp-api</artifactId>
    <version>2.1</version>
    <scope>provided</scope>
</dependency>

HTH.

Difference between objectForKey and valueForKey?

As said, the objectForKey: datatype is :(id)aKey whereas the valueForKey: datatype is :(NSString *)key.

For example:

 NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:@"123"],[NSNumber numberWithInteger:5], nil];

 NSLog(@"objectForKey : --- %@",[dict objectForKey:[NSNumber numberWithInteger:5]]);  
    //This will work fine and prints (    123    )  

 NSLog(@"valueForKey  : --- %@",[dict valueForKey:[NSNumber numberWithInteger:5]]); 
    //it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'"   ---- This will crash on runtime. 

So, valueForKey: will take only a string value and is a KVC method, whereas objectForKey: will take any type of object.

The value in objectForKey will be accessed by the same kind of object.

Is there a minlength validation attribute in HTML5?

Yes, there it is. It's like maxlength. W3.org documentation: http://www.w3.org/TR/html5/forms.html#attr-fe-minlength

In case minlength doesn't work, use the pattern attribute as mentioned by @Pumbaa80 for the input tag.

For textarea: For setting max; use maxlength and for min go to this link.

You will find here both for max and min.

Fatal error: iostream: No such file or directory in compiling C program using GCC

Seems like you posted a new question after you realized that you were dealing with a simpler problem related to size_t. I am glad that you did.

Anyways, You have a .c source file, and most of the code looks as per C standards, except that #include <iostream> and using namespace std;

C equivalent for the built-in functions of C++ standard #include<iostream> can be availed through #include<stdio.h>

  1. Replace #include <iostream> with #include <stdio.h>, delete using namespace std;
  2. With #include <iostream> taken off, you would need a C standard alternative for cout << endl;, which can be done by printf("\n"); or putchar('\n');
    Out of the two options, printf("\n"); works the faster as I observed.

    When used printf("\n"); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.031s
    user    0m0.030s
    sys     0m0.030s
    

    When used putchar('\n'); in the code above in place of cout<<endl;

    $ time ./thread.exe
    1 2 3 4 5 6 7 8 9 10
    
    real    0m0.047s
    user    0m0.030s
    sys     0m0.030s
    

Compiled with Cygwin gcc (GCC) 4.8.3 version. results averaged over 10 samples. (Took me 15 mins)

How to pass props to {this.props.children}

For a slightly cleaner way to do it, try:

<div>
    {React.cloneElement(this.props.children, { loggedIn: this.state.loggedIn })}
</div>

Edit: To use with multiple individual children (the child must itself be a component) you can do. Tested in 16.8.6

<div>
    {React.cloneElement(this.props.children[0], { loggedIn: true, testPropB: true })}
    {React.cloneElement(this.props.children[1], { loggedIn: true, testPropA: false })}
</div>

AngularJS: ng-repeat list is not updated when a model element is spliced from the model array

Whenever you do some form of operation outside of AngularJS, such as doing an Ajax call with jQuery, or binding an event to an element like you have here you need to let AngularJS know to update itself. Here is the code change you need to do:

app.directive("remove", function () {
    return function (scope, element, attrs) {
        element.bind ("mousedown", function () {
            scope.remove(element);
            scope.$apply();
        })
    };

});

app.directive("resize", function () {
    return function (scope, element, attrs) {
        element.bind ("mousedown", function () {
            scope.resize(element);
            scope.$apply();
        })
    };
});

Here is the documentation on it: https://docs.angularjs.org/api/ng/type/$rootScope.Scope#$apply

Import multiple csv files into pandas and concatenate into one DataFrame

This is how you can do using Colab on Google Drive

import pandas as pd
import glob

path = r'/content/drive/My Drive/data/actual/comments_only' # use your path
all_files = glob.glob(path + "/*.csv")

li = []

for filename in all_files:
    df = pd.read_csv(filename, index_col=None, header=0)
    li.append(df)

frame = pd.concat(li, axis=0, ignore_index=True,sort=True)
frame.to_csv('/content/drive/onefile.csv')

Servlet Mapping using web.xml

It allows servlets to have multiple servlet mappings:

<servlet>
    <servlet-name>Servlet1</servlet-name>
    <servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
    <servlet-name>Servlet1</servlet-name>
    <url-pattern>/bill</url-pattern>
</servlet-mapping>

It allows filters to be mapped on the particular servlet:

<filter-mapping>
    <filter-name>Filter1</filter-name>
    <servlet-name>Servlet1</servlet-name>
</filter-mapping>

Your proposal would support neither of them. Note that the web.xml is read and parsed only once during application's startup, not on every HTTP request as you seem to think.

Since Servlet 3.0, there's the @WebServlet annotation which minimizes this boilerplate:

@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {

See also:

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

How to write a JSON file in C#?

var responseData = //Fetch Data
string jsonData = JsonConvert.SerializeObject(responseData, Formatting.None);
System.IO.File.WriteAllText(Server.MapPath("~/JsonData/jsondata.txt"), jsonData);

python: Change the scripts working directory to the script's own directory

Don't do this.

Your scripts and your data should not be mashed into one big directory. Put your code in some known location (site-packages or /var/opt/udi or something) separate from your data. Use good version control on your code to be sure that you have current and previous versions separated from each other so you can fall back to previous versions and test future versions.

Bottom line: Do not mingle code and data.

Data is precious. Code comes and goes.

Provide the working directory as a command-line argument value. You can provide a default as an environment variable. Don't deduce it (or guess at it)

Make it a required argument value and do this.

import sys
import os
working= os.environ.get("WORKING_DIRECTORY","/some/default")
if len(sys.argv) > 1: working = sys.argv[1]
os.chdir( working )

Do not "assume" a directory based on the location of your software. It will not work out well in the long run.

Get the second highest value in a MySQL table

Seems I'm much late to answer this question. How about this one liner to get the same output?

SELECT DISTINCT salary FROM employees ORDER BY salary DESC LIMIT 1,1 ;

sample fiddle: https://www.db-fiddle.com/f/v4gZUMFbuYorB27AH9yBKy/0

Ordering by the order of values in a SQL IN() clause

Give this a shot:

SELECT name, description, ...
WHERE id IN
    (SELECT id FROM table1 WHERE...)
ORDER BY
    (SELECT display_order FROM table1 WHERE...),
    (SELECT name FROM table1 WHERE...)

The WHEREs will probably take a little tweaking to get the correlated subqueries working properly, but the basic principle should be sound.

What is the purpose of global.asax in asp.net

The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules.

http://msdn.microsoft.com/en-us/library/2027ewzw.aspx

Array String Declaration

Declare the array size will solve your problem

 String[] title = {
            "Abundance",
            "Anxiety",
            "Bruxism",
            "Discipline",
            "Drug Addiction"
        };
    String urlbase = "http://www.somewhere.com/data/";
    String imgSel = "/logo.png";
    String[] mStrings = new String[title.length];

    for(int i=0;i<title.length;i++) {
        mStrings[i] = urlbase + title[i].toLowerCase() + imgSel;

        System.out.println(mStrings[i]);
    }

How do I access ViewBag from JS

try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)

Regex Last occurrence?

I used below regex to get that result also when its finished by a \

(\\[^\\]+)\\?$

[Regex Demo]

Java: get greatest common divisor

Some implementations here are not working correctly if both numbers are negative. gcd(-12, -18) is 6, not -6.

So an absolute value should be returned, something like

public static int gcd(int a, int b) {
    if (b == 0) {
        return Math.abs(a);
    }
    return gcd(b, a % b);
}

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

GroupMember.find_or_create_by(member_id: 4, group_id: 7)

And use where is different:

GroupMember.where(member_id: 4, group_id: 7).first_or_create

This will call create on GroupMember.where(member_id: 4, group_id: 7):

GroupMember.where(member_id: 4, group_id: 7).create

On the contrary, the find_or_create_by(member_id: 4, group_id: 7) will call create on GroupMember:

GroupMember.create(member_id: 4, group_id: 7)

Please see this relevant commit on rails/rails.

import .css file into .less file

From the LESS website:

If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:

@import "lib.css"; The directive will just be left as is, and end up in the CSS output.

As jitbit points out in the comments below, this is really only useful for development purposes, as you wouldn't want to have unnecessary @imports consuming precious bandwidth.

How to swap String characters in Java?

String.toCharArray() will give you an array of characters representing this string.

You can change this without changing the original string (swap any characters you require), and then create a new string using String(char[]).

Note that strings are immutable, so you have to create a new string object.

Any way to replace characters on Swift String?

You can use this:

let s = "This is my string"
let modified = s.replace(" ", withString:"+")    

If you add this extension method anywhere in your code:

extension String
{
    func replace(target: String, withString: String) -> String
    {
       return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
    }
}

Swift 3:

extension String
{
    func replace(target: String, withString: String) -> String
    {
        return self.replacingOccurrences(of: target, with: withString, options: NSString.CompareOptions.literal, range: nil)
    }
}

Timeout on a function call

You can use multiprocessing.Process to do exactly that.

Code

import multiprocessing
import time

# bar
def bar():
    for i in range(100):
        print "Tick"
        time.sleep(1)

if __name__ == '__main__':
    # Start bar as a process
    p = multiprocessing.Process(target=bar)
    p.start()

    # Wait for 10 seconds or until process finishes
    p.join(10)

    # If thread is still active
    if p.is_alive():
        print "running... let's kill it..."

        # Terminate - may not work if process is stuck for good
        p.terminate()
        # OR Kill - will work for sure, no chance for process to finish nicely however
        # p.kill()

        p.join()

Get distance between two points in canvas

The distance between two coordinates x and y! x1 and y1 is the first point/position, x2 and y2 is the second point/position!

_x000D_
_x000D_
function diff (num1, num2) {_x000D_
  if (num1 > num2) {_x000D_
    return (num1 - num2);_x000D_
  } else {_x000D_
    return (num2 - num1);_x000D_
  }_x000D_
};_x000D_
_x000D_
function dist (x1, y1, x2, y2) {_x000D_
  var deltaX = diff(x1, x2);_x000D_
  var deltaY = diff(y1, y2);_x000D_
  var dist = Math.sqrt(Math.pow(deltaX, 2) + Math.pow(deltaY, 2));_x000D_
  return (dist);_x000D_
};
_x000D_
_x000D_
_x000D_

How can I run a program from a batch file without leaving the console open after the program starts?

From my own question:

start /b myProgram.exe params...

works if you start the program from an existing DOS session.

If not, call a vb script

wscript.exe invis.vbs myProgram.exe %*

The Windows Script Host Run() method takes:

  • intWindowStyle : 0 means "invisible windows"
  • bWaitOnReturn : false means your first script does not need to wait for your second script to finish

Here is invis.vbs:

set args = WScript.Arguments
num = args.Count

if num = 0 then
    WScript.Echo "Usage: [CScript | WScript] invis.vbs aScript.bat <some script arguments>"
    WScript.Quit 1
end if

sargs = ""
if num > 1 then
    sargs = " "
    for k = 1 to num - 1
        anArg = args.Item(k)
        sargs = sargs & anArg & " "
    next
end if

Set WshShell = WScript.CreateObject("WScript.Shell")

WshShell.Run """" & WScript.Arguments(0) & """" & sargs, 0, False

What is the "hasClass" function with plain JavaScript?

The attribute that stores the classes in use is className.

So you can say:

if (document.body.className.match(/\bmyclass\b/)) {
    ....
}

If you want a location that shows you how jQuery does everything, I would suggest:

http://code.jquery.com/jquery-1.5.js

How to get streaming url from online streaming radio station

The provided answers didn't work for me. I'm adding another answer because this is where I ended up when searching for radio stream urls.

Radio Browser is a searchable site with streaming urls for radio stations around the world:

http://www.radio-browser.info/

Search for a station like FIP, Pinguin Radio or Radio Paradise, then click the save button, which downloads a PLS file that you can open in your radioplayer (Rhythmbox), or you open the file in a text editor and copy the URL to add in Goodvibes.

How to define custom exception class in Java, the easiest way?

Exception class has two constructors

  • public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
  • public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.

Calculating width from percent to pixel then minus by pixel in LESS CSS

Or, you could use the margin attribute like this:

    {
    background:#222;
    width:100%;
    height:100px;
    margin-left: 10px;
    margin-right: 10px;
    display:block;
    }

Oracle query execution time

Use:

set serveroutput on
variable n number
exec :n := dbms_utility.get_time;
select ......
exec dbms_output.put_line( (dbms_utility.get_time-:n)/100) || ' seconds....' );

Or possibly:

SET TIMING ON;

-- do stuff

SET TIMING OFF;

...to get the hundredths of seconds that elapsed.

In either case, time elapsed can be impacted by server load/etc.

Reference:

How to write to the Output window in Visual Studio?

Even though OutputDebugString indeed prints a string of characters to the debugger console, it's not exactly like printf with regard to the latter being able to format arguments using the % notation and a variable number of arguments, something OutputDebugString does not do.

I would make the case that the _RPTFN macro, with _CRT_WARN argument at least, is a better suitor in this case -- it formats the principal string much like printf, writing the result to debugger console.

A minor (and strange, in my opinion) caveat with it is that it requires at least one argument following the format string (the one with all the % for substitution), a limitation printf does not suffer from.

For cases where you need a puts like functionality -- no formatting, just writing the string as-is -- there is its sibling _RPTF0 (which ignores arguments following the format string, another strange caveat). Or OutputDebugString of course.

And by the way, there is also everything from _RPT1 to _RPT5 but I haven't tried them. Honestly, I don't understand why provide so many procedures all doing essentially the same thing.

Why is Chrome showing a "Please Fill Out this Field" tooltip on empty fields?

Are you using the HTML5 required attribute?

That will cause Chrome 10 to display a balloon prompting the user to fill out the field.

Read HttpContent in WebApi controller

You can keep your CONTACT parameter with the following approach:

using (var stream = new MemoryStream())
{
    var context = (HttpContextBase)Request.Properties["MS_HttpContext"];
    context.Request.InputStream.Seek(0, SeekOrigin.Begin);
    context.Request.InputStream.CopyTo(stream);
    string requestBody = Encoding.UTF8.GetString(stream.ToArray());
}

Returned for me the json representation of my parameter object, so I could use it for exception handling and logging.

Found as accepted answer here

Define the selected option with the old input in Laravel / Blade

this will help you , just compare with old if exist , if not then compare with the default value

<select name="select_name">
    @foreach($options as $key => $text)
       <option {{ ($key == old('select_name',$default))?'selected':'' }}> {{ $text }} </option>
    @endforeach
</select>

the $default is the value that injected from the controller to the view

Adding ASP.NET MVC5 Identity Authentication to an existing project

This is what I did to integrate Identity with an existing database.

  1. Create a sample MVC project with MVC template. This has all the code needed for Identity implementation - Startup.Auth.cs, IdentityConfig.cs, Account Controller code, Manage Controller, Models and related views.

  2. Install the necessary nuget packages for Identity and OWIN. You will get an idea by seeing the references in the sample Project and the answer by @Sam

  3. Copy all these code to your existing project. Please note don't forget to add the "DefaultConnection" connection string for Identity to map to your database. Please check the ApplicationDBContext class in IdentityModel.cs where you will find the reference to "DefaultConnection" connection string.

  4. This is the SQL script I ran on my existing database to create necessary tables:

    USE ["YourDatabse"]
    GO
    /****** Object:  Table [dbo].[AspNetRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetRoles](
    [Id] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED 
    (
      [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserClaims]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserClaims](
       [Id] [int] IDENTITY(1,1) NOT NULL,
       [UserId] [nvarchar](128) NOT NULL,
       [ClaimType] [nvarchar](max) NULL,
       [ClaimValue] [nvarchar](max) NULL,
    CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED 
    (
       [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserLogins]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserLogins](
        [LoginProvider] [nvarchar](128) NOT NULL,
        [ProviderKey] [nvarchar](128) NOT NULL,
        [UserId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED 
    (
        [LoginProvider] ASC,
        [ProviderKey] ASC,
        [UserId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserRoles](
       [UserId] [nvarchar](128) NOT NULL,
       [RoleId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED 
    (
        [UserId] ASC,
        [RoleId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUsers]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUsers](
        [Id] [nvarchar](128) NOT NULL,
        [Email] [nvarchar](256) NULL,
        [EmailConfirmed] [bit] NOT NULL,
        [PasswordHash] [nvarchar](max) NULL,
        [SecurityStamp] [nvarchar](max) NULL,
        [PhoneNumber] [nvarchar](max) NULL,
        [PhoneNumberConfirmed] [bit] NOT NULL,
        [TwoFactorEnabled] [bit] NOT NULL,
        [LockoutEndDateUtc] [datetime] NULL,
        [LockoutEnabled] [bit] NOT NULL,
        [AccessFailedCount] [int] NOT NULL,
        [UserName] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
     GO
     ALTER TABLE [dbo].[AspNetUserClaims]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserLogins]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
     REFERENCES [dbo].[AspNetRoles] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
     GO
    
  5. Check and solve any remaining errors and you are done. Identity will handle the rest :)

What is the difference between Promises and Observables?

Both Promises and Observables help us dealing with asynchronous operations. They can call certain callbacks when these asynchronous operations are done.

Angular uses Observables which is from RxJS instead of promises for dealing with HTTP

Below are some important differences in promises & Observables.

difference between Promises and Observables

How to get date, month, year in jQuery UI datepicker?

what about that simple way)

$(document).ready ->
 $('#datepicker').datepicker( dateFormat: 'yy-mm-dd',  onSelect: (dateStr) ->
    alert dateStr # yy-mm-dd
    #OR
    alert $("#datepicker").val(); # yy-mm-dd

How do I install a NuGet package .nupkg file locally?

Recently I want to install squirrel.windows, I tried Install-Package squirrel.windows -Version 2.0.1 from https://www.nuget.org/packages/squirrel.windows/, but it failed with some errors. So I downloaded squirrel.windows.2.0.1.nupkg and save it in D:\Downloads\, then I can install it success via Install-Package squirrel.windows -verbose -Source D:\Downloads\ -Scope CurrentUser -SkipDependencies in powershell.

How to watch and reload ts-node when TypeScript files change

Here's an alternative to the HeberLZ's answer, using npm scripts.

My package.json:

  "scripts": {
    "watch": "nodemon -e ts -w ./src -x npm run watch:serve",
    "watch:serve": "ts-node --inspect src/index.ts"
  },
  • -e flag sets the extenstions to look for,
  • -w sets the watched directory,
  • -x executes the script.

--inspect in the watch:serve script is actually a node.js flag, it just enables debugging protocol.

WMI "installed" query different from add/remove programs list?

Besides the most commonly known registry key for installed programs:

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Uninstall

wmic command and the add/remove programs also query another registry key:

HKEY_CLASSES_ROOT\Installer\Products

Software name shown in the list is read from the Value of a Data entry within this key called: ProductName

Removing the registry key for a certain product from both of the above locations will keep it from showing in the add/remove programs list. This is not a method to uninstall programs, it will just remove the entry from what's known to windows as installed software.

Since, by using this method you would lose the chance of using the Remove button from the add/remove list to cleanly remove the software from your system; it's recommended to export registry keys to a file before you delete them. In future, if you decided to bring that item back to the list, you would simply run the registry file you stored.

Understanding SQL Server LOCKS on SELECT queries

select with no lock - will select records which may / may not going to be inserted. you will read a dirty data.

for example - lets say a transaction insert 1000 rows and then fails.

when you select - you will get the 1000 rows.

Apply Calibri (Body) font to text

If there is space between the letters of the font, you need to use quote.

font-family:"Calibri (Body)";

javascript return true or return false when and how to use it?

returning true or false indicates that whether execution should continue or stop right there. So just an example

<input type="button" onclick="return func();" />

Now if func() is defined like this

function func()
{
 // do something
return false;
}

the click event will never get executed. On the contrary if return true is written then the click event will always be executed.

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.

I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:

void find_squares(Mat& image, vector<vector<Point> >& squares)
{
    // blur will enhance edge detection
    Mat blurred(image);
    medianBlur(image, blurred, 9);

    Mat gray0(blurred.size(), CV_8U), gray;
    vector<vector<Point> > contours;

    // find squares in every color plane of the image
    for (int c = 0; c < 3; c++)
    {
        int ch[] = {c, 0};
        mixChannels(&blurred, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        const int threshold_level = 2;
        for (int l = 0; l < threshold_level; l++)
        {
            // Use Canny instead of zero threshold level!
            // Canny helps to catch squares with gradient shading
            if (l == 0)
            {
                Canny(gray0, gray, 10, 20, 3); // 

                // Dilate helps to remove potential holes between edge segments
                dilate(gray, gray, Mat(), Point(-1,-1));
            }
            else
            {
                    gray = gray0 >= (l+1) * 255 / threshold_level;
            }

            // Find contours and store them in a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            // Test contours
            vector<Point> approx;
            for (size_t i = 0; i < contours.size(); i++)
            {
                    // approximate contour with accuracy proportional
                    // to the contour perimeter
                    approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

                    // Note: absolute value of an area is used because
                    // area may be positive or negative - in accordance with the
                    // contour orientation
                    if (approx.size() == 4 &&
                            fabs(contourArea(Mat(approx))) > 1000 &&
                            isContourConvex(Mat(approx)))
                    {
                            double maxCosine = 0;

                            for (int j = 2; j < 5; j++)
                            {
                                    double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                                    maxCosine = MAX(maxCosine, cosine);
                            }

                            if (maxCosine < 0.3)
                                    squares.push_back(approx);
                    }
            }
        }
    }
}

After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >:

opencv paper sheet detection

I'm letting you write the function to find the largest square. ;)

How to automatically add user account AND password with a Bash script?

You can use expect in your bash script.

From http://www.seanodonnell.com/code/?id=21

#!/usr/bin/expect 
######################################### 
#$ file: htpasswd.sh 
#$ desc: Automated htpasswd shell script 
######################################### 
#$ 
#$ usage example: 
#$ 
#$ ./htpasswd.sh passwdpath username userpass 
#$ 
###################################### 

set htpasswdpath [lindex $argv 0] 
set username [lindex $argv 1] 
set userpass [lindex $argv 2] 

# spawn the htpasswd command process 
spawn htpasswd $htpasswdpath $username 

# Automate the 'New password' Procedure 
expect "New password:" 
send "$userpass\r" 

expect "Re-type new password:" 
send "$userpass\r"

Regular expression to match a line that doesn't contain a word

A simpler solution is to use the not operator !

Your if statement will need to match "contains" and not match "excludes".

var contains = /abc/;
var excludes =/hede/;

if(string.match(contains) && !(string.match(excludes))){  //proceed...

I believe the designers of RegEx anticipated the use of not operators.

Select <a> which href ends with some string

   $('a[href$="ABC"]')...

Selector documentation can be found at http://docs.jquery.com/Selectors

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

How to catch and print the full exception traceback without halting/exiting the program?

If you have an Error object already, and you want to print the whole thing, you need to make this slightly awkward call:

import traceback
traceback.print_exception(type(err), err, err.__traceback__)

That's right, print_exception takes three positional arguments: The type of the exception, the actual exception object, and the exception's own internal traceback property.

In python 3.5 or later, the type(err) is optional... but it's a positional argument, so you still have to explicitly pass None in its place.

traceback.print_exception(None, err, err.__traceback__)

I have no idea why all of this isn't just traceback.print_exception(err). Why you would ever want to print out an error, along with a traceback other than the one that belongs to that error, is beyond me.

Use basic authentication with jQuery and Ajax

The examples above are a bit confusing, and this is probably the best way:

$.ajaxSetup({
  headers: {
    'Authorization': "Basic " + btoa(USERNAME + ":" + PASSWORD)
  }
});

I took the above from a combination of Rico and Yossi's answer.

The btoa function Base64 encodes a string.

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

There should be no problem with some manual implementation like the one mentioned by @oozic.

Here are a couple of libs you could take a look at:

  • Response.js - jQuery plugin - make use of html data attributes and also has a js api.
  • enquire.js - enquire.js is a lightweight, pure JavaScript library for responding to CSS media queries
  • SimpleStateManager - s a javascript state manager for responsive websites. It is built to be light weight, has no dependencies.

Note that these libs are designed to work independently of bootstrap, foundation, etc. You can configure your own breakpoints and have fun.

How can I extract the folder path from file path in Python?

Here is the code:

import os
existGDBPath = r'T:\Data\DBDesign\DBDesign_93_v141b.mdb'
wkspFldr = os.path.dirname(existGDBPath)
print wkspFldr # T:\Data\DBDesign

git revert back to certain commit

http://www.kernel.org/pub/software/scm/git/docs/git-revert.html

using git revert <commit> will create a new commit that reverts the one you dont want to have.

You can specify a list of commits to revert.

An alternative: http://git-scm.com/docs/git-reset

git reset will reset your copy to the commit you want.

Programmatically getting the MAC of an Android device

public static String getMacAddr() {
    try {
        List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
        for (NetworkInterface nif : all) {
            if (!nif.getName().equalsIgnoreCase("wlan0")) continue;

            byte[] macBytes = nif.getHardwareAddress();
            if (macBytes == null) {
                return "";
            }

            StringBuilder res1 = new StringBuilder();
            for (byte b : macBytes) {
                res1.append(String.format("%02X:",b));
            }

            if (res1.length() > 0) {
                res1.deleteCharAt(res1.length() - 1);
            }
            return res1.toString();
        }
    } catch (Exception ex) {
    }
    return "02:00:00:00:00:00";
}

Why does an SSH remote command get fewer environment variables then when run manually?

How about sourcing the profile before running the command?

ssh user@host "source /etc/profile; /path/script.sh"

You might find it best to change that to ~/.bash_profile, ~/.bashrc, or whatever.

(As here (linuxquestions.org))

How to post JSON to a server using C#?

I finally invoked in sync mode by including the .Result

HttpResponseMessage response = null;
try
{
    using (var client = new HttpClient())
    {
       response = client.PostAsync(
        "http://localhost:8000/....",
         new StringContent(myJson,Encoding.UTF8,"application/json")).Result;
    if (response.IsSuccessStatusCode)
        {
            MessageBox.Show("OK");              
        }
        else
        {
            MessageBox.Show("NOK");
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show("ERROR");
}

RecyclerView expand/collapse items

Use two view types in the your RVAdapter. One for expanded layout and other for collapsed. And the magic happens with setting android:animateLayoutChanges="true" for RecyclerView Checkout the effect achieved using this at 0:42 in this video

Free Online Team Foundation Server

I know this thread is old, but since a Google search brought me here, it will also do to other people who may find this useful.

Microsoft recenly launched Visual Studio Online, which is free for projects with up to 5 users:

http://www.visualstudio.com/en-us/products/visual-studio-online-overview-vs.aspx

I have been using it for a while, and it integrates completely with Visual Studio 2013. It claims integration with other IDEs too. Apart from TFS, Git can also be used with it.

I know this thread is old, but since a Google search brought me here

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

None of these worked for me. So as I compared various app pools with one that worked vs one that didn't, I had to go into Advanced Settings for the App Pool, and set

Enable 32-Bit Applications = true

Then it worked fine!

Regex to validate date format dd/mm/yyyy

Please Following Expression

Regex regex = new Regex(@"(((0|1)[0-9]|2[0-9]|3[0-1])\/(0[1-9]|1[0-2])\/((19|20)\d\d))$");

How do I create a HTTP Client Request with a cookie?

You can do that using Requestify, a very simple and cool HTTP client I wrote for nodeJS, it support easy use of cookies and it also supports caching.

To perform a request with a cookie attached just do the following:

var requestify = require('requestify');
requestify.post('http://google.com', {}, {
    cookies: {
        sessionCookie: 'session-cookie-data'   
    }
});

Create a day-of-week column in a Pandas dataframe using Python

Just in case if .dt doesn't work for you. Trying .DatetimeIndex might help. Hope the code and our test result here help you fix it. Regards,

import pandas as pd
import datetime

df = pd.DataFrame({'Date':['2015-01-01','2015-01-02','2015-01-03'],'Number':[1,2,3]})

df['Day'] = pd.DatetimeIndex(df['Date']).day_name() # week day name
df.head()

enter image description here

how to stop a loop arduino

The three options that come to mind:

1st) End void loop() with while(1)... or equally as good... while(true)

void loop(){
    //the code you want to run once here, 
    //e.g., If (blah == blah)...etc.

    while(1)        //last line of main loop
}

This option runs your code once and then kicks the Ard into an endless "invisible" loop. Perhaps not the nicest way to go, but as far as outside appearances, it gets the job done.
The Ard will continue to draw current while it spins itself in an endless circle... perhaps one could set up a sort of timer function that puts the Ard to sleep after so many seconds, minutes, etc., of looping... just a thought... there are certainly various sleep libraries out there... see e.g., Monk, Programming Arduino: Next Steps, pgs., 85-100 for further discussion of such.

2nd) Create a "stop main loop" function with a conditional control structure that makes its initial test fail on a second pass.
This often requires declaring a global variable and having the "stop main loop" function toggle the value of the variable upon termination. E.g.,

boolean stop_it = false;         //global variable

void setup(){
    Serial.begin(9600); 
    //blah...
}

boolean stop_main_loop(){        //fancy stop main loop function

    if(stop_it == false){   //which it will be the first time through

        Serial.println("This should print once.");

       //then do some more blah....you can locate all the
       // code you want to run once here....eventually end by 
       //toggling the "stop_it" variable ... 
    }
    stop_it = true; //...like this
    return stop_it;   //then send this newly updated "stop_it" value
                     // outside the function
}

void loop{ 

    stop_it = stop_main_loop();     //and finally catch that updated 
                                    //value and store it in the global stop_it 
                                    //variable, effectively 
                                    //halting the loop  ...
}

Granted, this might not be especially pretty, but it also works.
It kicks the Ard into another endless "invisible" loop, but this time it's a case of repeatedly checking the if(stop_it == false) condition in stop_main_loop() which of course fails to pass every time after the first time through.

3rd) One could once again use a global variable but use a simple if (test == blah){} structure instead of a fancy "stop main loop" function.

boolean start = true;                  //global variable

void setup(){

      Serial.begin(9600);
}

void loop(){

      if(start == true){           //which it will be the first time through



           Serial.println("This should print once.");       

           //the code you want to run once here, 
           //e.g., more If (blah == blah)...etc.

     }

start = false;                //toggle value of global "start" variable
                              //Next time around, the if test is sure to fail.
}

There are certainly other ways to "stop" that pesky endless main loop but these three as well as those already mentioned should get you started.

How to display image with JavaScript?

You could make use of the Javascript DOM API. In particular, look at the createElement() method.

You could create a re-usable function that will create an image like so...

function show_image(src, width, height, alt) {
    var img = document.createElement("img");
    img.src = src;
    img.width = width;
    img.height = height;
    img.alt = alt;

    // This next line will just add it to the <body> tag
    document.body.appendChild(img);
}

Then you could use it like this...

<button onclick=
    "show_image('http://google.com/images/logo.gif', 
                 276, 
                 110, 
                 'Google Logo');">Add Google Logo</button> 

See a working example on jsFiddle: http://jsfiddle.net/Bc6Et/

MySQL maximum memory usage

mysqld.exe was using 480 mb in RAM. I found that I added this parameter to my.ini

table_definition_cache = 400

that reduced memory usage from 400,000+ kb down to 105,000kb

Force DOM redraw/refresh on Chrome/Mac

None of the above answers worked for me. I did notice that resizing my window did cause a redraw. So this did it for me:

$(window).trigger('resize');

Limiting double to 3 decimal places

If your purpose in truncating the digits is for display reasons, then you just just use an appropriate formatting when you convert the double to a string.

Methods like String.Format() and Console.WriteLine() (and others) allow you to limit the number of digits of precision a value is formatted with.

Attempting to "truncate" floating point numbers is ill advised - floating point numbers don't have a precise decimal representation in many cases. Applying an approach like scaling the number up, truncating it, and then scaling it down could easily change the value to something quite different from what you'd expected for the "truncated" value.

If you need precise decimal representations of a number you should be using decimal rather than double or float.

How do I check if a string is unicode or ascii?

If your code needs to be compatible with both Python 2 and Python 3, you can't directly use things like isinstance(s,bytes) or isinstance(s,unicode) without wrapping them in either try/except or a python version test, because bytes is undefined in Python 2 and unicode is undefined in Python 3.

There are some ugly workarounds. An extremely ugly one is to compare the name of the type, instead of comparing the type itself. Here's an example:

# convert bytes (python 3) or unicode (python 2) to str
if str(type(s)) == "<class 'bytes'>":
    # only possible in Python 3
    s = s.decode('ascii')  # or  s = str(s)[2:-1]
elif str(type(s)) == "<type 'unicode'>":
    # only possible in Python 2
    s = str(s)

An arguably slightly less ugly workaround is to check the Python version number, e.g.:

if sys.version_info >= (3,0,0):
    # for Python 3
    if isinstance(s, bytes):
        s = s.decode('ascii')  # or  s = str(s)[2:-1]
else:
    # for Python 2
    if isinstance(s, unicode):
        s = str(s)

Those are both unpythonic, and most of the time there's probably a better way.

How to check if a line has one of the strings in a list?

This still loops through the cartesian product of the two lists, but it does it one line:

>>> lines1 = ['soup', 'butter', 'venison']
>>> lines2 = ['prune', 'rye', 'turkey']
>>> search_strings = ['a', 'b', 'c']
>>> any(s in l for l in lines1 for s in search_strings)
True
>>> any(s in l for l in lines2 for s in search_strings)
False

This also have the advantage that any short-circuits, and so the looping stops as soon as a match is found. Also, this only finds the first occurrence of a string from search_strings in linesX. If you want to find multiple occurrences you could do something like this:

>>> lines3 = ['corn', 'butter', 'apples']
>>> [(s, l) for l in lines3 for s in search_strings if s in l]
[('c', 'corn'), ('b', 'butter'), ('a', 'apples')]

If you feel like coding something more complex, it seems the Aho-Corasick algorithm can test for the presence of multiple substrings in a given input string. (Thanks to Niklas B. for pointing that out.) I still think it would result in quadratic performance for your use-case since you'll still have to call it multiple times to search multiple lines. However, it would beat the above (cubic, on average) algorithm.

reading and parsing a TSV file, then manipulating it for saving as CSV (*efficiently*)

You should use the csv module to read the tab-separated value file. Do not read it into memory in one go. Each row you read has all the information you need to write rows to the output CSV file, after all. Keep the output file open throughout.

import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows([row[2:4] for _ in range(count)])

or, using the itertools module to do the repeating with itertools.repeat():

from itertools import repeat
import csv

with open('sample.txt', newline='') as tsvin, open('new.csv', 'w', newline='') as csvout:
    tsvin = csv.reader(tsvin, delimiter='\t')
    csvout = csv.writer(csvout)

    for row in tsvin:
        count = int(row[4])
        if count > 0:
            csvout.writerows(repeat(row[2:4], count))

Aren't Python strings immutable? Then why does a + " " + b work?

>>> a = 'dogs'

>>> a.replace('dogs', 'dogs eat treats')

'dogs eat treats'

>>> print a

'dogs'

Immutable, isn't it?!

The variable change part has already been discussed.

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

Using query-string module is the recommended one when you need a module to parse your query string in ease.

http://localhost:3000?token=xxx-xxx-xxx

componentWillMount() {
    var query = queryString.parse(this.props.location.search);
    if (query.token) {
        window.localStorage.setItem("jwt", query.token);
        store.dispatch(push("/"));
    }
}

Here, I am redirecting back to my client from Node.js server after successful Google-Passport authentication, which is redirecting back with token as query param.

I am parsing it with query-string module, saving it and updating the query params in the url with push from react-router-redux.