Programs & Examples On #Request validation

IOError: [Errno 2] No such file or directory trying to open a file

Hmm, there are a few things going wrong here.

for f in os.listdir(src_dir):
    os.path.join(src_dir, f)

You're not storing the result of join. This should be something like:

for f in os.listdir(src_dir):
    f = os.path.join(src_dir, f)

This open call is is the cause of your IOError. (Because without storing the result of the join above, f was still just 'file.csv', not 'src_dir/file.csv'.)

Also, the syntax:

with open(f): 

is close, but the syntax isn't quite right. It should be with open(file_name) as file_object:. Then, you use to the file_object to perform read or write operations.

And finally:

write(line)

You told python what you wanted to write, but not where to write it. Write is a method on the file object. Try file_object.write(line).

Edit: You're also clobbering your input file. You probably want to open the output file and write lines to it as you're reading them in from the input file.

See: input / output in python.

How to move text up using CSS when nothing is working

try a negative margin.

margin-top: -10px; /* as an example */

Java - Abstract class to contain variables?

Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class

Linker Error C++ "undefined reference "

This error tells you everything:

undefined reference toHash::insert(int, char)

You're not linking with the implementations of functions defined in Hash.h. Don't you have a Hash.cpp to also compile and link?

Android load from URL to Bitmap

public static Bitmap getBitmapFromURL(String src) {
    try {
        URL url = new URL(src);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        // Log exception
        return null;
    }
}

Count character occurrences in a string in C++

I would have done something like that :)

const char* str = "bla_bla_blabla_bla";
char* p = str;    
unsigned int count = 0;
while (*p != '\0')
    if (*p++ == '_')
        count++;

How to find which version of Oracle is installed on a Linux server (In terminal)

As the user running the Oracle Database one can also try $ORACLE_HOME/OPatch/opatch lsinventory which shows the exact version and patches installed.

For example this is a quick oneliner which should only return the version number:

$ORACLE_HOME/OPatch/opatch lsinventory | awk '/^Oracle Database/ {print $NF}'

Why maven? What are the benefits?

Maven is a powerful project management tool that is based on POM (project object model). It is used for projects build, dependency and documentation. It simplifies the build process like ANT. But it is too much advanced than ANT. Maven helps to manage- Builds,Documentation,Reporing,SCMs,Releases,Distribution. - maven repository is a directory of packaged JAR file with pom.xml file. Maven searches for dependencies in the repositories.

How do I convert a number to a letter in Java?

public static string IntToLetters(int value)
{
string result = string.Empty;
while (--value >= 0)
{
    result = (char)('A' + value % 26 ) + result;
    value /= 26;
}
return result;
}

To meet the requirement of A being 1 instead of 0, I've added -- to the while loop condition, and removed the value-- from the end of the loop, if anyone wants this to be 0 for their own purposes, you can reverse the changes, or simply add value++; at the beginning of the entire method.

How do I set <table> border width with CSS?

The default border-style is none, so you must specify that as well as the width and the colour.

You can use the border shorthand property to set all three values in one go.

Also, the border attribute describes the border for the table and the cells. CSS is much more flexible so it only describes the border of the elements you are selecting. You need to select the cells too in order to get the same effect.

table, th, td {
    border: solid black 1px;
}

See also border properties and tables in CSS.

Search text in fields in every table of a MySQL database

In case 23 answers is not enough, here are 2 more... Depending on database structure and content, you may find one them to actually be a quick and simple solution.

For fans of shell one-liners, here is a long one (actually on 2 lines to use variables):

cmd='mysql -u Username -pYour_Password -D Your_Database' # <-- Adapt this

$cmd -s -e 'SHOW TABLES' | while read table; do echo "=== $table ==="; $cmd -B -s -e "SELECT * FROM $table" | grep 'Your_Search'; done

Or on multiple lines to make it more readable:

$cmd -s -e 'SHOW TABLES' \
| while read table; do
    echo "=== $table ===";
    $cmd -B -s -e "SELECT * FROM $table" \
    | grep 'Your_Search';
  done
  • -s (--silent) is to suppress the column name headers

  • -B (--batch) escapes special characters like newlines, so we get the whole record when using grep

And for Perl fans, this will let you use regular expressions:

# perl -MDBI -le '($db,$u,$p)=@ARGV; $dbh=DBI->connect("dbi:mysql:dbname=$db",$u,$p); foreach $table ($dbh->tables()) {print "$table\n"; foreach $r ($dbh->selectall_array("SELECT * FROM $table")) {$_=join("\t", @$r); print $_ if (/Your_Regex/);}}' Your_Database Username Your_Password

Which in a "real" Perl script could be something like this:

#!/usr/bin/perl

use strict;
use open qw(:std :utf8);

use DBI;

my $db_host  = 'localhost';
my $db       = 'Your_Database';
my $db_user  = 'Username';
my $db_pass  = 'Your_Password';

my $search    = qr/Your_regex_Search/;


# https://metacpan.org/pod/DBD::mysql
my $dbh = DBI->connect( "dbi:mysql:dbname=$db;host=$db_host", $db_user, $db_pass,
                        { mysql_enable_utf8mb4 => 1 }
) or die "Can't connect: $DBI::errstr\n";


foreach my $table ( $dbh->tables() ) {
    my $sth = $dbh->prepare("SELECT * FROM $table")
        or die "Can't prepare: ", $dbh->errstr;

    $sth->execute
        or die "Can't execute: ", $sth->errstr;

    my @results;

    while (my @row = $sth->fetchrow()) {
        local $_ = join("\t", @row);
        if ( /$search/ ) {
            push @results, $_;
        }
    }

    $sth->finish;

    next unless @results;

    print "*** TABLE $table :\n",
          join("\n---------------\n", @results),
          "\n" . "=" x 20 . "\n";
}

$dbh->disconnect;

How to allow user to pick the image with Swift?

here is an easy way to do it:

but first you have to add ( Privacy - Photo Library Usage Description ) in the info.plist, and you should have a button and a UIImageView in your viewController.

then create an outlet of the UIImageView ( in this code the outlet is called myImage), and an action of the button ( I called the action importing in my code )

import UIKit
class ViewController: UIViewController, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

    }
    @IBOutlet weak var myImage: UIImageView!
    @IBAction func importing(_ sender: Any) {
        let Picker = UIImagePickerController()
        Picker.delegate = self
        Picker.sourceType = .photoLibrary
        self.present(Picker, animated: true, completion: nil)
        Picker.allowsEditing = true
        Picker.mediaTypes = UIImagePickerController.availableMediaTypes(for: .photoLibrary)!
    }

     func imagePickerController(_ picker: UIImagePickerController,didFinishPickingMediaWithInfo info: [String : Any])
    {
        let chosenImage = info[UIImagePickerControllerOriginalImage] as! UIImage //1
        myImage.contentMode = .scaleAspectFit //2
        myImage.image = chosenImage //3
        dismiss(animated:true, completion: nil) //4
    }

}

Suppress Scientific Notation in Numpy When Creating Array From Nested List

Python Force-suppress all exponential notation when printing numpy ndarrays, wrangle text justification, rounding and print options:

What follows is an explanation for what is going on, scroll to bottom for code demos.

Passing parameter suppress=True to function set_printoptions works only for numbers that fit in the default 8 character space allotted to it, like this:

import numpy as np
np.set_printoptions(suppress=True) #prevent numpy exponential 
                                   #notation on print, default False

#            tiny     med  large
a = np.array([1.01e-5, 22, 1.2345678e7])  #notice how index 2 is 8 
                                          #digits wide

print(a)    #prints [ 0.0000101   22.     12345678. ]

However if you pass in a number greater than 8 characters wide, exponential notation is imposed again, like this:

np.set_printoptions(suppress=True)

a = np.array([1.01e-5, 22, 1.2345678e10])    #notice how index 2 is 10
                                             #digits wide, too wide!

#exponential notation where we've told it not to!
print(a)    #prints [1.01000000e-005   2.20000000e+001   1.23456780e+10]

numpy has a choice between chopping your number in half thus misrepresenting it, or forcing exponential notation, it chooses the latter.

Here comes set_printoptions(formatter=...) to the rescue to specify options for printing and rounding. Tell set_printoptions to just print bare a bare float:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:f}'.format})

a = np.array([1.01e-5, 22, 1.2345678e30])  #notice how index 2 is 30
                                           #digits wide.  

#Ok good, no exponential notation in the large numbers:
print(a)  #prints [0.000010 22.000000 1234567799999999979944197226496.000000] 

We've force-suppressed the exponential notation, but it is not rounded or justified, so specify extra formatting options:

np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:0.2f}'.format})  #float, 2 units 
                                               #precision right, 0 on left

a = np.array([1.01e-5, 22, 1.2345678e30])   #notice how index 2 is 30
                                            #digits wide

print(a)  #prints [0.00 22.00 1234567799999999979944197226496.00]

The drawback for force-suppressing all exponential notion in ndarrays is that if your ndarray gets a huge float value near infinity in it, and you print it, you're going to get blasted in the face with a page full of numbers.

Full example Demo 1:

from pprint import pprint
import numpy as np
#chaotic python list of lists with very different numeric magnitudes
my_list = [[3.74, 5162, 13683628846.64, 12783387559.86, 1.81],
           [9.55, 116, 189688622.37, 260332262.0, 1.97],
           [2.2, 768, 6004865.13, 5759960.98, 1.21],
           [3.74, 4062, 3263822121.39, 3066869087.9, 1.93],
           [1.91, 474, 44555062.72, 44555062.72, 0.41],
           [5.8, 5006, 8254968918.1, 7446788272.74, 3.25],
           [4.5, 7887, 30078971595.46, 27814989471.31, 2.18],
           [7.03, 116, 66252511.46, 81109291.0, 1.56],
           [6.52, 116, 47674230.76, 57686991.0, 1.43],
           [1.85, 623, 3002631.96, 2899484.08, 0.64],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32],
           [13.76, 1227, 1737874137.5, 1446511574.32, 4.32]]

#convert python list of lists to numpy ndarray called my_array
my_array = np.array(my_list)

#This is a little recursive helper function converts all nested 
#ndarrays to python list of lists so that pretty printer knows what to do.
def arrayToList(arr):
    if type(arr) == type(np.array):
        #If the passed type is an ndarray then convert it to a list and
        #recursively convert all nested types
        return arrayToList(arr.tolist())
    else:
        #if item isn't an ndarray leave it as is.
        return arr

#suppress exponential notation, define an appropriate float formatter
#specify stdout line width and let pretty print do the work
np.set_printoptions(suppress=True,
   formatter={'float_kind':'{:16.3f}'.format}, linewidth=130)
pprint(arrayToList(my_array))

Prints:

array([[           3.740,         5162.000,  13683628846.640,  12783387559.860,            1.810],
       [           9.550,          116.000,    189688622.370,    260332262.000,            1.970],
       [           2.200,          768.000,      6004865.130,      5759960.980,            1.210],
       [           3.740,         4062.000,   3263822121.390,   3066869087.900,            1.930],
       [           1.910,          474.000,     44555062.720,     44555062.720,            0.410],
       [           5.800,         5006.000,   8254968918.100,   7446788272.740,            3.250],
       [           4.500,         7887.000,  30078971595.460,  27814989471.310,            2.180],
       [           7.030,          116.000,     66252511.460,     81109291.000,            1.560],
       [           6.520,          116.000,     47674230.760,     57686991.000,            1.430],
       [           1.850,          623.000,      3002631.960,      2899484.080,            0.640],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320],
       [          13.760,         1227.000,   1737874137.500,   1446511574.320,            4.320]])

Full example Demo 2:

import numpy as np  
#chaotic python list of lists with very different numeric magnitudes 

#            very tiny      medium size            large sized
#            numbers        numbers                numbers

my_list = [[0.000000000074, 5162, 13683628846.64, 1.01e10, 1.81], 
           [1.000000000055,  116, 189688622.37, 260332262.0, 1.97], 
           [0.010000000022,  768, 6004865.13,   -99e13, 1.21], 
           [1.000000000074, 4062, 3263822121.39, 3066869087.9, 1.93], 
           [2.91,            474, 44555062.72, 44555062.72, 0.41], 
           [5,              5006, 8254968918.1, 7446788272.74, 3.25], 
           [0.01,           7887, 30078971595.46, 27814989471.31, 2.18], 
           [7.03,            116, 66252511.46, 81109291.0, 1.56], 
           [6.52,            116, 47674230.76, 57686991.0, 1.43], 
           [1.85,            623, 3002631.96, 2899484.08, 0.64], 
           [13.76,          1227, 1737874137.5, 1446511574.32, 4.32], 
           [13.76,          1337, 1737874137.5, 1446511574.32, 4.32]] 
import sys 
#convert python list of lists to numpy ndarray called my_array 
my_array = np.array(my_list) 
#following two lines do the same thing, showing that np.savetxt can 
#correctly handle python lists of lists and numpy 2D ndarrays. 
np.savetxt(sys.stdout, my_list, '%19.2f') 
np.savetxt(sys.stdout, my_array, '%19.2f') 

Prints:

 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32
 0.00             5162.00      13683628846.64      10100000000.00              1.81
 1.00              116.00        189688622.37        260332262.00              1.97
 0.01              768.00          6004865.13 -990000000000000.00              1.21
 1.00             4062.00       3263822121.39       3066869087.90              1.93
 2.91              474.00         44555062.72         44555062.72              0.41
 5.00             5006.00       8254968918.10       7446788272.74              3.25
 0.01             7887.00      30078971595.46      27814989471.31              2.18
 7.03              116.00         66252511.46         81109291.00              1.56
 6.52              116.00         47674230.76         57686991.00              1.43
 1.85              623.00          3002631.96          2899484.08              0.64
13.76             1227.00       1737874137.50       1446511574.32              4.32
13.76             1337.00       1737874137.50       1446511574.32              4.32

Notice that rounding is consistent at 2 units precision, and exponential notation is suppressed in both the very large e+x and very small e-x ranges.

max(length(field)) in mysql

Use CHAR_LENGTH() instead-of LENGTH() as suggested in: MySQL - length() vs char_length()

SELECT name, CHAR_LENGTH(name) AS mlen FROM mytable ORDER BY mlen DESC LIMIT 1

What does the arrow operator, '->', do in Java?

This one is useful as well when you want to implement a functional interface

Runnable r = ()-> System.out.print("Run method");

is equivalent to

Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.print("Run method");
        }
};

Javascript counting number of objects in object

Try Demo Here

var list ={}; var count= Object.keys(list).length;

Excel: How to check if a cell is empty with VBA?

You could use IsEmpty() function like this:

...
Set rRng = Sheet1.Range("A10")
If IsEmpty(rRng.Value) Then ...

you could also use following:

If ActiveCell.Value = vbNullString Then ...

Android Material: Status bar color won't change

I know this doesn't answer the question, but with Material Design (API 21+) we can change the color of the status bar by adding this line in the theme declaration in styles.xml:

<!-- MAIN THEME -->
<style name="AppTheme" parent="@android:style/Theme.Material.Light">
    <item name="android:actionBarStyle">@style/actionBarCustomization</item>
    <item name="android:spinnerDropDownItemStyle">@style/mySpinnerDropDownItemStyle</item>
    <item name="android:spinnerItemStyle">@style/mySpinnerItemStyle</item>
    <item name="android:colorButtonNormal">@color/myDarkBlue</item>
    <item name="android:statusBarColor">@color/black</item>
</style>

Notice the android:statusBarColor, where we can define the color, otherwise the default is used.

Is there a way to split a widescreen monitor in to two or more virtual monitors?

The only software that I found that already exists is Matrox PowerDesk. Among other things it lets you split a monitor into 2 virtual desktops. You have to have a compatible matrox video card though. It also does a bunch of other multi-monitor functions.

Convert JSON array to Python list

data will return you a string representation of a list, but it is actually still a string. Just check the type of data with type(data). That means if you try using indexing on this string representation of a list as such data['fruits'][0], it will return you "[" as it is the first character of data['fruits']

You can do json.loads(data['fruits']) to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here

sqlite copy data from one table to another

INSERT INTO Destination SELECT * FROM Source;

See SQL As Understood By SQLite: INSERT for a formal definition.

Pick a random value from an enum?

It's probably easiest to have a function to pick a random value from an array. This is more generic, and is straightforward to call.

<T> T randomValue(T[] values) {
    return values[mRandom.nextInt(values.length)];
}

Call like so:

MyEnum value = randomValue(MyEnum.values());

How to set environment variables in Jenkins?

In my case, I needed to add the JMETER_HOME environment variable to be available via my Ant build scripts across all projects on my Jenkins server (Linux), in a way that would not interfere with my local build environment (Windows and Mac) in the build.xml script. Setting the environment variable via Manage Jenkins - Configure System - Global properties was the easiest and least intrusive way to accomplish this. No plug-ins are necessary.

Manage Jenkins Global Properties


The environment variable is then available in Ant via:

<property environment="env" />
<property name="jmeter.home" value="${env.JMETER_HOME}" />

This can be verified to works by adding:

<echo message="JMeter Home: ${jmeter.home}"/>

Which produces:

JMeter Home: ~/.jmeter

How do I pass an object from one activity to another on Android?

This answer is specific to situations where the objects to be passed has nested class structure. With nested class structure, making it Parcelable or Serializeable is a bit tedious. And, the process of serialising an object is not efficient on Android. Consider the example below,

class Myclass    {
  int a;
  class SubClass    {
       int b;
  }
}

With Google's GSON library, you can directly parse an object into a JSON formatted String and convert it back to the object format after usage. For example,

MyClass src = new MyClass();
Gson gS = new Gson();
String target = gS.toJson(src); // Converts the object to a JSON String

Now you can pass this String across activities as a StringExtra with the activity intent.

Intent i = new Intent(FromActivity.this, ToActivity.class);
i.putExtra("MyObjectAsString", target);

Then in the receiving activity, create the original object from the string representation.

String target = getIntent().getStringExtra("MyObjectAsString");
MyClass src = gS.fromJson(target, MyClass.class); // Converts the JSON String to an Object

It keeps the original classes clean and reusable. Above of all, if these class objects are created from the web as JSON objects, then this solution is very efficient and time saving.

UPDATE


While the above explained method works for most situations, for obvious performance reasons, do not rely on Android's bundled-extra system to pass objects around. There are a number of solutions makes this process flexible and efficient, here are a few. Each has its own pros and cons.

  1. Eventbus
  2. Otto

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

Change the project theme in Android Studio?

In Manifest theme sets with style name (AppTheme and myDialog)/ You can set new styles in styles.xml

        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity
        android:name=".MyActivity2"
        android:label="@string/title_activity_my_activity2"
        android:theme="@style/myDialog"
        >
    </activity>
</application>

styles.xml example

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Black">
    <!-- Customize your theme here. -->
</style>

<style name="myDialog" parent="android:Theme.Dialog">

</style>

In parent you set actualy the theme

Bash script to cd to directory with spaces in pathname

When working under Linux the syntax below is right:

cd ~/My\ Code

However when you're executing your file, use the syntax below:

$ . cdcode

(just '.' and not './')

Using strtok with a std::string

First off I would say use boost tokenizer.
Alternatively if your data is space separated then the string stream library is very useful.

But both the above have already been covered.
So as a third C-Like alternative I propose copying the std::string into a buffer for modification.

std::string   data("The data I want to tokenize");

// Create a buffer of the correct length:
std::vector<char>  buffer(data.size()+1);

// copy the string into the buffer
strcpy(&buffer[0],data.c_str());

// Tokenize
strtok(&buffer[0]," ");

Git Push ERROR: Repository not found

Had similar issue. The root of the problem was that I followed some online tutorial about adding a new repository to Github.

Just go to Github, create a new repo, it will ask you to add a README, don't add it. Create it, and you'll get instructions on how to push.

It's similar to the next two lines:

git remote add origin https://github.com/YOUR_USER/your-repo.git
git push -u origin master

What is duck typing?

I know I am not giving generalized answer. In Ruby, we don’t declare the types of variables or methods— everything is just some kind of object. So Rule is "Classes Aren’t Types"

In Ruby, the class is never (OK, almost never) the type. Instead, the type of an object is defined more by what that object can do. In Ruby, we call this duck typing. If an object walks like a duck and talks like a duck, then the interpreter is happy to treat it as if it were a duck.

For example, you may be writing a routine to add song information to a string. If you come from a C# or Java background, you may be tempted to write this:

def append_song(result, song)
    # test we're given the right parameters 
    unless result.kind_of?(String)
        fail TypeError.new("String expected") end
    unless song.kind_of?(Song)
        fail TypeError.new("Song expected")
end

result << song.title << " (" << song.artist << ")" end
result = ""

append_song(result, song) # => "I Got Rhythm (Gene Kelly)"

Embrace Ruby’s duck typing, and you’d write something far simpler:

def append_song(result, song)
    result << song.title << " (" << song.artist << ")"
end

result = ""
append_song(result, song) # => "I Got Rhythm (Gene Kelly)"

You don’t need to check the type of the arguments. If they support << (in the case of result) or title and artist (in the case of song), everything will just work. If they don’t, your method will throw an exception anyway (just as it would have done if you’d checked the types). But without the check, your method is suddenly a lot more flexible. You could pass it an array, a string, a file, or any other object that appends using <<, and it would just work.

jQuery on window resize

function myResizeFunction() {
  ...
}

$(function() {
  $(window).resize(myResizeFunction).trigger('resize');
});

This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize') to run on page load instead.

UPDATE: Here's another option if you don't want to make use of any other third-party libraries.

This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).

It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.

function myResizeFunction() {
  var $window = $(this),
      height = Math.ceil($window.height()),
      previousHeight = $window.data('previousHeight');

  if (height !== previousHeight) {
    if (height < 819)
      previousHeight >= 819 && $('.footer').removeClass('hgte819');
    else if (!previousHeight || previousHeight < 819)
      $('.footer').addClass('hgte819');

    $window.data('previousHeight', height);
  }
}

$(function() {
  $(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});

As an example, you might have the following as some of your CSS rules:

.footer {
  bottom: auto;
  left: auto;
  position: static;
}

.footer.hgte819 {
  bottom: 3px;
  left: 0;
  position: absolute;
}

How to pass command line arguments to a shell alias?

An empty alias will execute its args:

alias DEBUG=

How to scroll to an element inside a div?

If you are using jQuery, you could scroll with an animation using the following:

$(MyContainerDiv).animate({scrollTop: $(MyContainerDiv).scrollTop() + ($('element_within_div').offset().top - $(MyContainerDiv).offset().top)});

The animation is optional: you could also take the scrollTop value calculated above and put it directly in the container's scrollTop property.

Working with TIFFs (import, export) in Python using numpy

You can also use pytiff of which I'm the author.

    import pytiff

    with pytiff.Tiff("filename.tif") as handle:
        part = handle[100:200, 200:400]

    # multipage tif
    with pytiff.Tiff("multipage.tif") as handle:
        for page in handle:
            part = page[100:200, 200:400]

It's a fairly small module and may not have as many features as other modules, but it supports tiled tiffs and bigtiff, so you can read parts of large images.

Bringing a subview to be in front of all other views

Let me make a conclusion. In Swift 5

You can choose to addSubview to keyWindow, if you add the view in the last. Otherwise, you can bringSubViewToFront.

let view = UIView()
UIApplication.shared.keyWindow?.addSubview(view)
UIApplication.shared.keyWindow?.bringSubviewToFront(view)

You can also set the zPosition. But the drawback is that you can not change the gesture responding order.

view.layer.zPosition = 1

Copy a git repo without history

You can limit the depth of the history while cloning:

--depth <depth>
Create a shallow clone with a history truncated to the specified 
number of revisions.

Use this if you want limited history, but still some.

SQL not a single-group group function

Well the problem simply-put is that the SUM(TIME) for a specific SSN on your query is a single value, so it's objecting to MAX as it makes no sense (The maximum of a single value is meaningless).

Not sure what SQL database server you're using but I suspect you want a query more like this (Written with a MSSQL background - may need some translating to the sql server you're using):

SELECT TOP 1 SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
ORDER BY 2 DESC

This will give you the SSN with the highest total time and the total time for it.

Edit - If you have multiple with an equal time and want them all you would use:

SELECT
SSN, SUM(TIME)
FROM downloads
GROUP BY SSN
HAVING SUM(TIME)=(SELECT MAX(SUM(TIME)) FROM downloads GROUP BY SSN))

What is the quickest way to HTTP GET in Python?

You could use a library called requests.

import requests
r = requests.get("http://example.com/foo/bar")

This is quite easy. Then you can do like this:

>>> print(r.status_code)
>>> print(r.headers)
>>> print(r.content)

How do I connect to my existing Git repository using Visual Studio Code?

  1. Use git clone to clone your repository into a folder (say work). You should see a new subfolder, work/.git.
  2. Open folder work in Visual Studio Code - everything should work fine!

PS: Blow away the temporary folder.

When restoring a backup, how do I disconnect all active connections?

None of these were working for me, couldn't delete or disconnect current users. Also couldn't see any active connections to the DB. Restarting SQL Server (Right click and select Restart) allowed me to do it.

When to use NSInteger vs. int

On iOS, it currently does not matter if you use int or NSInteger. It will matter more if/when iOS moves to 64-bits.

Simply put, NSIntegers are ints in 32-bit code (and thus 32-bit long) and longs on 64-bit code (longs in 64-bit code are 64-bit wide, but 32-bit in 32-bit code). The most likely reason for using NSInteger instead of long is to not break existing 32-bit code (which uses ints).

CGFloat has the same issue: on 32-bit (at least on OS X), it's float; on 64-bit, it's double.

Update: With the introduction of the iPhone 5s, iPad Air, iPad Mini with Retina, and iOS 7, you can now build 64-bit code on iOS.

Update 2: Also, using NSIntegers helps with Swift code interoperability.

Show git diff on file in staging area

In order to see the changes that have been staged already, you can pass the -–staged option to git diff (in pre-1.6 versions of Git, use –-cached).

git diff --staged
git diff --cached

Difference between if () { } and if () : endif;

They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my .phtml files (Zend Framework) I will write something like this:

<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>

MS Excel showing the formula in a cell instead of the resulting value

I tried everything I could find but nothing worked. Then I highlighted the formula column and right-clicked and selected 'clear contents'. That worked! Now I see the results, not the formula.

Which font is used in Visual Studio Code Editor and how to change fonts?

For windows please follow these steps Goto - > File -> preferences -> settings
OR press CTRL + , (for windows only) you'll see settings page there find text editor option tab on left side then click on ' Font ' then add any valid font family name there which you want to apply to vscode.

Count if two criteria match - EXCEL formula

Add the sheet name infront of the cell, e.g.:

=COUNTIFS(stock!A:A,"M",stock!C:C,"Yes")

Assumes the sheet name is "stock"

Maximum concurrent Socket.IO connections

I tried to use socket.io on AWS, I can at most keep around 600 connections stable.

And I found out it is because socket.io used long polling first and upgraded to websocket later.

after I set the config to use websocket only, I can keep around 9000 connections.

Set this config at client side:

const socket = require('socket.io-client')
const conn = socket(host, { upgrade: false, transports: ['websocket'] })

How can I limit possible inputs in a HTML5 "number" element?

More relevant attributes to use would be min and max.

Convert DOS line endings to Linux line endings in Vim

The below command is used for reformating all .sh file in the current directory. I tested it on my Fedora OS.

for file in *.sh; do awk '{ sub("\r$", ""); print }' $file >luxubutmp; cp -f luxubutmp $file; rm -f luxubutmp ;done

Rename multiple files in a folder, add a prefix (Windows)

Free Software 'Bulk Rename Utility' also works well (and is powerful for advanced tasks also). Download and installation takes a minute.

See screenshots and tutorial on original website.

--

I cannot provide step-by-step screenshots as the images will have to be released under Creative Commons License, and I do not own the screenshots of the software.

Disclaimer: I am not associated with the said software/company in any way. I liked the product for my own task, it serves OP's and similar requirements, thus recommending.

How to set environment variables in PyCharm?

This functionality has been added to the IDE now (working Pycharm 2018.3)

Just click the EnvFile tab in the run configuration, click Enable EnvFile and click the + icon to add an env file

Example with the glorious material theme

Update: Essentially the same as the answer by @imguelvargasf but the the plugin was enabled by default for me.

jQuery: serialize() form and other parameters

I fix the problem with under statement ; send data with url same GET methode

$.ajax({
    url: 'includes/get_ajax_function.php?value=jack&id='+id,
    type: 'post',
    data: $('#b-info1').serializeArray(),

and get value with $_REQUEST['value'] OR $_GET['id']

Convert unsigned int to signed int C

@Mysticial got it. A short is usually 16-bit and will illustrate the answer:

int main()  
{
    unsigned int x = 65529;
    int y = (int) x;
    printf("%d\n", y);

    unsigned short z = 65529;
    short zz = (short)z;
    printf("%d\n", zz);
}

65529
-7
Press any key to continue . . .


A little more detail. It's all about how signed numbers are stored in memory. Do a search for twos-complement notation for more detail, but here are the basics.

So let's look at 65529 decimal. It can be represented as FFF9h in hexadecimal. We can also represent that in binary as:

11111111 11111001

When we declare short zz = 65529;, the compiler interprets 65529 as a signed value. In twos-complement notation, the top bit signifies whether a signed value is positive or negative. In this case, you can see the top bit is a 1, so it is treated as a negative number. That's why it prints out -7.

For an unsigned short, we don't care about sign since it's unsigned. So when we print it out using %d, we use all 16 bits, so it's interpreted as 65529.

android.app.Application cannot be cast to android.app.Activity

You are getting this error because the parameter required is Activity and you are passing it the Application. So, either you cast application to the Activity like: (Activity)getApplicationContext(); Or you can just type the Activity like: MyActivity.this

'innerText' works in IE, but not in Firefox

This has been my experience with innerText, textContent, innerHTML, and value:

// elem.innerText = changeVal;  // works on ie but not on ff or ch
// elem.setAttribute("innerText", changeVal); // works on ie but not ff or ch
// elem.textContent = changeVal;  // works on ie but not ff or ch
// elem.setAttribute("textContent", changeVal);  // does not work on ie ff or ch
// elem.innerHTML = changeVal;  // ie causes error - doesn't work in ff or ch
// elem.setAttribute("innerHTML", changeVal); //ie causes error doesn't work in ff or ch
   elem.value = changeVal; // works in ie and ff -- see note 2 on ch
// elem.setAttribute("value", changeVal); // ie works; see note 1 on ff and note 2 on ch

ie = internet explorer, ff = firefox, ch = google chrome. note 1: ff works until after value is deleted with backspace - see note by Ray Vega above. note 2: works somewhat in chrome - after update it is unchanged then you click away and click back into the field and the value appears. The best of the lot is elem.value = changeVal; which I did not comment out above.

CSS: 100% font size - 100% of what?

According to ALL THE SPECS DATING BACK TO 1996, percentage values on font-size refer to the parent element's (computed) font-size.

<style>
div {
  font-size: 16px;
}
span {
  font-size: 75%;
}
</style>
<div><span>this font size is 12px!</span></div>

It's that easy.

What if the div declares a relative font-size, like ems, or even worse, another percentage?? See “computed” above. Whatever absolute unit the relative unit converts to.

The only question that remains is what happens when you use a percentage value on the root element, which has no parent:

html {
  font-size: 62.5%; /* 62.5% of what? */
}

In that case, see the “duplicate” of this question. TLDR: percentages on the root element refer to the browser default font size, which might be different per user.

References:

How to configure CORS in a Spring Boot + Spring Security application?

Cross origin protection is a feature of the browser. Curl does not care for CORS, as you presumed. That explains why your curls are successful, while the browser requests are not.

If you send the browser request with the wrong credentials, spring will try to forward the client to a login page. This response (off the login page) does not contain the header 'Access-Control-Allow-Origin' and the browser reacts as you describe.

You must make spring to include the haeder for this login response, and may be for other response, like error pages etc.

This can be done like this :

    @Configuration
    @EnableWebMvc
    public class WebConfig extends WebMvcConfigurerAdapter {

            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/api/**")
                    .allowedOrigins("http://domain2.com")
                    .allowedMethods("PUT", "DELETE")
                    .allowedHeaders("header1", "header2", "header3")
                    .exposedHeaders("header1", "header2")
                    .allowCredentials(false).maxAge(3600);
            }
     }

This is copied from cors-support-in-spring-framework

I would start by adding cors mapping for all resources with :

registry.addMapping("/**")

and also allowing all methods headers.. Once it works you may start to reduce that again to the needed minimum.

Please note, that the CORS configuration changes with Release 4.2.

If this does not solve your issues, post the response you get from the failed ajax request.

IIS URL Rewrite and Web.config

Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)

In rule #2 for permanent redirect there is thing missing:

redirectType="Permanent"

So rule #2 should look like this:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Edit

For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference

In response to @kneidels question from the comments; To match the url: topic.php?id=39 something like the following could be used:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="SpecificRedirect" stopProcessing="true">
        <match url="^topic.php$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
        </conditions>
        <action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

This will match topic.php?id=ab where a is any number between 0-9 and b is also any number between 0-9. It will then redirect to /newpage/xy where xy comes from the original url. I have not tested this but it should work.

Twitter Bootstrap Button Text Word Wrap

You can add these style's and it works just as expected.

.btn {
    white-space:normal !important; 
    word-wrap: break-word; 
    word-break: normal;
}

How to extract duration time from ffmpeg output?

Argh. Forget that. It looks like I have to get the cobwebs out of my C and C++ programming and use that instead. I do not know all the shell tricks to get it to work. This is how far I got.

ffmpeg -i myfile 2>&1 | grep "" > textdump.txt

and then I would probably extract the duration with a C++ app instead by extracting tokens.

I am not posting the solution because I am not a nice person right now

Update - I have my approach to getting that duration time stamp

Step 1 - Get the media information on to a text file
`ffprobe -i myfile 2>&1 | grep "" > textdump.txt`
OR
`ffprobe -i myfile 2>&1 | awk '{ print }' > textdump.txt`

Step 2 - Home in on the information needed and extract it
cat textdump.txt | grep "Duration" | awk '{ print $2 }' | ./a.out
Notice the a.out. That is my C code to chop off the resulting comma because the output is something like 00:00:01.33,
Here is the C code that takes stdin and outputs the correct information needed. I had to take the greater and less than signs out for viewing.

#include stdio.h #include string.h void main() { //by Admiral Smith Nov 3. 2016 char time[80]; int len; char *correct; scanf("%s", &time); correct = (char *)malloc(strlen(time)); if (!correct) { printf("\nmemory error"); return; } memcpy(correct,&time,strlen(time)-1); correct[strlen(time)]='/0'; printf("%s", correct); free(correct); }

Now the output formats correctly like 00:00:01.33

The provider is not compatible with the version of Oracle client

Chris' solution worked for me as well. I did however get a follow error message that states:

Could not load file or assembly 'Oracle.DataAccess' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Apparently, in the foreign language of Oraclish, that means that your program are either targeting all platforms, or 32-bit machines. Simply change your target platform in Project Properties to 64-bit and hope for the best.

How to execute an .SQL script file using c#

There are two points to considerate.

1) This source code worked for me:

private static string Execute(string credentials, string scriptDir, string scriptFilename)
{ 
  Process process = new Process();
  process.StartInfo.UseShellExecute = false;
  process.StartInfo.WorkingDirectory = scriptDir;
  process.StartInfo.RedirectStandardOutput = true;
  process.StartInfo.FileName = "sqlplus";
  process.StartInfo.Arguments = string.Format("{0} @{1}", credentials, scriptFilename);
  process.StartInfo.CreateNoWindow = true;

  process.Start();
  string output = process.StandardOutput.ReadToEnd();
  process.WaitForExit();

  return output;
}

I set the working directory to the script directory, so that sub scripts within the script also work.

Call it e.g. as Execute("usr/pwd@service", "c:\myscripts", "script.sql")

2) You have to finalize your SQL script with the statement EXIT;

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I found the solution as Its problem with Android Studio 3.1 Canary 6

My backup of Android Studio 3.1 Canary 5 is useful to me and saved my half day.

Now My build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    buildToolsVersion '27.0.2'
    defaultConfig {
        applicationId "com.example.demo"
        minSdkVersion 15
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }
    dataBinding {
        enabled true
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    productFlavors {
    }
}

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:appcompat-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:design:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:support-v4:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:recyclerview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.android.support:cardview-v7:${rootProject.ext.supportLibVersion}"
    implementation "com.squareup.retrofit2:retrofit:2.3.0"
    implementation "com.google.code.gson:gson:2.8.2"
    implementation "com.android.support.constraint:constraint-layout:1.0.2"
    implementation "com.squareup.retrofit2:converter-gson:2.3.0"
    implementation "com.squareup.okhttp3:logging-interceptor:3.6.0"
    implementation "com.squareup.picasso:picasso:2.5.2"
    implementation "com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3"
    compile 'com.github.elevenetc:badgeview:v1.0.0'
    annotationProcessor 'com.github.elevenetc:badgeview:v1.0.0'
    testImplementation "junit:junit:4.12"
    androidTestImplementation("com.android.support.test.espresso:espresso-core:3.0.1", {
        exclude group: "com.android.support", module: "support-annotations"
    })
}

and My gradle is:

classpath 'com.android.tools.build:gradle:3.1.0-alpha06'

and its working finally.

I think there problem in Android Studio 3.1 Canary 6

Thank you all for your time.

How to run a shell script at startup

For some people, this will work:

You could simply add the following command into SystemPreferencesStartup Applications:

bash /full/path/to/your/script.sh

Parsing JSON object in PHP using json_decode

When you json decode , force it to return an array instead of object.

$data = json_decode($json, TRUE); -> // TRUE

This will return an array and you can access the values by giving the keys.

Compare two files line by line and generate the difference in another file

I'm surprised nobody mentioned diff -y to produce a side-by-side output, for example:

diff -y file1 file2 > file3

And in file3(different lines have a symbol | in middle):

same     same
diff_1 | diff_2

Xamarin 2.0 vs Appcelerator Titanium vs PhoneGap

I have worked with Xamarin. Here are the positives and negatives I have found:

Positives

  1. Easy to code, C# makes the job easier
  2. Performance won't be a concern
  3. Native UI
  4. Good IDE, much like Xcode and Visual Studio.
  5. Xamarin Debugger
  6. Xamarin SDK is free and open-source. Wiki

Negatives

  1. You need to know the API for each platform you want to target (iOS, Android, WP8). However, you do not need to know Objective-C or Java.
  2. Xamarin shares only a few things across platforms (things like databases and web services).
  3. You have to design the UI of each platform separately (this can be a blessing or a curse).

libpthread.so.0: error adding symbols: DSO missing from command line

I found I had the same error. I was compiling a code with both lapack and blas. When I switched the order that the two libraries were called the error went away.

"LAPACK_LIB = -llapack -lblas" worked where "LAPACK_LIB = -lblas -llapack" gave the error described above.

Update records using LINQ

This worked best.

(from p in Context.person_account_portfolio 
 where p.person_id == personId select p).ToList()
                                        .ForEach(x => x.is_default = false);

Context.SaveChanges();

Easy way to convert a unicode list to a list containing python strings?

[str(x) for x in EmployeeList] would do a conversion, but it would fail if the unicode string characters do not lie in the ascii range.

>>> EmployeeList = [u'1001', u'Karick', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
['1001', 'Karick', '14-12-2020', '1$']


>>> EmployeeList = [u'1001', u'????', u'14-12-2020', u'1$']
>>> [str(x) for x in EmployeeList]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range(128)

How to write inline if statement for print?

hmmm, you can do it with a list comprehension. This would only make sense if you had a real range.. but it does do the job:

print([a for i in range(0,1) if b])

or using just those two variables:

print([a for a in range(a,a+1) if b])

Entity Framework: table without primary key

Update to @CodeNotFound's answer.

In EF Core 3.0 DbQuery<T> has been deprecated, instead you should use Keyless entity types which supposedly does the same thing. These are configured with the ModelBuilder HasNoKey() method. In your DbContext class, do this

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder
        .Entity<YourEntityType>(eb =>
        {
            eb.HasNoKey();
        });

}

There are restrictions though, notably:

  • Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.
  • Only support a subset of navigation mapping capabilities, specifically:
    • They may never act as the principal end of a relationship.
    • They may not have navigations to owned entities
    • They can only contain reference navigation properties pointing to regular entities.
    • Entities cannot contain navigation properties to keyless entity types.

This means that for the question of

If I want to use them and modify data, must I necessarily add a PK to those tables, or is there a workaround so that I don't have to?

You cannot modify data this way - however you can read. One could envision using another way (e.g. ADO.NET, Dapper) to modify data though - this could be a solution in cases where you rarely need to do non-read operations and still would like to stick with EF Core for your majority cases.

Also, if you truly need/want to work with heap(keyless) tables - consider ditching EF and use another way to talk to your database.

onchange event for input type="number"

$("input[type='number']").bind("focus", function() {
    var value = $(this).val();
    $(this).bind("blur", function() {
        if(value != $(this).val()) {
            alert("Value changed");
        }
        $(this).unbind("blur");
    });
});

OR

$("input[type='number']").bind("input", function() {
    alert("Value changed");
});

Linq select object from list depending on objects attribute

First, Single throws an exception if there is more than one element satisfying the criteria. Second, your criteria should only check if the Correct property is true. Right now, you are checking if a is equal to a.Correct (which will not even compile).

You should use First (which will throw if there are no such elements), or FirstOrDefault (which will return null for a reference type if there isn't such element):

// this will return the first correct answer,
// or throw an exception if there are no correct answers
var correct = answers.First(a => a.Correct); 

// this will return the first correct answer, 
// or null if there are no correct answers
var correct = answers.FirstOrDefault(a => a.Correct); 

// this will return a list containing all answers which are correct,
// or an empty list if there are no correct answers
var allCorrect = answers.Where(a => a.Correct).ToList();

Can I convert a boolean to Yes/No in a ASP.NET GridView

Nope - but you could use a template column:

<script runat="server">
  TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {
     object o = DataBinder.Eval(Container.DataItem, field);
     if (converter == null) {
        return (TResult)o;
     }
     return converter((T)o);
  }
</script>

<asp:TemplateField>
  <ItemTemplate>
     <%# Eval<bool, string>("Active", b => b ? "Yes" : "No") %>
  </ItemTemplate>
</asp:TemplateField>

Swap two items in List<T>

Check the answer from Marc from C#: Good/best implementation of Swap method.

public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
}

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;
}

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

SessionTimeout: web.xml vs session.maxInactiveInterval()

Now, i'm being told that this will terminate the session (or is it all sessions?) in the 15th minute of use, regardless their activity.

No, that's not true. The session-timeout configures a per session timeout in case of inactivity.

Are these methods equivalent? Should I favour the web.xml config?

The setting in the web.xml is global, it applies to all sessions of a given context. Programatically, you can change this for a particular session.

Importing images from a directory (Python) to list or dictionary

from PIL import Image
import os, os.path

imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
    ext = os.path.splitext(f)[1]
    if ext.lower() not in valid_images:
        continue
    imgs.append(Image.open(os.path.join(path,f)))
   

How to use the curl command in PowerShell?

In Powershell 3.0 and above there is both a Invoke-WebRequest and Invoke-RestMethod. Curl is actually an alias of Invoke-WebRequest in PoSH. I think using native Powershell would be much more appropriate than curl, but it's up to you :).

Invoke-WebRequest MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849901.aspx?f=255&MSPPError=-2147217396

Invoke-RestMethod MSDN docs are here: https://technet.microsoft.com/en-us/library/hh849971.aspx?f=255&MSPPError=-2147217396

AngularJS + JQuery : How to get dynamic content working in angularjs

Addition to @jwize's answer

Because angular.element(document).injector() was giving error injector is not defined So, I have created function that you can run after AJAX call or when DOM is changed using jQuery.

  function compileAngularElement( elSelector) {

        var elSelector = (typeof elSelector == 'string') ? elSelector : null ;  
            // The new element to be added
        if (elSelector != null ) {
            var $div = $( elSelector );

                // The parent of the new element
                var $target = $("[ng-app]");

              angular.element($target).injector().invoke(['$compile', function ($compile) {
                        var $scope = angular.element($target).scope();
                        $compile($div)($scope);
                        // Finally, refresh the watch expressions in the new element
                        $scope.$apply();
                    }]);
            }

        }

use it by passing just new element's selector. like this

compileAngularElement( '.user' ) ; 

AndroidStudio gradle proxy

Rajesh's suggestion did not work for me. What I did was go to

File -> Settings ->HTTP Proxy(Under IDE Settings) ->Manual proxy configuration

I still left the proxy information in Project Settings under Gradle, like Rajesh suggested. But I'm not entirely sure if it's necessary.

I am using 0.8.6 Beta

Is there a way to get colored text in GitHubflavored Markdown?

You can not color plain text in a GitHub README.md file. You can however add color to code samples in your GitHub README.md file with the tags below.

To do this, just add tags, such as these samples, to your README.md file:

```json
   // Code for coloring
```
```html
   // Code for coloring
```
```js
   // Code for coloring
```
```css
   // Code for coloring
```
// etc.

**Colored Code Example, JavaScript:** place this code below, in your GitHub README.md file and see how it colors the code for you.
  import { Component } from '@angular/core';
  import { MovieService } from './services/movie.service';

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css'],
    providers: [ MovieService ]
  })
  export class AppComponent {
    title = 'app works!';
  }

No "pre" or "code" tags are needed.

This is now covered in the GitHub Markdown documentation (about half way down the page, there's an example using Ruby). GitHub uses Linguist to identify and highlight syntax - you can find a full list of supported languages (as well as their markdown keywords) over in the Linguist's YAML file.

DEMO

Right to Left support for Twitter Bootstrap 3

  1. I highly recommend bootstrap-rtl. It is built over Bootstrap core, and rtl support is added as it is a bootstrap theme. This would make your code more maintainable as you can always update your core bootstrap files. CDN

  2. Another option to use this stand-alone library, It also comes with few awesome Arabic fonts.

Using async/await with a forEach loop

Currently the Array.forEach prototype property doesn't support async operations, but we can create our own poly-fill to meet our needs.

// Example of asyncForEach Array poly-fill for NodeJs
// file: asyncForEach.js
// Define asynForEach function 
async function asyncForEach(iteratorFunction){
  let indexer = 0
  for(let data of this){
    await iteratorFunction(data, indexer)
    indexer++
  }
}
// Append it as an Array prototype property
Array.prototype.asyncForEach = asyncForEach
module.exports = {Array}

And that's it! You now have an async forEach method available on any arrays that are defined after these to operations.

Let's test it...

// Nodejs style
// file: someOtherFile.js

const readline = require('readline')
Array = require('./asyncForEach').Array
const log = console.log

// Create a stream interface
function createReader(options={prompt: '>'}){
  return readline.createInterface({
    input: process.stdin
    ,output: process.stdout
    ,prompt: options.prompt !== undefined ? options.prompt : '>'
  })
}
// Create a cli stream reader
async function getUserIn(question, options={prompt:'>'}){
  log(question)
  let reader = createReader(options)
  return new Promise((res)=>{
    reader.on('line', (answer)=>{
      process.stdout.cursorTo(0, 0)
      process.stdout.clearScreenDown()
      reader.close()
      res(answer)
    })
  })
}

let questions = [
  `What's your name`
  ,`What's your favorite programming language`
  ,`What's your favorite async function`
]
let responses = {}

async function getResponses(){
// Notice we have to prepend await before calling the async Array function
// in order for it to function as expected
  await questions.asyncForEach(async function(question, index){
    let answer = await getUserIn(question)
    responses[question] = answer
  })
}

async function main(){
  await getResponses()
  log(responses)
}
main()
// Should prompt user for an answer to each question and then 
// log each question and answer as an object to the terminal

We could do the same for some of the other array functions like map...

async function asyncMap(iteratorFunction){
  let newMap = []
  let indexer = 0
  for(let data of this){
    newMap[indexer] = await iteratorFunction(data, indexer, this)
    indexer++
  }
  return newMap
}

Array.prototype.asyncMap = asyncMap

... and so on :)

Some things to note:

  • Your iteratorFunction must be an async function or promise
  • Any arrays created before Array.prototype.<yourAsyncFunc> = <yourAsyncFunc> will not have this feature available

How do I get values from a SQL database into textboxes using C#?

If you want to display single value access from database into textbox, please refer to the code below:

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
TextBox1.Text=cmd.ExecuteScalar();
Con.Close();

or

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
SqlDataReader dr=new SqlDataReadr();
dr=cmd.Executereader();
if(dr.read())
{
    TextBox1.Text=dr.GetValue(0).Tostring();
}
Con.Close();

WPF - add static items to a combo box

Like this:

<ComboBox Text="MyCombo">
<ComboBoxItem  Name="cbi1">Item1</ComboBoxItem>
<ComboBoxItem  Name="cbi2">Item2</ComboBoxItem>
<ComboBoxItem  Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

Single Form Hide on Startup

Try to hide the app from the task bar as well.

To do that please use this code.

  protected override void OnLoad(EventArgs e)
  {
   Visible = false; // Hide form window.
   ShowInTaskbar = false; // Remove from taskbar.
   Opacity = 0;

   base.OnLoad(e);
   }

Thanks. Ruhul

Automatically resize jQuery UI dialog to the width of the content loaded by ajax

You can avoid the 100% width issue by specifying a maximum width. The maxWidth option does not seem to work; so set the CSS max-width property on the dialog widget instead.

In case you also want to constrain the maximum height, use the maxHeight option. It will correctly show a scrollbar when necessary.

_x000D_
_x000D_
$(function() {_x000D_
  var $dialog = $("#dialog");_x000D_
  $dialog.dialog({_x000D_
    autoOpen: false,_x000D_
    modal: true,_x000D_
    width: "auto"_x000D_
  });_x000D_
  /*_x000D_
   * max-width should be set on dialog widget because maxWidth option has known issues_x000D_
   * max-height should be set using maxHeight option_x000D_
   */_x000D_
  $dialog.dialog("widget").css("max-width", $(window).width() - 100);_x000D_
  $dialog.dialog("option", "maxHeight", $(window).height() - 100);_x000D_
  $(".test-link").on("click", function(e) {_x000D_
    e.preventDefault();_x000D_
    $dialog.html($(this.hash).html());_x000D_
    // if you change the content of dialog after it is created then reset the left_x000D_
    // coordinate otherwise content only grows up to the right edge of screen_x000D_
    $dialog.dialog("widget").css({ left: 0 });_x000D_
    $dialog.dialog("open");_x000D_
  });_x000D_
});
_x000D_
@import url("https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.min.css");
_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>_x000D_
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>_x000D_
_x000D_
<div id="dialog"></div>_x000D_
_x000D_
<!-- test links -->_x000D_
_x000D_
<p>_x000D_
  <a href="#content-1" class="test-link">Image (Landscape)</a>_x000D_
  <a href="#content-2" class="test-link">Image (Portrait)</a>_x000D_
  <a href="#content-3" class="test-link">Text Content (Small)</a>_x000D_
  <a href="#content-4" class="test-link">Text Content (Large)</a>_x000D_
</p>_x000D_
<p>If you are viewing in Stack Snippets > Full page then reload the snippet so that window height is recalculated (Right click > Reload frame).</p>_x000D_
_x000D_
<!-- sample content -->_x000D_
_x000D_
<div id="content-1" style="display: none;">_x000D_
  <img src="https://i.stack.imgur.com/5leq2.jpg" width="450" height="300">_x000D_
</div>_x000D_
_x000D_
<div id="content-2" style="display: none;">_x000D_
  <img src="https://i.stack.imgur.com/9pVkn.jpg" width="300" height="400">_x000D_
</div>_x000D_
_x000D_
<div id="content-3" style="display: none;">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sodales eu urna sit amet fermentum. Morbi ornare, leo ut ornare volutpat, nibh diam mattis elit, eget porta sapien quam eu mi. Nullam sollicitudin, nibh non suscipit commodo, nisi metus bibendum urna, vitae congue nisl risus eu tellus. Praesent diam ligula, hendrerit eget bibendum quis, convallis eu erat. Aliquam scelerisque turpis augue, sit amet dictum urna hendrerit id. Vestibulum luctus dolor quis ex sodales, nec aliquet lacus elementum. Mauris sollicitudin dictum augue eget posuere. Suspendisse diam elit, scelerisque eu quam vel, tempus sodales metus. Morbi et vehicula elit. In sit amet bibendum mi.</p>_x000D_
</div>_x000D_
_x000D_
<div id="content-4" style="display: none;">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam sodales eu urna sit amet fermentum. Morbi ornare, leo ut ornare volutpat, nibh diam mattis elit, eget porta sapien quam eu mi. Nullam sollicitudin, nibh non suscipit commodo, nisi metus bibendum urna, vitae congue nisl risus eu tellus. Praesent diam ligula, hendrerit eget bibendum quis, convallis eu erat. Aliquam scelerisque turpis augue, sit amet dictum urna hendrerit id. Vestibulum luctus dolor quis ex sodales, nec aliquet lacus elementum. Mauris sollicitudin dictum augue eget posuere. Suspendisse diam elit, scelerisque eu quam vel, tempus sodales metus. Morbi et vehicula elit. In sit amet bibendum mi.</p>_x000D_
  <p>Aenean eu magna tempor, pellentesque arcu eget, mattis enim. Cras at volutpat mi. Aenean id placerat felis, quis imperdiet nunc. Aenean a iaculis est, quis lacinia nisl. Sed aliquet sem eget justo convallis congue. Quisque rhoncus nulla sit amet cursus maximus. Phasellus nec auctor urna. Nam mattis felis et diam finibus consectetur. Etiam finibus dignissim vestibulum. In eu urna mattis dui pharetra iaculis. Nam eleifend odio et massa imperdiet, et hendrerit mauris tempor. Quisque sapien lorem, dapibus ut ultricies ut, hendrerit in nulla. Nunc lobortis mi libero, nec tincidunt lacus pretium at. Aliquam erat volutpat.</p>_x000D_
  <p>Fusce eleifend enim nec massa porttitor tempor a eget neque. Quisque vel augue ac urna posuere iaculis. Morbi pharetra augue ac interdum pulvinar. Duis vel posuere risus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut vitae lectus non nisl iaculis volutpat nec vitae ante. Maecenas quis condimentum elit. Sed nisl urna, convallis ut pellentesque sit amet, pellentesque eget quam. Pellentesque ornare sapien ac scelerisque pretium. Pellentesque metus tortor, accumsan in vehicula iaculis, efficitur eget nisi. Donec tincidunt, felis vel viverra convallis, lectus lectus elementum magna, faucibus viverra risus nulla in dolor.</p>_x000D_
  <p>Duis tristique sapien ut commodo laoreet. In vel sapien dui. Vestibulum non bibendum erat. Etiam iaculis vehicula accumsan. Phasellus finibus, elit et molestie luctus, massa arcu tempor nulla, id hendrerit metus mauris non mi. Morbi a ultricies magna. Proin condimentum suscipit urna eu maximus. Mauris condimentum massa ac egestas fermentum. Praesent faucibus a neque a molestie. Integer sed diam at eros accumsan convallis.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to escape single quotes within single quoted strings

Since one cannot put single quotes within single quoted strings, the simplest and most readable option is to use a HEREDOC string

command=$(cat <<'COMMAND'
urxvt -fg '#111111' -bg '#111111'
COMMAND
)

alias rxvt=$command

In the code above, the HEREDOC is sent to the cat command and the output of that is assigned to a variable via the command substitution notation $(..)

Putting a single quote around the HEREDOC is needed since it is within a $()

Browser detection

I would not advise hacking browser-specific things manually with JS. Either use a javascript library like "prototype" or "jquery", which will handle all the specific issues transparently.

Or use these libs to determine the browser type if you really must.

Also see Browser & version in prototype library?

How do I get the classes of all columns in a data frame?

One option is to use lapply and class. For example:

> foo <- data.frame(c("a", "b"), c(1, 2))
> names(foo) <- c("SomeFactor", "SomeNumeric")
> lapply(foo, class)
$SomeFactor
[1] "factor"

$SomeNumeric
[1] "numeric"

Another option is str:

> str(foo)
'data.frame':   2 obs. of  2 variables:
 $ SomeFactor : Factor w/ 2 levels "a","b": 1 2
 $ SomeNumeric: num  1 2

How to have the cp command create any necessary folders for copying a file to a destination

rsync is work!

#file:
rsync -aqz _vimrc ~/.vimrc

#directory:
rsync -aqz _vim/ ~/.vim

How do I convert Int/Decimal to float in C#?

It is just:

float f = (float)6;

What's the difference between Invoke() and BeginInvoke()

The difference between Control.Invoke() and Control.BeginInvoke() is,

  • BeginInvoke() will schedule the asynchronous action on the GUI thread. When the asynchronous action is scheduled, your code continues. Some time later (you don't know exactly when) your asynchronous action will be executed
  • Invoke() will execute your asynchronous action (on the GUI thread) and wait until your action has completed.

A logical conclusion is that a delegate you pass to Invoke() can have out-parameters or a return-value, while a delegate you pass to BeginInvoke() cannot (you have to use EndInvoke to retrieve the results).

How to detect control+click in Javascript from an onclick div attribute?

Because it's been a several years since this question was first asked, the other answers are outdated or incomplete.

Here's the code for a modern implementation using jQuery:

$( 'div#1' ).on( 'click', function( event ) {
    if ( event.ctrlKey ) {
        //is ctrl + click
    } else {
        //normal click
    }
} );

As for detecting right-clicks, this was correctly provided by another user but I'll list it here just to have everything in one place.

$( 'div#1' ).on( 'contextmenu', function( event ) {
    // right-click handler
} ) ;

Change width of select tag in Twitter Bootstrap

This works for me to reduce select tag's width;

<select id ="Select1" class="input-small">

You can use any one of these classes;

class="input-small"

class="input-medium"

class="input-large"

class="input-xlarge"

class="input-xxlarge"

Does overflow:hidden applied to <body> work on iPhone Safari?

It does apply, but it only applies to certain elements within the DOM. for example, it won't work on a table, td, or some other elements, but it will work on a <DIV> tag.
eg:

<body>
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>

Only tested in iOS 4.3.

A minor edit: you may be better off using overflow:scroll so two finger-scrolling does work.

How to print color in console using System.out.println?

If your terminal supports it, you can use ANSI escape codes to use color in your output. It generally works for Unix shell prompts; however, it doesn't work for Windows Command Prompt (Although, it does work for Cygwin). For example, you could define constants like these for the colors:

public static final String ANSI_RESET = "\u001B[0m";
public static final String ANSI_BLACK = "\u001B[30m";
public static final String ANSI_RED = "\u001B[31m";
public static final String ANSI_GREEN = "\u001B[32m";
public static final String ANSI_YELLOW = "\u001B[33m";
public static final String ANSI_BLUE = "\u001B[34m";
public static final String ANSI_PURPLE = "\u001B[35m";
public static final String ANSI_CYAN = "\u001B[36m";
public static final String ANSI_WHITE = "\u001B[37m";

Then, you could reference those as necessary.

For example, using the above constants, you could make the following red text output on supported terminals:

System.out.println(ANSI_RED + "This text is red!" + ANSI_RESET);

Update: You might want to check out the Jansi library. It provides an API and has support for Windows using JNI. I haven't tried it yet; however, it looks promising.

Update 2: Also, if you wish to change the background color of the text to a different color, you could try the following as well:

public static final String ANSI_BLACK_BACKGROUND = "\u001B[40m";
public static final String ANSI_RED_BACKGROUND = "\u001B[41m";
public static final String ANSI_GREEN_BACKGROUND = "\u001B[42m";
public static final String ANSI_YELLOW_BACKGROUND = "\u001B[43m";
public static final String ANSI_BLUE_BACKGROUND = "\u001B[44m";
public static final String ANSI_PURPLE_BACKGROUND = "\u001B[45m";
public static final String ANSI_CYAN_BACKGROUND = "\u001B[46m";
public static final String ANSI_WHITE_BACKGROUND = "\u001B[47m";

For instance:

System.out.println(ANSI_GREEN_BACKGROUND + "This text has a green background but default text!" + ANSI_RESET);
System.out.println(ANSI_RED + "This text has red text but a default background!" + ANSI_RESET);
System.out.println(ANSI_GREEN_BACKGROUND + ANSI_RED + "This text has a green background and red text!" + ANSI_RESET);

Raw_Input() Is Not Defined

For Python 3.x, use input(). For Python 2.x, use raw_input(). Don't forget you can add a prompt string in your input() call to create one less print statement. input("GUESS THAT NUMBER!").

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

sql how to cast a select query

Yes you can do.

Syntax for CAST:

CAST ( expression AS data_type [ ( length ) ] )

For example:

CAST(MyColumn AS Varchar(10))

CAST in SELECT Statement:

Select CAST(MyColumn AS Varchar(10)) AS MyColumn
FROM MyTable

See for more information CAST and CONVERT (Transact-SQL)

Cannot read property 'length' of null (javascript)

if (capital.touched && capital != undefined && capital.length < 1 ) { 
//capital does exists
}

Min and max value of input in angular4 application

Most simple approach in Template driven forms for min/max validation with out using reactive forms and building any directive, would be to use pattern attribute of html. This has already been explained and answered here please look https://stackoverflow.com/a/63312336/14069524

How to downgrade php from 5.5 to 5.3

It is possible! Yes

In many cases, you might want to use XAMPP with a different PHP version than the one that comes preinstalled. You might do this to get the benefits of a newer version of PHP, or to reproduce bugs using an earlier version of PHP.

To use a different version of PHP with XAMPP, follow these steps:

  1. Download a binary build of the PHP version that you wish to use from the PHP website, and extract the contents of the compressed archive file to your XAMPP installation directory (usually, C:\xampp). Ensure that you give it a different directory name to avoid overwriting the existing PHP version. For example, in this tutorial, we’ll call the new directory C:\xampp\php5-6-0. NOTE : Ensure that the PHP build you download matches the Apache build (VC9 or VC11) in your XAMPP platform.

  2. Within the new directory, rename the php.ini-development file to php.ini. If you prefer to use production settings, you could instead rename the php.ini-production file to php.ini.

  3. Edit the httpd-xampp.conf file in the apache\conf\extra\ subdirectory of your XAMPP installation directory. Within this file, search for all instances of the old PHP directory path and replace them with the path to the new PHP directory created in Step 1. In particular, be sure to change the lines

    LoadFile "/xampp/php/php5ts.dll"
    LoadFile "/xampp/php/libpq.dll"
    LoadModule php5_module "/xampp/php/php5apache2_4.dll"

to

    LoadFile "/xampp/php5-6-0/php5ts.dll"
    LoadFile "/xampp/php5-6-0/libpq.dll"
    LoadModule php5_module "/xampp/php5-6-0/php5apache2_4.dll"

NOTE : Remember to adjust the file and directory paths above to reflect valid paths on your system.

  1. Restart your Apache server through the XAMPP control panel for your changes to take effect. The new version of PHP should now be active. To verify this, browse to the URL http://localhost/xampp/phpinfo.php, which displays the output of the phpinfo() command, and check the version number at the top of the page.

How to add a scrollbar to an HTML5 table?

<!DOCTYPE html>
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Scrollable Table</title>
    <style type="text/css">
      * { padding: 0; margin: 0; }
      table.my_table { 
        font-family: verdana, arial, helvetica, sans-serif;
        font-size: 11px;
        cellspacing: 0; 
        border-collapse: collapse; 
        width: 283px;    
        }
      table.my_table th, table.my_table td { 
        border-bottom: 1px solid #999; 
        border-right: 1px solid #999; 
        }
      table.my_table th { background: #ffb; }
      table.my_table td { background: #ffe; }

      div.scrollableContainer { 
        height: 100px; 
        overflow: auto;  
        width: 300px; 
        margin: 40px;    
        border: 1px solid #999;
        background: #ffb;     
        }

    </style>
    </head>
    <body>
    <div class="scrollableContainer">
        <table class="my_table scrollable">
          <thead>
            <tr>
              <th>URL</th>
                </tr>
        </thead>

        <tbody>
                <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td> 
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td>                   
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td> 
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td>                   
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td> 
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td>                   
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td> 
                    </tr>

                    <tr>
              <td>http://www.youtube.com/embed/evuSpI2Genw</td>                   
                    </tr>
            </tbody>
          </table>
        </div>
      </body>
    </html>

Right HTTP status code to wrong input

Codes starting with 4 (4xx) are meant for client errors. Maybe 400 (Bad Request) could be suitable to this case? Definition in http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html says:

"The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. "

jQuery DataTables: control table width

This works fine.

#report_container {
   float: right;
   position: relative;
   width: 100%;
}

Android: Create a toggle button with image and no text

ToggleButton inherits from TextView so you can set drawables to be displayed at the 4 borders of the text. You can use that to display the icon you want on top of the text and hide the actual text

<ToggleButton
    android:id="@+id/toggleButton1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:drawableTop="@android:drawable/ic_menu_info_details"
    android:gravity="center"
    android:textOff=""
    android:textOn=""
    android:textSize="0dp" />

The result compared to regular ToggleButton looks like

enter image description here

The seconds option is to use an ImageSpan to actually replace the text with an image. Looks slightly better since the icon is at the correct position but can't be done with layout xml directly.

You create a plain ToggleButton

<ToggleButton
    android:id="@+id/toggleButton3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="false" />

Then set the "text" programmatially

ToggleButton button = (ToggleButton) findViewById(R.id.toggleButton3);
ImageSpan imageSpan = new ImageSpan(this, android.R.drawable.ic_menu_info_details);
SpannableString content = new SpannableString("X");
content.setSpan(imageSpan, 0, 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
button.setText(content);
button.setTextOn(content);
button.setTextOff(content);

The result here in the middle - icon is placed slightly lower since it takes the place of the text.

enter image description here

Difference between <input type='button' /> and <input type='submit' />

type='Submit' is set to forward & get the values on BACK-END (PHP, .NET etc). type='button' will reflect normal button behavior.

SQLSTATE[HY000] [2002] php_network_getaddresses: getaddrinfo failed: Name or service not known

In my case, everything was set up correctly, but my Docker infrastructure needed more RAM. I'm using Docker for Mac, where default RAM was around 1 GB, and as MySQL uses around 1.5Gb of RAM ( and probably was crashing ??? ), changing the Docker RAM utilization level to 3-4 Gb solved the issue.

Error: Jump to case label

JohannesD's answer is correct, but I feel it isn't entirely clear on an aspect of the problem.

The example he gives declares and initializes the variable i in case 1, and then tries to use it in case 2. His argument is that if the switch went straight to case 2, i would be used without being initialized, and this is why there's a compilation error. At this point, one could think that there would be no problem if variables declared in a case were never used in other cases. For example:

switch(choice) {
    case 1:
        int i = 10; // i is never used outside of this case
        printf("i = %d\n", i);
        break;
    case 2:
        int j = 20; // j is never used outside of this case
        printf("j = %d\n", j);
        break;
}

One could expect this program to compile, since both i and j are used only inside the cases that declare them. Unfortunately, in C++ it doesn't compile: as Ciro Santilli ???? ???? ??? explained, we simply can't jump to case 2:, because this would skip the declaration with initialization of i, and even though case 2 doesn't use i at all, this is still forbidden in C++.

Interestingly, with some adjustments (an #ifdef to #include the appropriate header, and a semicolon after the labels, because labels can only be followed by statements, and declarations do not count as statements in C), this program does compile as C:

// Disable warning issued by MSVC about scanf being deprecated
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif

#ifdef __cplusplus
#include <cstdio>
#else
#include <stdio.h>
#endif

int main() {

    int choice;
    printf("Please enter 1 or 2: ");
    scanf("%d", &choice);

    switch(choice) {
        case 1:
            ;
            int i = 10; // i is never used outside of this case
            printf("i = %d\n", i);
            break;
        case 2:
            ;
            int j = 20; // j is never used outside of this case
            printf("j = %d\n", j);
            break;
    }
}

Thanks to an online compiler like http://rextester.com you can quickly try to compile it either as C or C++, using MSVC, GCC or Clang. As C it always works (just remember to set STDIN!), as C++ no compiler accepts it.

Update row values where certain condition is met in pandas

I think you can use loc if you need update two columns to same value:

df1.loc[df1['stream'] == 2, ['feat','another_feat']] = 'aaaa'
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2        aaaa         aaaa
c       2        aaaa         aaaa
d       3  some_value   some_value

If you need update separate, one option is use:

df1.loc[df1['stream'] == 2, 'feat'] = 10
print df1
   stream        feat another_feat
a       1  some_value   some_value
b       2          10   some_value
c       2          10   some_value
d       3  some_value   some_value

Another common option is use numpy.where:

df1['feat'] = np.where(df1['stream'] == 2, 10,20)
print df1
   stream  feat another_feat
a       1    20   some_value
b       2    10   some_value
c       2    10   some_value
d       3    20   some_value

EDIT: If you need divide all columns without stream where condition is True, use:

print df1
   stream  feat  another_feat
a       1     4             5
b       2     4             5
c       2     2             9
d       3     1             7

#filter columns all without stream
cols = [col for col in df1.columns if col != 'stream']
print cols
['feat', 'another_feat']

df1.loc[df1['stream'] == 2, cols ] = df1 / 2
print df1
   stream  feat  another_feat
a       1   4.0           5.0
b       2   2.0           2.5
c       2   1.0           4.5
d       3   1.0           7.0

If working with multiple conditions is possible use multiple numpy.where or numpy.select:

df0 = pd.DataFrame({'Col':[5,0,-6]})

df0['New Col1'] = np.where((df0['Col'] > 0), 'Increasing', 
                          np.where((df0['Col'] < 0), 'Decreasing', 'No Change'))

df0['New Col2'] = np.select([df0['Col'] > 0, df0['Col'] < 0],
                            ['Increasing',  'Decreasing'], 
                            default='No Change')

print (df0)
   Col    New Col1    New Col2
0    5  Increasing  Increasing
1    0   No Change   No Change
2   -6  Decreasing  Decreasing

How to fix corrupt HDFS FIles

If you just want to get your HDFS back to normal state and don't worry much about the data, then

This will list the corrupt HDFS blocks:

hdfs fsck -list-corruptfileblocks

This will delete the corrupted HDFS blocks:

hdfs fsck / -delete

Note that, you might have to use sudo -u hdfs if you are not the sudo user (assuming "hdfs" is name of the sudo user)

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

A full list of all the new/popular databases and their uses?

To file under both 'established' and 'key-value store': Berkeley DB.

Has transactions and replication. Usually linked as a lib (no standalone server, although you may write one). Values and keys are just binary strings, you can provide a custom sorting function for them (where applicable).

Does not prevent from shooting yourself in the foot. Switch off locking/transaction support, access the db from two threads at once, end up with a corrupt file.

How can I control the width of a label tag?

Giving width to Label is not a proper way. you should take one div or table structure to manage this. but still if you don't want to change your whole code then you can use following code.

label {
  width:200px;
  float: left;
}

How to implement endless list with RecyclerView?

Thanks to @Kushal and this is how I implemented it

private boolean loading = true;
int pastVisiblesItems, visibleItemCount, totalItemCount;

mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        if (dy > 0) { //check for scroll down
            visibleItemCount = mLayoutManager.getChildCount();
            totalItemCount = mLayoutManager.getItemCount();
            pastVisiblesItems = mLayoutManager.findFirstVisibleItemPosition();

            if (loading) {
                if ((visibleItemCount + pastVisiblesItems) >= totalItemCount) {
                    loading = false;
                    Log.v("...", "Last Item Wow !");
                    // Do pagination.. i.e. fetch new data

                    loading = true;
                }
            }
        }
    }
});

Don't forget to add

LinearLayoutManager mLayoutManager;
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

What are my options for storing data when using React Native? (iOS and Android)

We dont need redux-persist we can simply use redux for persistance.

react-redux + AsyncStorage = redux-persist

so inside createsotre file simply add these lines

store.subscribe(async()=> await AsyncStorage.setItem("store", JSON.stringify(store.getState())))

this will update the AsyncStorage whenever there are some changes in the redux store.

Then load the json converted store. when ever the app loads. and set the store again.

Because redux-persist creates issues when using wix react-native-navigation. If that's the case then I prefer to use simple redux with above subscriber function

How can I set a custom date time format in Oracle SQL Developer?

In my case the format set in Preferences/Database/NLS was [Date Format] = RRRR-MM-DD HH24:MI:SSXFF but in grid there were seen 8probably default format RRRR/MM/DD (even without time) The format has changed after changing the setting [Date Format] to: RRRR-MM-DD HH24:MI:SS (without 'XFF' at the end).

There were no errors, but format with xff at the end didn't work.

Note: in polish notation RRRR means YYYY

How to get just the parent directory name of a specific file

In Groovy:

There is no need to create a File instance to parse the string in groovy. It can be done as follows:

String path = "C:/aaa/bbb/ccc/ddd/test.java"
path.split('/')[-2]  // this will return ddd

The split will create the array [C:, aaa, bbb, ccc, ddd, test.java] and index -2 will point to entry before the last one, which in this case is ddd

ExecutorService that interrupts tasks after a timeout

You can use a ScheduledExecutorService for this. First you would submit it only once to begin immediately and retain the future that is created. After that you can submit a new task that would cancel the retained future after some period of time.

 ScheduledExecutorService executor = Executors.newScheduledThreadPool(2); 
 final Future handler = executor.submit(new Callable(){ ... });
 executor.schedule(new Runnable(){
     public void run(){
         handler.cancel();
     }      
 }, 10000, TimeUnit.MILLISECONDS);

This will execute your handler (main functionality to be interrupted) for 10 seconds, then will cancel (i.e. interrupt) that specific task.

Dismissing a Presented View Controller

Swift 3.0 //Dismiss View Controller in swift

self.navigationController?.popViewController(animated: true)
dismiss(animated: true, completion: nil)

Angular Material: mat-select not selecting default

Binding or setting of default value works only if the value attribute on MatSelect is comparable to value attribute binded to MatOption. If you bind caption of your item to value attribute of mat-option element you must set the default element on mat-select to caption of your item too. If you bind Id of your item to mat-option, you must bind id to mat-select too, not a whole item, caption or any other, only the same field.

But you need to do it with binding []

When 1 px border is added to div, Div size increases, Don't want to do that

Sometimes you don't want height or width to be affected without explicitly setting either. In that case, I find it helpful to use pseudo elements.

.border-me {
    position: relative;
}

.border-me::after {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    border: solid 1px black;
}

You can also do a lot more with the pseudo element so this is a pretty powerful pattern.

Calling Java from Python

Here is my summary of this problem: 5 Ways of Calling Java from Python

http://baojie.org/blog/2014/06/16/call-java-from-python/ (cached)

Short answer: Jpype works pretty well and is proven in many projects (such as python-boilerpipe), but Pyjnius is faster and simpler than JPype

I have tried Pyjnius/Jnius, JCC, javabridge, Jpype and Py4j.

Py4j is a bit hard to use, as you need to start a gateway, adding another layer of fragility.

Equals(=) vs. LIKE

The LIKE keyword undoubtedly comes with a "performance price-tag" attached. That said, if you have an input field that could potentially include wild card characters to be used in your query, I would recommend using LIKE only if the input contains one of the wild cards. Otherwise, use the standard equal to comparison.

Best regards...

HQL ERROR: Path expected for join

You need to name the entity that holds the association to User. For example,

... INNER JOIN ug.user u ...

That's the "path" the error message is complaining about -- path from UserGroup to User entity.

Hibernate relies on declarative JOINs, for which the join condition is declared in the mapping metadata. This is why it is impossible to construct the native SQL query without having the path.

mkdir -p functionality in Python

For Python = 3.5, use pathlib.Path.mkdir:

import pathlib
pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)

The exist_ok parameter was added in Python 3.5.

For Python = 3.2, os.makedirs has an optional third argument exist_ok that, when True, enables the mkdir -p functionality—unless mode is provided and the existing directory has different permissions than the intended ones; in that case, OSError is raised as previously:

import os
os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)

For even older versions of Python you can use os.makedirs and ignore the error:

import errno    
import os

def mkdir_p(path):
    try:
        os.makedirs(path)
    except OSError as exc:  # Python = 2.5
        if exc.errno == errno.EEXIST and os.path.isdir(path):
            pass
        else:
            raise

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

Gooye if it's possible to use Joda Time in your project then this code works for me:

String dateStr = "2012-10-01T09:45:00.000+02:00";
String customFormat = "yyyy-MM-dd HH:mm:ss";

DateTimeFormatter dtf = ISODateTimeFormat.dateTime();
LocalDateTime parsedDate = dtf.parseLocalDateTime(dateStr);

String dateWithCustomFormat = parsedDate.toString(DateTimeFormat.forPattern(customFormat));
System.out.println(dateWithCustomFormat);

Is there an equivalent of lsusb for OS X

If you are a user of MacPorts, you may simply install usbutils

sudo port install usbutils

If you are not, this might be a good opportunity to install it, it has ports for several other useful linux tools.

Using find to locate files that match one of multiple patterns

This will find all .c or .cpp files on linux

$ find . -name "*.c" -o -name "*.cpp"

You don't need the escaped parenthesis unless you are doing some additional mods. Here from the man page they are saying if the pattern matches, print it. Perhaps they are trying to control printing. In this case the -print acts as a conditional and becomes an "AND'd" conditional. It will prevent any .c files from being printed.

$ find .  -name "*.c" -o -name "*.cpp"  -print

But if you do like the original answer you can control the printing. This will find all .c files as well.

$ find . \( -name "*.c" -o -name "*.cpp" \) -print

One last example for all c/c++ source files

$ find . \( -name "*.c" -o -name "*.cpp"  -o -name "*.h" -o -name "*.hpp" \) -print

format statement in a string resource file

For me it worked like that in Kotlin:

my string.xml

 <string name="price" formatted="false">Price:U$ %.2f%n</string>

my class.kt

 var formatPrice: CharSequence? = null
 var unitPrice = 9990
 formatPrice = String.format(context.getString(R.string.price), unitPrice/100.0)
 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 99,90

For an even better result, we can do so

 <string name="price_to_string">Price:U$ %1$s</string>

 var formatPrice: CharSequence? = null
 var unitPrice = 199990
 val numberFormat = (unitPrice/100.0).toString()
 formatPrice = String.format(context.getString(R.string.price_to_string), formatValue(numberFormat))

  fun formatValue(value: String) :String{
    val mDecimalFormat = DecimalFormat("###,###,##0.00")
    val s1 = value.toDouble()
    return mDecimalFormat.format(s1)
 }

 Log.d("Double_CharSequence", "$formatPrice")

D/Double_CharSequence: Price :U$ 1.999,90

How to use jQuery in chrome extension?

Apart from the solutions already mentioned, you can also download jquery.min.js locally and then use it -

For downloading -

wget "https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"

manifest.json -

"content_scripts": [
   {
    "js": ["/path/to/jquery.min.js", ...]
   }
],

in html -

<script src="/path/to/jquery.min.js"></script>

Reference - https://developer.chrome.com/extensions/contentSecurityPolicy

Double Iteration in List Comprehension

Gee, I guess I found the anwser: I was not taking care enough about which loop is inner and which is outer. The list comprehension should be like:

[x for b in a for x in b]

to get the desired result, and yes, one current value can be the iterator for the next loop.

Maximum number of records in a MySQL database table

According to Scalability and Limits section in http://dev.mysql.com/doc/refman/5.6/en/features.html, MySQL support for large databases. They use MySQL Server with databases that contain 50 million records. Some users use MySQL Server with 200,000 tables and about 5,000,000,000 rows.

How I can filter a Datatable?

It is better to use DataView for this task.

Example of the using it you can find in this post: How to filter data in dataview

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This one disables all bogus verbs and only allows GET and POST

<system.webServer>
  <security>
    <requestFiltering>
      <verbs allowUnlisted="false">
    <clear/>
    <add verb="GET" allowed="true"/>
    <add verb="POST" allowed="true"/>
      </verbs>
    </requestFiltering>
  </security>
</system.webServer>

How to get the current location latitude and longitude in android

Use Location Listener Method

@Override
public void onLocationChanged(Location loc) {
Double lat = loc.getLatitude();
Double lng = loc.getLongitude();
}

Show MySQL host via SQL Command

Maybe

mysql> show processlist;

hasNext in Python iterators?

In addition to all the mentions of StopIteration, the Python "for" loop simply does what you want:

>>> it = iter("hello")
>>> for i in it:
...     print i
...
h
e
l
l
o

How do I generate random number for each row in a TSQL Select?

When called multiple times in a single batch, rand() returns the same number.

I'd suggest using convert(varbinary,newid()) as the seed argument:

SELECT table_name, 1.0 + floor(14 * RAND(convert(varbinary, newid()))) magic_number 
FROM information_schema.tables

newid() is guaranteed to return a different value each time it's called, even within the same batch, so using it as a seed will prompt rand() to give a different value each time.

Edited to get a random whole number from 1 to 14.

How to read and write to a text file in C++?

Look at this tutorial or this one, they are both pretty simple. If you are interested in an alternative this is how you do file I/O in C.

Some things to keep in mind, use single quotes ' when dealing with single characters, and double " for strings. Also it is a bad habit to use global variables when not necessary.

Have fun!

Rails Root directory path?

For super correctness, you should use:

Rails.root.join('foo','bar')

which will allow your app to work on platforms where / is not the directory separator, should anyone try and run it on one.

pandas groupby sort descending order

This kind of operation is covered under hierarchical indexing. Check out the examples here

When you groupby, you're making new indices. If you also pass a list through .agg(). you'll get multiple columns. I was trying to figure this out and found this thread via google.

It turns out if you pass a tuple corresponding to the exact column you want sorted on.

Try this:

# generate toy data 
ex = pd.DataFrame(np.random.randint(1,10,size=(100,3)), columns=['features', 'AUC', 'recall'])

# pass a tuple corresponding to which specific col you want sorted. In this case, 'mean' or 'AUC' alone are not unique. 
ex.groupby('features').agg(['mean','std']).sort_values(('AUC', 'mean'))

This will output a df sorted by the AUC-mean column only.

SQL "between" not inclusive

Just use the time stamp as date:

SELECT * FROM Cases WHERE date(created_at)='2013-05-01' 

Convert month name to month number in SQL Server

You can use below code

DECLARE @T TABLE ([Month] VARCHAR(20))
INSERT INTO @T
SELECT 'January'
UNION
SELECT 'February'
UNION
SELECT 'March'`

SELECT MONTH('01-' + [Month] + '-2010') As MonthNumeric,[Month] FROM @T
ORDER BY MonthNumeric

Eclipse "this compilation unit is not on the build path of a java project"

  1. Delete your project (DO NOT DELETE THE ORIGIN FILE IN THE FILE SYSTEM)
  2. Right click at Package explorer area and right click import.
  3. Go to Maven folder and hit import an existing maven project.

Hope it helps

Python send UDP packet

Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.

#!/usr/bin/python

import sys, socket

def main(args):
    ip = args[1]
    port = int(args[2])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    file = 'sample.csv'

    fp = open(file, 'r')
    for line in fp:
        sock.sendto(line.encode('utf-8'), (ip, port))
    fp.close()

main(sys.argv)

The program reads a file, sample.csv from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp then one could run it by doing something like:

$ python send-udp 192.168.1.2 30088

Box-Shadow on the left side of the element only

This question is very, very, very old, but as a trick in the future, I recommend something like this:

.element{
    box-shadow: 0px 0px 10px #232931;
}
.container{
    height: 100px;
    width: 100px;
    overflow: hidden;
}

Basically, you have a box shadow and then wrapping the element in a div with its overflow set to hidden. You'll need to adjust the height, width, and even padding of the div to only show the left box shadow, but it works. See here for an example If you look at the example, you can see how there's no other shadows, but only a black left shadow. Edit: this is a retake of the same screen shot, in case some one thinks that I just cropped out the right. You can find it here

VueJS conditionally add an attribute for an element

Simplest form:

<input :required="test">   // if true
<input :required="!test">  // if false
<input :required="!!test"> // test ? true : false

How to implement a ViewPager with different Fragments / Layouts

Code for adding fragment

public Fragment getItem(int position) {

    switch (position){
        case 0:
            return new Fragment1();

        case 1:
            return new Fragment2();

        case 2:
            return new Fragment3();

        case 3:
            return new Fragment4();

        default:
            break;
    }

    return null;
}

Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.

public class Fragment1 extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container, false);

        return view;

    }
}

Later you can make necessary corrections.. It worked for me.

Why does intellisense and code suggestion stop working when Visual Studio is open?

For python, try clicking on the "Python X.X" button on the left side of the bottom status bar and changing it to different values.

This is the only thing that worked for me.

Python sum() function with list parameter

numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)

This would work, if your are trying to Sum up a list.

Why am I getting Unknown error in line 1 of pom.xml?

For me I changed in the parent tag of the pom.xml and it solved it change 2.1.5 to 2.1.4 then Maven-> Update Project

How to convert JSON object to JavaScript array?

Suppose you have:

var j = {0: "1", 1: "2", 2: "3", 3: "4"};

You could get the values with (supported in practically all browser versions):

Object.keys(j).map(function(_) { return j[_]; })

or simply:

Object.values(j)

Output:

["1", "2", "3", "4"]

The Network Adapter could not establish the connection when connecting with Oracle DB

When a client connects to an Oracle server, it first connnects to the Oracle listener service. It often redirects the client to another port. So the client has to open another connection on a different port, which is blocked by the firewall.

So you might in fact have encountered a firewall problem due to Oracle port redirection. It should be possible to diagnose it with a network monitor on the client machine or with the firewall management software on the firewall.

How to hide image broken Icon using only CSS/HTML?

Using CSS only is tough, but you could use CSS's background-image instead of <img> tags...

Something like this:

HTML

<div id="image"></div>

CSS

#image {
    background-image: url(Error.src);
    width: //width of image;
    height: //height of image;

}

Here is a working fiddle.

Note: I added the border in the CSS on the fiddle just to demonstrate where the image would be.

How to ignore HTML element from tabindex?

Such hack like "tabIndex=-1" not work for me with Chrome v53.

This is which works for chrome, and most browsers:

_x000D_
_x000D_
function removeTabIndex(element) {_x000D_
    element.removeAttribute('tabindex');_x000D_
}
_x000D_
<input tabIndex="1" />_x000D_
<input tabIndex="2" id="notabindex" />_x000D_
<input tabIndex="3" />_x000D_
<button tabIndex="4" onclick="removeTabIndex(document.getElementById('notabindex'))">Remove tabindex</button>
_x000D_
_x000D_
_x000D_

Clear text input on click with AngularJS

Inspired from Robert's answer, but when we use,

ng-click="searchAll = null" in the filter, it makes the model values as null and in-turn the search doesn't work with its normal functionality, so it would be better enough to use ng-click="searchAll = ''" instead

Array vs ArrayList in performance

I agree with somebody's recently deleted post that the differences in performance are so small that, with very very few exceptions, (he got dinged for saying never) you should not make your design decision based upon that.

In your example, where the elements are Objects, the performance difference should be minimal.

If you are dealing with a large number of primitives, an array will offer significantly better performance, both in memory and time.

Why doesn't wireshark detect my interface?

As described in other answer, it's usually caused by incorrectly setting up permissions related to running Wireshark correctly.

Windows machines:

Run Wireshark as administrator.

Wireshark in Administrator privileges.

Stop absolutely positioned div from overlapping text

Thing which works for me is to use padding-bottom on the sibling just before the absolutely-positioned child. Like in your case, it will be like this:

<div style="position: relative; width:600px;">
    <p>Content of unknown length, but quite quite quite quite quite quite quite quite quite quite quite quite quite quite quite quite long</p>
    <div style="padding-bottom: 100px;">Content of unknown height</div>
    <div class="btn" style="position: absolute; right: 0; bottom: 0; width: 200px; height: 100px;background-color: red;"></div>
</div>

How can I convert string to datetime with format specification in JavaScript?

I think this can help you: http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

Update: there's an updated version of the samples available at javascripttoolbox.com

ES6 map an array of objects, to return an array of objects with new keys

You just need to wrap object in ()

_x000D_
_x000D_
var arr = [{_x000D_
  id: 1,_x000D_
  name: 'bill'_x000D_
}, {_x000D_
  id: 2,_x000D_
  name: 'ted'_x000D_
}]_x000D_
_x000D_
var result = arr.map(person => ({ value: person.id, text: person.name }));_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

How to print pthread_t

GDB uses the thread-id (aka kernel pid, aka LWP) for short numbers on Linux. Try:

  #include <syscall.h>
  ...

    printf("tid = %d\n", syscall(SYS_gettid));

How to know if a DateTime is between a DateRange in C#

You could use extension methods to make it a little more readable:

public static class DateTimeExtensions
{
    public static bool InRange(this DateTime dateToCheck, DateTime startDate, DateTime endDate)
    {
        return dateToCheck >= startDate && dateToCheck < endDate;
    }
}

Now you can write:

dateToCheck.InRange(startDate, endDate)

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

Try to run Maven from the command line or type "-X" in the text field - you can't break anything this way, at the worst, you'll get an error (I don't have Netbeans; in Eclipse, there is a checkbox "Debug" for this).

When running with debug output enabled, you should see the paths which the exec-maven-plugin plugin uses.

The next step would then be to copy the command into a command prompt or terminal and execute it manually to see if you get a useful error message there.

SyntaxError: Non-ASCII character '\xa3' in file when function returns '£'

Adding the following two lines at the top of my .py script worked for me (first line was necessary):

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

Android Camera Preview Stretched

i tried all the solution above but none of them works for me. finaly i solved it myself, and find actually it's quite easy. there are two points you need to be careful.

parameters.setPreviewSize(cameraResolution.x, cameraResolution.y);

this previewSize must be one of the camera supported resolution, which can be get as below:

List<Camera.Size> rawSupportedSizes = parameters.getSupportedPreviewSizes(); 

usually one of the rawSupportedSize equals to the device resolution.

Second, place your SurfaceView in a FrameLayout and set the surface layout height and width in surfaceChanged method as above

FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams) surfaceView.getLayoutParams();
layoutParams.height = cameraResolution.x;
layoutParams.width = cameraResolution.y;

Ok, things done, hope this could help you.

Invert "if" statement to reduce nesting

As others have mentioned, there shouldn't be a performance hit, but there are other considerations. Aside from those valid concerns, this also can open you up to gotchas in some circumstances. Suppose you were dealing with a double instead:

public void myfunction(double exampleParam){
    if(exampleParam > 0){
        //Body will *not* be executed if Double.IsNan(exampleParam)
    }
}

Contrast that with the seemingly equivalent inversion:

public void myfunction(double exampleParam){
    if(exampleParam <= 0)
        return;
    //Body *will* be executed if Double.IsNan(exampleParam)
}

So in certain circumstances what appears to be a a correctly inverted if might not be.

Changing the selected option of an HTML Select element

Test this Demo

  1. Selecting Option based on its value

    var vals = [2,'c'];
    
    $('option').each(function(){
       var $t = $(this);
    
       for (var n=vals.length; n--; )
          if ($t.val() == vals[n]){
             $t.prop('selected', true);
             return;
          }
    });
    
  2. Selecting Option based on its text

    var vals = ['Two','CCC'];                   // what we're looking for is different
    
    $('option').each(function(){
       var $t = $(this);
    
       for (var n=vals.length; n--; )
          if ($t.text() == vals[n]){            // method used is different
             $t.prop('selected', true);
             return;
          }
    });
    

Supporting HTML

<select>
   <option value=""></option>
   <option value="1">One</option>
   <option value="2">Two</option>
   <option value="3">Three</option>
</select>

<select>
   <option value=""></option>
   <option value="a">AAA</option>
   <option value="b">BBB</option>
   <option value="c">CCC</option>
</select>

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Html Agility Pack get all elements by class

You can use the following script:

var findclasses = _doc.DocumentNode.Descendants("div").Where(d => 
    d.Attributes.Contains("class") && d.Attributes["class"].Value.Contains("float")
);

jQuery $.ajax request of dataType json will not retrieve data from PHP script

In addition to McHerbie's note, try json_encode( $json_arr, JSON_FORCE_OBJECT ); if you are on PHP 5.3...

Why is exception.printStackTrace() considered bad practice?

In server applications the stacktrace blows up your stdout/stderr file. It may become larger and larger and is filled with useless data because usually you have no context and no timestamp and so on.

e.g. catalina.out when using tomcat as container

Linq : select value in a datatable column

If the return value is string and you need to search by Id you can use:

string name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name")).ToString();

or using generic variable:

var name = datatable.AsEnumerable().Where(row => Convert.ToInt32(row["Id"]) == Id).Select(row => row.Field<string>("name"));

How to allow download of .json file with ASP.NET

Add the JSON MIME type to IIS 6. Follow the directions at MSDN's Configure MIME Types (IIS 6.0).

  • Extension: .json
  • MIME type: application/json

Don't forget to restart IIS after the change.

UPDATE: There are easy ways to do this on IIS7 and newer. The op specifically asked for IIS6 help so I'm leaving this answer as-is. But this answer is still getting a lot of traffic even though IIS6 is very old now. Hopefully you're using something newer, so I wanted to mention that if you have a newer IIS7 or newer version see @ProVega's answer below for a simpler solution for those newer versions.

How to do a non-greedy match in grep?

grep

For non-greedy match in grep you could use a negated character class. In other words, try to avoid wildcards.

For example, to fetch all links to jpeg files from the page content, you'd use:

grep -o '"[^" ]\+.jpg"'

To deal with multiple line, pipe the input through xargs first. For performance, use ripgrep.

Get UserDetails object from Security Context in Spring MVC controller

You can use below code to find out principal (user email who logged in)

  org.opensaml.saml2.core.impl.NameIDImpl principal =  
  (NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();

  String email = principal.getValue();

This code is written on top of SAML.

Uploading images using Node.js, Express, and Mongoose

It will become easy to store files after converting in string you just have to convert string in image in your frontend

convert image in to base64 string using this code in your api and also don't forgot to delete file from upload folder

"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")

to delete the file

       let resultHandler = function (err) {
            if (err) {
                console.log("unlink failed", err);
            } else {
                console.log("file deleted");
            }
        }

        fs.unlink(req.file.path, resultHandler);

at your routes import multer

 `multer const multer = require('multer');
  const upload = multer({ dest: __dirname + '/uploads/images' });`
  Add upload.single('img') in your request

  router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]), 
        upload.single('img'), usersController.fellowsdetails);

OR

If you want save images in localstorage and want save path in database you can try following approach

you have to install first the fs-extra which will create folder. I am creating separate folders by id's if you want to remove it you can remove it. and to save path of image where it is uploaded add this code in your api or controller you are using to save image and and add it in database with other data

    let Id = req.body.id;
    let path = `tmp/daily_gasoline_report/${Id}`;

create separate folder for multer like multerHelper.js

 const multer = require('multer');
 let fs = require('fs-extra');

 let storage = multer.diskStorage({
 destination: function (req, file, cb) {
    let Id = req.body.id;
    let path = `tmp/daily_gasoline_report/${Id}`;
    fs.mkdirsSync(path);
    cb(null, path);
 },
 filename: function (req, file, cb) {
    // console.log(file);

  let extArray = file.mimetype.split("/");
  let extension = extArray[extArray.length - 1];
  cb(null, file.fieldname + '-' + Date.now() + "." + extension);
 }
})

let upload = multer({ storage: storage });

let createUserImage = upload.array('images', 100);

let multerHelper = {
     createUserImage,
}

   module.exports = multerHelper;

In your routes import multerhelper file

   const multerHelper = require("../helpers/multer_helper");

   router.post(multerHelper. createUserImage , function(req, res, next) {
      //Here accessing the body datas.
    })

Python - How to convert JSON File to Dataframe

Creating dataframe from dictionary object.

import pandas as pd
data = [{'name': 'vikash', 'age': 27}, {'name': 'Satyam', 'age': 14}]
df = pd.DataFrame.from_dict(data, orient='columns')

df
Out[4]:
   age  name
0   27  vikash
1   14  Satyam

If you have nested columns then you first need to normalize the data:

data = [
  {
    'name': {
      'first': 'vikash',
      'last': 'singh'
    },
    'age': 27
  },
  {
    'name': {
      'first': 'satyam',
      'last': 'singh'
    },
    'age': 14
  }
]

df = pd.DataFrame.from_dict(pd.json_normalize(data), orient='columns')

df    
Out[8]:
age name.first  name.last
0   27  vikash  singh
1   14  satyam  singh

Source:

How in node to split string by newline ('\n')?

The first one should work:

> "a\nb".split("\n");
[ 'a', 'b' ]
> var a = "test.js\nagain.js"
undefined
> a.split("\n");
[ 'test.js', 'again.js' ]

How to install xgboost in Anaconda Python (Windows platform)?

You can install it using pip:

pip3 install --default-timeout=100 xgboost

Design Patterns web based applications

In the beaten-up MVC pattern, the Servlet is "C" - controller.

Its main job is to do initial request evaluation and then dispatch the processing based on the initial evaluation to the specific worker. One of the worker's responsibilities may be to setup some presentation layer beans and forward the request to the JSP page to render HTML. So, for this reason alone, you need to pass the request object to the service layer.

I would not, though, start writing raw Servlet classes. The work they do is very predictable and boilerplate, something that framework does very well. Fortunately, there are many available, time-tested candidates ( in the alphabetical order ): Apache Wicket, Java Server Faces, Spring to name a few.

PHP random string generator

Finally I have found a solution to get random and unique values.

My solution is:

substr(md5(time()), 0, 12)

time always return a timestamp, and it is always unique. You can use it with MD5 to make it better.

Increase Tomcat memory settings

try setting this

CATALINA_OPTS="-Djava.awt.headless=true -Dfile.encoding=UTF-8 
-server -Xms1536m -Xmx1536m
-XX:NewSize=256m -XX:MaxNewSize=256m -XX:PermSize=256m 
-XX:MaxPermSize=256m -XX:+DisableExplicitGC"

in {$tomcat-folder}\bin\setenv.sh (create it if necessary).

See http://www.mkyong.com/tomcat/tomcat-javalangoutofmemoryerror-permgen-space/ for more details.

Javascript - How to show escape characters in a string?

You have to escape the backslash, so try this:

str = "Hello\\nWorld";

Here are more escaped characters in Javascript.

Angular ngClass and click event for toggling class

If you want to toggle text with a toggle button.

HTMLfile which is using bootstrap:

<input class="btn" (click)="muteStream()"  type="button"
          [ngClass]="status ? 'btn-success' : 'btn-danger'" 
          [value]="status ? 'unmute' : 'mute'"/>

TS file:

muteStream() {
   this.status = !this.status;
}