Programs & Examples On #Private constructor

private constructor

For example, you can invoke a private constructor inside a friend class or a friend function.

Singleton pattern usually uses it to make sure that nobody creates more instances of the intended type.

How to get cookie's expire time

This is difficult to achieve, but the cookie expiration date can be set in another cookie. This cookie can then be read later to get the expiration date. Maybe there is a better way, but this is one of the methods to solve your problem.

How to combine class and ID in CSS selector?

There are differences between #header .callout and #header.callout in css.

Here is the "plain English" of #header .callout:
Select all elements with the class name callout that are descendants of the element with an ID of header.

And #header.callout means:
Select the element which has an ID of header and also a class name of callout.

You can read more here css tricks

How to center a checkbox in a table cell?

If you don't support legacy browsers, I'd use flexbox because it's well supported and will simply solve most of your layout problems.

#table-id td:nth-child(1) { 
    /* nth-child(1) is the first column, change to fit your needs */
    display: flex;
    justify-content: center;
}

This centers all content in the first <td> of every row.

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

get current date from [NSDate date] but set the time to 10:00 am

this nsdate used different format:

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMM dd, yyyy HH:mm"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:now];

NSDateFormatter *inFormat = [[NSDateFormatter alloc] init];
[inFormat setDateFormat:@"MMM dd, yyyy"];

NSDate *parsed = [inFormat dateFromString:dateString]; 

python location on mac osx

This one will solve all your problems not only for Mac but works on every basic shell -> Linux also:

If you have a Mac and you've installed python3 like most of us do :) (with brew install - ofc)

your file is located in:

/usr/local/Cellar/python/3.6.4_4/bin/python3

How do you know? -> you can run this on every basic shell Run:

which python3

You should get:

/usr/local/bin/python3

Now this is a symbolic link, how do you know? Run:

ls -al /usr/local/bin/python3 

and you'll get:

/usr/local/bin/python3 -> /usr/local/Cellar/python/3.6.4_4/bin/python3

which means that your

/usr/local/bin/python3 

is actually pointing to:

/usr/local/Cellar/python/3.6.4_4/bin/python3

If, for some reason, your

/usr/local/bin/python3 

is not pointing to the place you want, which in our case:

/usr/local/Cellar/python/3.6.4_4/bin/python3

just backup it:

cp /usr/local/bin/python3{,.orig} 

and run:

rm -rf /usr/local/bin/python3

now create a new symbolic link:

ln -s /usr/local/Cellar/python/3.6.4_4/bin/python3 /usr/local/bin/python3 

and now your

/usr/local/bin/python3

is pointing to

/usr/local/Cellar/python/3.6.4_4/bin/python3 

Check it out by running:

ls -al /usr/local/bin/python3

incompatible character encodings: ASCII-8BIT and UTF-8

ASCII-8BIT is Ruby's description for characters above the normal 0-0x7f ASCII character-set, and that are single-byte characters. Typically that would be something like ISO-8859-1, or one of its siblings.

If you can identify which character is causing the problem, then you can tell Ruby 1.9.2 to convert between the character set of that character to UTF-8.

James Grey wrote a series of blogs talking about these sort of problems and how to deal with them. I'd recommend going through them.

incompatible character encodings: ASCII-8BIT and UTF-8

That typically happens because you are trying to concatenate two strings, and one contains characters that do not map to the character-set of the other string. There are characters in ISO-8859-1 that do not have equivalents in UTF-8, and vice-versa and how to handle string joining with those incompatibilities requires the programmer to step in.

Passing parameters to JavaScript files

Although this question has been asked a while ago, it is still relevant as of today. This is not a trivial approach using script file params, but I already had some extreme use-cases that this way was most suited.

I came across this post to find out a better solution than I wrote a while ago, with hope to find maybe a native feature or something similar.
I will share my solution, up until a better one will be implemented. This works on most modern browsers, maybe even on older ones, didn't try.

All the solutions above, are based on the fact that it has to be injected with predefined and well marked SCRIPT tag and rely completely on the HTML implementation. But, what if the script is injected dynamically, or even worse, what if you are write a library, that will be used in a variety of websites?
In these and some other cases, all the above answers are not sufficient and even becoming too complicated.

First, let's try to understand what do we need to achieve here. All we need to do is to get the URL of the script itself, from there it's a piece of cake.

There is actually a nice trick to get the script URL from the script itself. One of the functionalities of the native Error class, is the ability to provide a stack trace of the "problematic location", including the exact file trace to the last call. In order to achieve this, I will use the stack property of the Error instance, that once created, will give the full stack trace.

Here is how the magic works:

// The pattern to split each row in the stack trace string
const STACK_TRACE_SPLIT_PATTERN = /(?:Error)?\n(?:\s*at\s+)?/;
// For browsers, like Chrome, IE, Edge and more.
const STACK_TRACE_ROW_PATTERN1 = /^.+?\s\((.+?):\d+:\d+\)$/;
// For browsers, like Firefox, Safari, some variants of Chrome and maybe other browsers.
const STACK_TRACE_ROW_PATTERN2 = /^(?:.*?@)?(.*?):\d+(?::\d+)?$/;

const getFileParams = () => {
    const stack = new Error().stack;
    const row = stack.split(STACK_TRACE_SPLIT_PATTERN, 2)[1];
    const [, url] = row.match(STACK_TRACE_ROW_PATTERN1) || row.match(STACK_TRACE_ROW_PATTERN2) || [];
    if (!url) {
        console.warn("Something went wrong. You should debug it and find out why.");
        return;
    }
    try {
        const urlObj = new URL(url);
        return urlObj.searchParams; // This feature doesn't exists in IE, in this case you should use urlObj.search and handle the query parsing by yourself.
    } catch (e) {
        console.warn(`The URL '${url}' is not valid.`);
    }
}

Now, in any case of script call, like in the OP case:

<script type="text/javascript" src="file.js?obj1=somevalue&obj2=someothervalue"></script>

In the file.js script, you can now do:

const params = getFileParams();
console.log(params.get('obj2'));
// Prints: someothervalue

This will also work with RequireJS and other dynamically injected file scripts.

How to enter in a Docker container already running with a new TTY

I started powershell on a running microsoft/iis run as daemon using

docker exec -it <nameOfContainer> powershell

How can I escape a double quote inside double quotes?

A simple example of escaping quotes in the shell:

$ echo 'abc'\''abc'
abc'abc
$ echo "abc"\""abc"
abc"abc

It's done by finishing an already-opened one ('), placing the escaped one (\'), and then opening another one (').

Alternatively:

$ echo 'abc'"'"'abc'
abc'abc
$ echo "abc"'"'"abc"
abc"abc

It's done by finishing already opened one ('), placing a quote in another quote ("'"), and then opening another one (').

More examples: Escaping single-quotes within single-quoted strings

How to redirect to the same page in PHP

A quick easy approach if you are not concerned about query params:

header("location: ./");

Git pushing to remote branch

Simply push this branch to a different branch name

 git push -u origin localBranch:remoteBranch

What's the difference between the atomic and nonatomic attributes?

To simplify the entire confusion, let us understand mutex lock.

Mutex lock, as per the name, locks the mutability of the object. So if the object is accessed by a class, no other class can access the same object.

In iOS, @sychronise also provides the mutex lock .Now it serves in FIFO mode and ensures the flow is not affected by two classes sharing the same instance. However, if the task is on main thread, avoid accessing object using atomic properties as it may hold your UI and degrade the performance.

What is let-* in Angular 2 templates?

The Angular microsyntax lets you configure a directive in a compact, friendly string. The microsyntax parser translates that string into attributes on the <ng-template>. The let keyword declares a template input variable that you reference within the template.

Populating a data frame in R in a loop

You could do it like this:

 iterations = 10
 variables = 2

 output <- matrix(ncol=variables, nrow=iterations)

 for(i in 1:iterations){
  output[i,] <- runif(2)

 }

 output

and then turn it into a data.frame

 output <- data.frame(output)
 class(output)

what this does:

  1. create a matrix with rows and columns according to the expected growth
  2. insert 2 random numbers into the matrix
  3. convert this into a dataframe after the loop has finished.

How to multiply all integers inside list

The most pythonic way would be to use a list comprehension:

l = [2*x for x in l]

If you need to do this for a large number of integers, use numpy arrays:

l = numpy.array(l, dtype=int)*2

A final alternative is to use map

l = list(map(lambda x:2*x, l))

List only stopped Docker containers

docker container list -f "status=exited"

or

docker container ls -f "status=exited"

or

 docker ps -f "status=exited"

SQL-Server: Error - Exclusive access could not be obtained because the database is in use

Use the following script to find and kill all the opened connections to the database before restoring database.

declare @sql as varchar(20), @spid as int

select @spid = min(spid)  from master..sysprocesses  where dbid = db_id('<database_name>') 
and spid != @@spid    

while (@spid is not null)
begin
    print 'Killing process ' + cast(@spid as varchar) + ' ...'
    set @sql = 'kill ' + cast(@spid as varchar)
    exec (@sql)

    select 
        @spid = min(spid)  
    from 
        master..sysprocesses  
    where 
        dbid = db_id('<database_name>') 
        and spid != @@spid
end 

print 'Process completed...'

Hope this will help...

Android getResources().getDrawable() deprecated API 22

Now you need to implement like this

  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { //>= API 21
        //
    } else {
        //
    }

Following single line of code is enough, everything will take care by ContextCompat.getDrawable

ContextCompat.getDrawable(this, R.drawable.your_drawable_file)

what does "error : a nonstatic member reference must be relative to a specific object" mean?

Only static functions are called with class name.

classname::Staicfunction();

Non static functions have to be called using objects.

classname obj;
obj.Somefunction();

This is exactly what your error means. Since your function is non static you have to use a object reference to invoke it.

How can I get a Dialog style activity window to fill the screen?

This would be helpful for someone like me. Create custom dialog style:

<style name="MyDialog" parent="Theme.AppCompat.Light.Dialog">
    <item name="windowNoTitle">true</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowIsFloating">false</item>
</style>

In AndroidManifest.xml file set theme for wanted activity:

<activity
        android:name=".CustomDialog"
        ...
        android:theme="@style/MyDialog"/>

That is all, no need to call methods programaticaly.

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

Copy a git repo without history

Deleting the .git folder is probably the easiest path since you don't want/need the history (as Stephan said).

So you can create a new repo from your latest commit: (How to clone seed/kick-start project without the whole history?)

git clone <git_url>

then delete .git, and afterwards run

git init

Or if you want to reuse your current repo: Make the current commit the only (initial) commit in a Git repository?

Follow the above steps then:

git add .
git commit -m "Initial commit"

Push to your repo.

git remote add origin <github-uri>
git push -u --force origin master

How to parse/format dates with LocalDateTime? (Java 8)

I found the it wonderful to cover multiple variants of date time format like this:

final DateTimeFormatterBuilder dtfb = new DateTimeFormatterBuilder();
dtfb.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSSS"))
.appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSSS"))
    .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))
    .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SS"))
    .appendOptional(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S"))
    .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
    .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
    .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0);

How to get ID of the last updated row in MySQL?

Query :

$sqlQuery = "UPDATE 
            update_table 
        SET 
            set_name = 'value' 
        WHERE 
            where_name = 'name'
        LIMIT 1;";

PHP function:

function updateAndGetId($sqlQuery)
{
    mysql_query(str_replace("SET", "SET id = LAST_INSERT_ID(id),", $sqlQuery));
    return mysql_insert_id();
}

It's work for me ;)

Visual Studio Code Tab Key does not insert a tab

Make sure this is NOT checked :

[ ] Tools | Options | Text Editor | C/C++ | Formatting | Automatic Indentation On Tab

Let me know if this helped!

How to loop through a directory recursively to delete files with certain extensions

This method handles spaces well.

files="$(find -L "$dir" -type f)"
echo "Count: $(echo -n "$files" | wc -l)"
echo "$files" | while read file; do
  echo "$file"
done

Edit, fixes off-by-one

function count() {
    files="$(find -L "$1" -type f)";
    if [[ "$files" == "" ]]; then
        echo "No files";
        return 0;
    fi
    file_count=$(echo "$files" | wc -l)
    echo "Count: $file_count"
    echo "$files" | while read file; do
        echo "$file"
    done
}

mysqli_connect(): (HY000/2002): No connection could be made because the target machine actively refused it

In your PHP code you have set the incorrect port, this is what the code should be

<?php

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$db     = 'test_db13';

The port in your code is set to 3360 when it should be 3306, however as this is the default port, you don't need to specify.

Excel formula to remove space between words in a cell

It is SUBSTITUTE(B1," ",""), not REPLACE(xx;xx;xx).

Swift - How to convert String to Double

SWIFT 3

To clear, nowadays there is a default method:

public init?(_ text: String)` of `Double` class.

It can be used for all classes.

let c = Double("-1.0")
let f = Double("0x1c.6")
let i = Double("inf")

, etc.

How to take off line numbers in Vi?

To turn off line numbering, again follow the preceding instructions, except this time enter the following line at the : prompt:

set nonumber

jQuery.getJSON - Access-Control-Allow-Origin Issue

It's simple, use $.getJSON() function and in your URL just include

callback=?

as a parameter. That will convert the call to JSONP which is necessary to make cross-domain calls. More info: http://api.jquery.com/jQuery.getJSON/

How do I pass multiple attributes into an Angular.js attribute directive?

You could pass an object as attribute and read it into the directive like this:

<div my-directive="{id:123,name:'teo',salary:1000,color:red}"></div>

app.directive('myDirective', function () {
    return {            
        link: function (scope, element, attrs) {
           //convert the attributes to object and get its properties
           var attributes = scope.$eval(attrs.myDirective);       
           console.log('id:'+attributes.id);
           console.log('id:'+attributes.name);
        }
    };
});

Retrieving the text of the selected <option> in <select> element

If you use jQuery then you can write the following code:

$("#selectId option:selected").html();

Is there a limit on an Excel worksheet's name length?

My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.

Add new field to every document in a MongoDB collection

if you are using mongoose try this,after mongoose connection

async ()=> await Mongoose.model("collectionName").updateMany({}, {$set: {newField: value}})

Creating a directory in /sdcard fails

File f = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
        + "/FoderName");
if (!f.exists()) {
    f.mkdirs();
}

How to create a custom navigation drawer in android

I used below layout and able to achieve custom layout in Navigation View.

<android.support.design.widget.NavigationView
        android:id="@+id/navi_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start|top"
        android:background="@color/navigation_view_bg_color"
        app:theme="@style/NavDrawerTextStyle">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <include layout="@layout/drawer_header" />

            <include layout="@layout/navigation_drawer_menu" />
        </LinearLayout>
</android.support.design.widget.NavigationView> 

pandas groupby sort within groups

Try this Instead

simple way to do 'groupby' and sorting in descending order

df.groupby(['companyName'])['overallRating'].sum().sort_values(ascending=False).head(20)

Displaying standard DataTables in MVC

Here is the answer in Razor syntax

 <table border="1" cellpadding="5">
    <thead>
       <tr>
          @foreach (System.Data.DataColumn col in Model.Columns)
          {
             <th>@col.Caption</th>
          }
       </tr>
    </thead>
    <tbody>
    @foreach(System.Data.DataRow row in Model.Rows)
    {
       <tr>
          @foreach (var cell in row.ItemArray)
          {
             <td>@cell.ToString()</td>
          }
       </tr>
    }      
    </tbody>
</table>

Laravel 5.2 - pluck() method returns array

laravel pluck returns an array

if your query is:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

then the array is like this (key is the index of the item. auto incremented value):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

but if you do like this:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

then the key is actual index in the database.

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

you can set any value as key.

How do I copy an object in Java?

I use Google's JSON library to serialize it then create a new instance of the serialized object. It does deep copy with a few restrictions:

  • there can't be any recursive references

  • it won't copy arrays of disparate types

  • arrays and lists should be typed or it won't find the class to instantiate

  • you may need to encapsulate strings in a class you declare yourself

I also use this class to save user preferences, windows and whatnot to be reloaded at runtime. It is very easy to use and effective.

import com.google.gson.*;

public class SerialUtils {

//___________________________________________________________________________________

public static String serializeObject(Object o) {
    Gson gson = new Gson();
    String serializedObject = gson.toJson(o);
    return serializedObject;
}
//___________________________________________________________________________________

public static Object unserializeObject(String s, Object o){
    Gson gson = new Gson();
    Object object = gson.fromJson(s, o.getClass());
    return object;
}
       //___________________________________________________________________________________
public static Object cloneObject(Object o){
    String s = serializeObject(o);
    Object object = unserializeObject(s,o);
    return object;
}
}

How can I backup a remote SQL Server database to a local drive?

You can use Copy database ... right click on the remote database ... select tasks and use copy database ... it will asks you about source server and destination server . that your source is the remote and destination is your local instance of sql server.

it's that easy

Working around MySQL error "Deadlock found when trying to get lock; try restarting transaction"

Note that if you use SELECT FOR UPDATE to perform a uniqueness check before an insert, you will get a deadlock for every race condition unless you enable the innodb_locks_unsafe_for_binlog option. A deadlock-free method to check uniqueness is to blindly insert a row into a table with a unique index using INSERT IGNORE, then to check the affected row count.

add below line to my.cnf file

innodb_locks_unsafe_for_binlog = 1

#

1 - ON
0 - OFF

#

Printing Python version in output

Try

import sys
print(sys.version)

This prints the full version information string. If you only want the python version number, then Bastien Léonard's solution is the best. You might want to examine the full string and see if you need it or portions of it.

Scroll RecyclerView to show selected item on top

I don't know why I didn't find the best answer but its really simple.

recyclerView.smoothScrollToPosition(position);

No errors

Creates Animations

Set timeout for ajax (jQuery)

Please read the $.ajax documentation, this is a covered topic.

$.ajax({
    url: "test.html",
    error: function(){
        // will fire when timeout is reached
    },
    success: function(){
        //do something
    },
    timeout: 3000 // sets timeout to 3 seconds
});

You can get see what type of error was thrown by accessing the textStatus parameter of the error: function(jqXHR, textStatus, errorThrown) option. The options are "timeout", "error", "abort", and "parsererror".

Check if a path represents a file or a folder

String path = "Your_Path";
File f = new File(path);

if (f.isDirectory()){



  }else if(f.isFile()){



  }

Express.js: how to get remote client address

This is just additional information for this answer.

If you are using nginx, you would add proxy_set_header X-Real-IP $remote_addr; to the location block for the site. /etc/nginx/sites-available/www.example.com for example. Here is a example server block.

server {
    listen 80;
    listen [::]:80;

    server_name example.com www.example.com;

    location / {
        proxy_set_header  X-Real-IP  $remote_addr;
        proxy_pass http://127.0.1.1:3080;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

After restarting nginx, you will be able to access the ip in your node/express application routes with req.headers['x-real-ip'] || req.connection.remoteAddress;

What is the equivalent to a JavaScript setInterval/setTimeout in Android/Java?

The first answer is definitely the correct answer and is what I based this lambda version off of, which is much shorter in syntax. Since Runnable has only 1 override method "run()", we can use a lambda:

this.m_someBoolFlag = false;
new android.os.Handler().postDelayed(() -> this.m_someBoolFlag = true, 300);

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Xerces-based tools will emit the following error

The processing instruction target matching "[xX][mM][lL]" is not allowed.

when an XML declaration is encountered anywhere other than at the top of an XML file.

This is a valid diagnostic message; other XML parsers should issue a similar error message in this situation.

To correct the problem, check the following possibilities:

  1. Some blank space or other visible content exists before the <?xml ?> declaration.

    Resolution: remove blank space or any other visible content before the XML declaration.

  2. Some invisible content exists before the <?xml ?> declaration. Most commonly this is a Byte Order Mark (BOM).

    Resolution: Remove the BOM using techniques such as those suggested by the W3C page on the BOM in HTML.

  3. A stray <?xml ?> declaration exists within the XML content. This can happen when XML files are combined programmatically or via cut-and-paste. There can only be one <?xml ?> declaration in an XML file, and it can only be at the top.

    Resolution: Search for <?xml in a case-insensitive manner, and remove all but the top XML declaration from the file.

Binding an enum to a WinForms combo box, and then setting it

comboBox1.SelectedItem = MyEnum.Something;

should work just fine ... How can you tell that SelectedItem is null?

How to make a vertical SeekBar in Android?

Try:

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

<SeekBar 
    android:id="@+id/seekBar1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:rotation="270" 
    /> 

</RelativeLayout> 

Calculating sum of repeated elements in AngularJS ng-repeat

This is a simple way to do this with ng-repeat and ng-init to aggregate all the values and extend the model with a item.total property.

<table>
<tr ng-repeat="item in items" ng-init="setTotals(item)">
                    <td>{{item.name}}</td>
                    <td>{{item.quantity}}</td>
                    <td>{{item.unitCost | number:2}}</td>
                    <td>{{item.total | number:2}}</td>
</tr>
<tr class="bg-warning">
                    <td>Totals</td>
                    <td>{{invoiceCount}}</td>
                    <td></td>                    
                    <td>{{invoiceTotal | number:2}}</td>
                </tr>
</table>

The ngInit directive calls the set total function for each item. The setTotals function in the controller calculates each item total. It also uses the invoiceCount and invoiceTotal scope variables to aggregate (sum) the quantity and total for all items.

$scope.setTotals = function(item){
        if (item){
            item.total = item.quantity * item.unitCost;
            $scope.invoiceCount += item.quantity;
            $scope.invoiceTotal += item.total;
        }
    }

for more information and demo look at this link:

http://www.ozkary.com/2015/06/angularjs-calculate-totals-using.html

How to generate different random numbers in a loop in C++?

The way the function rand() works is that every time you call it, it generates a random number. In your code, you've called it once and stored it into the variable random_x. To get your desired random numbers instead of storing it into a variable, just call the function like this:

for (int t=0;t<10;t++)
{
    cout << "\nRandom X = " << rand() % 100;
}

How to pass a querystring or route parameter to AWS Lambda from Amazon API Gateway

exports.handler = async (event) => {
    let query = event.queryStringParameters;
    console.log(`id: ${query.id}`);
    const response = {
        statusCode: 200,
        body: "Hi",
    };
    return response;
};

New og:image size for Facebook share?

I'm using the minimum image size (200 x 200) and getting good results. Take a look:

enter image description here https://developers.facebook.com/tools/debug/og/object?q=origgami.com.br

This squared size is better than rectangles because it is the format that appears on facebook comments. The rectangle format gets cropped.

This size is on facebook documentation

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

Add a second });.

When properly indented, your code reads

$(function() {
    $("#mewlyDiagnosed").hover(function() {
        $("#mewlyDiagnosed").animate({'height': '237px', 'top': "-75px"});
    }, function() {
        $("#mewlyDiagnosed").animate({'height': '162px', 'top': "0px"});
    });
MISSING!

You never closed the outer $(function() {.

Run git pull over all subdirectories

gitfox is a tool to execute command on all subrepos

npm install gitfox -g
g pull

python JSON only get keys in first level

Just do a simple .keys()

>>> dct = {
...     "1": "a", 
...     "3": "b", 
...     "8": {
...         "12": "c", 
...         "25": "d"
...     }
... }
>>> 
>>> dct.keys()
['1', '8', '3']
>>> for key in dct.keys(): print key
...
1
8
3
>>>

If you need a sorted list:

keylist = dct.keys()
keylist.sort()

Image change every 30 seconds - loop

You should take a look at various javascript libraries, they should be able to help you out:

All of them have tutorials, and fade in/fade out is a basic usage.

For e.g. in jQuery:

var $img = $("img"), i = 0, speed = 200;
window.setInterval(function() {
  $img.fadeOut(speed, function() {
    $img.attr("src", images[(++i % images.length)]);
    $img.fadeIn(speed);
  });
}, 30000);

How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?

Easiest ways to get file name:

val fileName = File(uri.path).name
// or
val fileName = uri.pathSegments.last()

If they don't give you the right name you should use:

fun Uri.getName(context: Context): String {
    val returnCursor = context.contentResolver.query(this, null, null, null, null)
    val nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
    returnCursor.moveToFirst()
    val fileName = returnCursor.getString(nameIndex)
    returnCursor.close()
    return fileName
}

How to execute XPath one-liners from shell?

My Python script xgrep.py does exactly this. In order to search for all attributes attribute of elements element in files filename.xml ..., you would run it as follows:

xgrep.py "//element/@attribute" filename.xml ...

There are various switches for controlling the output, such as -c for counting matches, -i for indenting the matching parts, and -l for outputting filenames only.

The script is not available as a Debian or Ubuntu package, but all of its dependencies are.

Get Today's date in Java at midnight time

Defining ‘Midnight’

The word “midnight” is tricky to define.

Some think of it as the moment before a new day starts. Trying to represent that in software as tricky as the last moment of the day can always be subdivided as a smaller fraction of a second.

I suggest a better way of thinking about this is to get “first moment of the day”.

This supports the commonly used approach of defining a span of time as ‘Half-Open’, where the beginning is inclusive while the ending is exclusive. So a full day starts with the first moment of the day and runs up to, but not including, the first moment of the following day. A full day would like this (notice the date going from the 3rd to the 4th):

2016-02-03T00:00:00.0-08:00[America/Los_Angeles]/2016-02-04T00:00:00.0-08:00[America/Los_Angeles]

Joda-Time

If using the Joda-Time library, call withTimeAtStartOfDay.

Note how we specify the time zone. If omitted, the JVM’s current default time zone is implicitly applied. Better to be explicit.

DateTime todayStart = DateTime.now( DateTimeZone.forID( "America/Montreal" ) ).withTimeAtStartOfDay() ;

If using Java 8 or later, better to use the java.time package built into Java. See sibling Answer by Jens Hoffman.

How to add months to a date in JavaScript?

Split your date into year, month, and day components then use Date:

var d = new Date(year, month, day);
d.setMonth(d.getMonth() + 8);

Date will take care of fixing the year.

Remove space above and below <p> tag HTML

<p> tags have built in padding and margin. You could create a CSS selector combined with some javascript for instances when your <p> is empty. Probably overkill, but it should do what you need it to do.

CSS example: .NoPaddingOrMargin {padding: 0px; margin:0px}

Store output of sed into a variable

In general,

variable=$(command)

or

variable=`command`

The latter one is the old syntax, prefer $(command).

Note: variable = .... means execute the command variable with the first argument =, the second ....

sed edit file in place

If you are replacing the same amount of characters and after carefully reading “In-place” editing of files...

You can also use the redirection operator <> to open the file to read and write:

sed 's/foo/bar/g' file 1<> file

See it live:

$ cat file
hello
i am here                           # see "here"
$ sed 's/here/away/' file 1<> file  # Run the `sed` command
$ cat file
hello
i am away                           # this line is changed now

From Bash Reference Manual ? 3.6.10 Opening File Descriptors for Reading and Writing:

The redirection operator

[n]<>word

causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.

What are these attributes: `aria-labelledby` and `aria-hidden`

Aria is used to improve the user experience of visually impaired users. Visually impaired users navigate though application using screen reader software like JAWS, NVDA,.. While navigating through the application, screen reader software announces content to users. Aria can be used to add content in the code which helps screen reader users understand role, state, label and purpose of the control

Aria does not change anything visually. (Aria is scared of designers too).

aria-hidden:

aria-hidden attribute is used to hide content for visually impaired users who navigate through application using screen readers (JAWS, NVDA,...).

aria-hidden attribute is used with values true, false.

How To Use:

<i class = "fa fa-books" aria-hidden = "true"></i>

using aria-hidden = "true" on the <i> hides content to screen reader users with no visual change in the application.

aria-label

aria-label attribute is used to communicate the label to screen reader users. Usually search input field does not have visual label (thanks to designers). aria-label can be used to communicate the label of control to screen reader users

How To Use:

<input type = "edit" aria-label = "search" placeholder = "search">

There is no visual change in application. But screen readers can understand the purpose of control

aria-labelledby

Both aria-label and aria-labelledby is used to communicate the label. But aria-labelledby can be used to reference any label already present in the page whereas aria-label is used to communicate the label which i not displayed visually

Approach 1:

<span id = "sd"> Search </span>

<input type = "text" aria-labelledby = "sd">

aria-labelledby can also be used to combine two labels for screen reader users

Approach 2:

<span id = "de"> Billing Address </span>

<span id = "sd"> First Name </span>

<input type = "text" aria-labelledby = "de sd">

Properly escape a double quote in CSV

Not only double quotes, you will be in need for single quote ('), double quote ("), backslash (\) and NUL (the NULL byte).

Use fputcsv() to write, and fgetcsv() to read, which will take care of all.

How do you set autocommit in an SQL Server session?

You can turn autocommit ON by setting implicit_transactions OFF:

SET IMPLICIT_TRANSACTIONS OFF

When the setting is ON, it returns to implicit transaction mode. In implicit transaction mode, every change you make starts a transactions which you have to commit manually.

Maybe an example is clearer. This will write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
COMMIT TRANSACTION

This will not write a change to the database:

SET IMPLICIT_TRANSACTIONS ON
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

The following example will update a row, and then complain that there's no transaction to commit:

SET IMPLICIT_TRANSACTIONS OFF
UPDATE MyTable SET MyField = 1 WHERE MyId = 1
ROLLBACK TRANSACTION

Like Mitch Wheat said, autocommit is the default for Sql Server 2000 and up.

Python group by

I also liked pandas simple grouping. it's powerful, simple and most adequate for large data set

result = pandas.DataFrame(input).groupby(1).groups

Convert seconds to HH-MM-SS with JavaScript?

var time1 = date1.getTime();
var time2 = date2.getTime();
var totalMilisec = time2 - time1;

alert(DateFormat('hh:mm:ss',new Date(totalMilisec)))

 /* ----------------------------------------------------------
 *  Field        | Full Form          | Short Form
 *  -------------|--------------------|-----------------------
 *  Year         | yyyy (4 digits)    | yy (2 digits)
 *  Month        | MMM (abbr.)        | MM (2 digits)
                 | NNN (name)         |
 *  Day of Month | dd (2 digits)      | 
 *  Day of Week  | EE (name)          | E (abbr)
 *  Hour (1-12)  | hh (2 digits)      | 
 *  Minute       | mm (2 digits)      | 
 *  Second       | ss (2 digits)      | 
 *  ----------------------------------------------------------
 */
function DateFormat(formatString,date){
    if (typeof date=='undefined'){
    var DateToFormat=new Date();
    }
    else{
        var DateToFormat=date;
    }
    var DAY         = DateToFormat.getDate();
    var DAYidx      = DateToFormat.getDay();
    var MONTH       = DateToFormat.getMonth()+1;
    var MONTHidx    = DateToFormat.getMonth();
    var YEAR        = DateToFormat.getYear();
    var FULL_YEAR   = DateToFormat.getFullYear();
    var HOUR        = DateToFormat.getHours();
    var MINUTES     = DateToFormat.getMinutes();
    var SECONDS     = DateToFormat.getSeconds();

    var arrMonths = new Array("January","February","March","April","May","June","July","August","September","October","November","December");
    var arrDay=new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
    var strMONTH;
    var strDAY;
    var strHOUR;
    var strMINUTES;
    var strSECONDS;
    var Separator;

    if(parseInt(MONTH)< 10 && MONTH.toString().length < 2)
        strMONTH = "0" + MONTH;
    else
        strMONTH=MONTH;
    if(parseInt(DAY)< 10 && DAY.toString().length < 2)
        strDAY = "0" + DAY;
    else
        strDAY=DAY;
    if(parseInt(HOUR)< 10 && HOUR.toString().length < 2)
        strHOUR = "0" + HOUR;
    else
        strHOUR=HOUR;
    if(parseInt(MINUTES)< 10 && MINUTES.toString().length < 2)
        strMINUTES = "0" + MINUTES;
    else
        strMINUTES=MINUTES;
    if(parseInt(SECONDS)< 10 && SECONDS.toString().length < 2)
        strSECONDS = "0" + SECONDS;
    else
        strSECONDS=SECONDS;

    switch (formatString){
        case "hh:mm:ss":
            return strHOUR + ':' + strMINUTES + ':' + strSECONDS;
        break;
        //More cases to meet your requirements.
    }
}

how to set imageview src?

To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.

If you have image in the form of bitmap then use

imageview.setImageBitmap(bm);

If you have image in the form of drawable then use

imageview.setImageDrawable(drawable);

If you have image in your resource example if image is present in drawable folder then use

imageview.setImageResource(R.drawable.image);

If you have path of image then use

imageview.setImageURI(Uri.parse("pathofimage"));

How do I catch a numpy warning like it's an exception (not just for testing)?

It seems that your configuration is using the print option for numpy.seterr:

>>> import numpy as np
>>> np.array([1])/0   #'warn' mode
__main__:1: RuntimeWarning: divide by zero encountered in divide
array([0])
>>> np.seterr(all='print')
{'over': 'warn', 'divide': 'warn', 'invalid': 'warn', 'under': 'ignore'}
>>> np.array([1])/0   #'print' mode
Warning: divide by zero encountered in divide
array([0])

This means that the warning you see is not a real warning, but it's just some characters printed to stdout(see the documentation for seterr). If you want to catch it you can:

  1. Use numpy.seterr(all='raise') which will directly raise the exception. This however changes the behaviour of all the operations, so it's a pretty big change in behaviour.
  2. Use numpy.seterr(all='warn'), which will transform the printed warning in a real warning and you'll be able to use the above solution to localize this change in behaviour.

Once you actually have a warning, you can use the warnings module to control how the warnings should be treated:

>>> import warnings
>>> 
>>> warnings.filterwarnings('error')
>>> 
>>> try:
...     warnings.warn(Warning())
... except Warning:
...     print 'Warning was raised as an exception!'
... 
Warning was raised as an exception!

Read carefully the documentation for filterwarnings since it allows you to filter only the warning you want and has other options. I'd also consider looking at catch_warnings which is a context manager which automatically resets the original filterwarnings function:

>>> import warnings
>>> with warnings.catch_warnings():
...     warnings.filterwarnings('error')
...     try:
...         warnings.warn(Warning())
...     except Warning: print 'Raised!'
... 
Raised!
>>> try:
...     warnings.warn(Warning())
... except Warning: print 'Not raised!'
... 
__main__:2: Warning: 

How to import the class within the same directory or sub directory?

I just learned (thanks to martineau's comment) that, in order to import classes from files within the same directory, you would now write in Python 3:

from .user import User
from .dir import Dir

How to get current time and date in C++?

I found this link pretty useful for my implementation: C++ Date and Time

Here's the code I use in my implementation, to get a clear "YYYYMMDD HHMMSS" output format. The param in is for switching between UTC and local time. You can easily modify my code to suite your need.

#include <iostream>
#include <ctime>

using namespace std;

/**
 * This function gets the current date time
 * @param useLocalTime true if want to use local time, default to false (UTC)
 * @return current datetime in the format of "YYYYMMDD HHMMSS"
 */

string getCurrentDateTime(bool useLocalTime) {
    stringstream currentDateTime;
    // current date/time based on current system
    time_t ttNow = time(0);
    tm * ptmNow;

    if (useLocalTime)
        ptmNow = localtime(&ttNow);
    else
        ptmNow = gmtime(&ttNow);

    currentDateTime << 1900 + ptmNow->tm_year;

    //month
    if (ptmNow->tm_mon < 9)
        //Fill in the leading 0 if less than 10
        currentDateTime << "0" << 1 + ptmNow->tm_mon;
    else
        currentDateTime << (1 + ptmNow->tm_mon);

    //day
    if (ptmNow->tm_mday < 10)
        currentDateTime << "0" << ptmNow->tm_mday << " ";
    else
        currentDateTime <<  ptmNow->tm_mday << " ";

    //hour
    if (ptmNow->tm_hour < 10)
        currentDateTime << "0" << ptmNow->tm_hour;
    else
        currentDateTime << ptmNow->tm_hour;

    //min
    if (ptmNow->tm_min < 10)
        currentDateTime << "0" << ptmNow->tm_min;
    else
        currentDateTime << ptmNow->tm_min;

    //sec
    if (ptmNow->tm_sec < 10)
        currentDateTime << "0" << ptmNow->tm_sec;
    else
        currentDateTime << ptmNow->tm_sec;


    return currentDateTime.str();
}

Output (UTC, EST):

20161123 000454
20161122 190454

bind/unbind service example (android)

First of all, two things that we need to understand,

Client

  • It makes request to a specific server

bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"), mServiceConn, Context.BIND_AUTO_CREATE);

here mServiceConn is instance of ServiceConnection class(inbuilt) it is actually interface that we need to implement with two (1st for network connected and 2nd network not connected) method to monitor network connection state.

Server

  • It handles the request of the client and makes replica of its own which is private to client only who send request and this raplica of server runs on different thread.

Now at client side, how to access all the methods of server?

  • Server sends response with IBinder Object. So, IBinder object is our handler which accesses all the methods of Service by using (.) operator.

.

MyService myService;
public ServiceConnection myConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className, IBinder binder) {
        Log.d("ServiceConnection","connected");
        myService = binder;
    }
    //binder comes from server to communicate with method's of 

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
}

Now how to call method which lies in service

myservice.serviceMethod();

Here myService is object and serviceMethod is method in service. and by this way communication is established between client and server.

PHP: Calling another class' method

//file1.php
<?php

class ClassA
{
   private $name = 'John';

   function getName()
   {
     return $this->name;
   }   
}
?>

//file2.php
<?php
   include ("file1.php");

   class ClassB
   {

     function __construct()
     {
     }

     function callA()
     {
       $classA = new ClassA();
       $name = $classA->getName();
       echo $name;    //Prints John
     }
   }

   $classb = new ClassB();
   $classb->callA();
?>

how can the textbox width be reduced?

<input type='text' 
       name='t1'
       id='t1'
       maxlength=10
       placeholder='typing some text' >
<p></p>

This is the text box, it has a fixed length of 10 characters, and if you can try but this text box does not contain maximum length 10 character

How to use adb pull command?

I don't think adb pull handles wildcards for multiple files. I ran into the same problem and did this by moving the files to a folder and then pulling the folder.

I found a link doing the same thing. Try following these steps.

How to copy selected files from Android with adb pull

Renaming a branch in GitHub

Simple as that. In order to rename a Git branch locally and remotely use this snippet (tested and works like a charm):

git branch -m <oldBranchName> <newBranchName>
git push origin :<oldBranchName>
git push --set-upstream origin <newBranchName>

Explanation:

  1. Rename step:

Git reference: With a -m or -M option, <oldbranch> will be renamed to <newbranch>. If <oldbranch> had a corresponding reflog, it is renamed to match <newbranch>, and a reflog entry is created to remember the branch renaming. If <newbranch> exists, -M must be used to force the rename to happen.

  1. Delete step:

Git reference: git push origin :experimental Find a ref that matches experimental in the origin repository (e.g. refs/heads/experimental), and delete it.

  1. Update on remote repository step (upstream reference for tracking):

Git reference: --set-upstream For every branch that is up to date or successfully pushed, add upstream (tracking) reference, used by argument-less git-pull[1] and other commands. For more information, see branch.<name>.merge in git-config[1].

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

ListView with Add and Delete Buttons in each Row in android

public class UserCustomAdapter extends ArrayAdapter<User> {
 Context context;
 int layoutResourceId;
 ArrayList<User> data = new ArrayList<User>();

 public UserCustomAdapter(Context context, int layoutResourceId,
   ArrayList<User> data) {
  super(context, layoutResourceId, data);
  this.layoutResourceId = layoutResourceId;
  this.context = context;
  this.data = data;
 }

 @Override
 public View getView(int position, View convertView, ViewGroup parent) {
  View row = convertView;
  UserHolder holder = null;

  if (row == null) {
   LayoutInflater inflater = ((Activity) context).getLayoutInflater();
   row = inflater.inflate(layoutResourceId, parent, false);
   holder = new UserHolder();
   holder.textName = (TextView) row.findViewById(R.id.textView1);
   holder.textAddress = (TextView) row.findViewById(R.id.textView2);
   holder.textLocation = (TextView) row.findViewById(R.id.textView3);
   holder.btnEdit = (Button) row.findViewById(R.id.button1);
   holder.btnDelete = (Button) row.findViewById(R.id.button2);
   row.setTag(holder);
  } else {
   holder = (UserHolder) row.getTag();
  }
  User user = data.get(position);
  holder.textName.setText(user.getName());
  holder.textAddress.setText(user.getAddress());
  holder.textLocation.setText(user.getLocation());
  holder.btnEdit.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Edit Button Clicked", "**********");
    Toast.makeText(context, "Edit button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  holder.btnDelete.setOnClickListener(new OnClickListener() {

   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    Log.i("Delete Button Clicked", "**********");
    Toast.makeText(context, "Delete button Clicked",
      Toast.LENGTH_LONG).show();
   }
  });
  return row;

 }

 static class UserHolder {
  TextView textName;
  TextView textAddress;
  TextView textLocation;
  Button btnEdit;
  Button btnDelete;
 }
}

Hey Please have a look here-

I have same answer here on my blog ..

Using Jquery Datatable with AngularJs

Take a look at this: AngularJS+JQuery(datatable)

FULL code: http://jsfiddle.net/zdam/7kLFU/

JQuery Datatables's Documentation: http://www.datatables.net/

var dialogApp = angular.module('tableExample', []);

    dialogApp.directive('myTable', function() {
        return function(scope, element, attrs) {

            // apply DataTable options, use defaults if none specified by user
            var options = {};
            if (attrs.myTable.length > 0) {
                options = scope.$eval(attrs.myTable);
            } else {
                options = {
                    "bStateSave": true,
                    "iCookieDuration": 2419200, /* 1 month */
                    "bJQueryUI": true,
                    "bPaginate": false,
                    "bLengthChange": false,
                    "bFilter": false,
                    "bInfo": false,
                    "bDestroy": true
                };
            }

            // Tell the dataTables plugin what columns to use
            // We can either derive them from the dom, or use setup from the controller           
            var explicitColumns = [];
            element.find('th').each(function(index, elem) {
                explicitColumns.push($(elem).text());
            });
            if (explicitColumns.length > 0) {
                options["aoColumns"] = explicitColumns;
            } else if (attrs.aoColumns) {
                options["aoColumns"] = scope.$eval(attrs.aoColumns);
            }

            // aoColumnDefs is dataTables way of providing fine control over column config
            if (attrs.aoColumnDefs) {
                options["aoColumnDefs"] = scope.$eval(attrs.aoColumnDefs);
            }

            if (attrs.fnRowCallback) {
                options["fnRowCallback"] = scope.$eval(attrs.fnRowCallback);
            }

            // apply the plugin
            var dataTable = element.dataTable(options);



            // watch for any changes to our data, rebuild the DataTable
            scope.$watch(attrs.aaData, function(value) {
                var val = value || null;
                if (val) {
                    dataTable.fnClearTable();
                    dataTable.fnAddData(scope.$eval(attrs.aaData));
                }
            });
        };
    });

function Ctrl($scope) {

    $scope.message = '';            

        $scope.myCallback = function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {            
            $('td:eq(2)', nRow).bind('click', function() {
                $scope.$apply(function() {
                    $scope.someClickHandler(aData);
                });
            });
            return nRow;
        };

        $scope.someClickHandler = function(info) {
            $scope.message = 'clicked: '+ info.price;
        };

        $scope.columnDefs = [ 
            { "mDataProp": "category", "aTargets":[0]},
            { "mDataProp": "name", "aTargets":[1] },
            { "mDataProp": "price", "aTargets":[2] }
        ]; 

        $scope.overrideOptions = {
            "bStateSave": true,
            "iCookieDuration": 2419200, /* 1 month */
            "bJQueryUI": true,
            "bPaginate": true,
            "bLengthChange": false,
            "bFilter": true,
            "bInfo": true,
            "bDestroy": true
        };


        $scope.sampleProductCategories = [

              {
                "name": "1948 Porsche 356-A Roadster",
                "price": 53.9,
                  "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1948 Porsche Type 356 Roadster",
                "price": 62.16,
            "category": "Classic Cars",
                  "action":"x"
              },
              {
                "name": "1949 Jaguar XK 120",
                "price": 47.25,
            "category": "Classic Cars",
                  "action":"x"
              }
              ,
              {
                "name": "1936 Harley Davidson El Knucklehead",
                "price": 24.23,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1957 Vespa GS150",
                "price": 32.95,
            "category": "Motorcycles",
                  "action":"x"
              },
              {
                "name": "1960 BSA Gold Star DBD34",
                "price": 37.32,
            "category": "Motorcycles",
                  "action":"x"
              }
           ,
              {
                "name": "1900s Vintage Bi-Plane",
                "price": 34.25,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1900s Vintage Tri-Plane",
                "price": 36.23,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1928 British Royal Navy Airplane",
                "price": 66.74,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "1980s Black Hawk Helicopter",
                "price": 77.27,
            "category": "Planes",
                  "action":"x"
              },
              {
                "name": "ATA: B757-300",
                "price": 59.33,
            "category": "Planes",
                  "action":"x"
              }

        ];            

}

Attach a file from MemoryStream to a MailMessage in C#

A bit of a late entry - but hopefully still useful to someone out there:-

Here's a simplified snippet for sending an in-memory string as an email attachment (a CSV file in this particular case).

using (var stream = new MemoryStream())
using (var writer = new StreamWriter(stream))    // using UTF-8 encoding by default
using (var mailClient = new SmtpClient("localhost", 25))
using (var message = new MailMessage("[email protected]", "[email protected]", "Just testing", "See attachment..."))
{
    writer.WriteLine("Comma,Seperated,Values,...");
    writer.Flush();
    stream.Position = 0;     // read from the start of what was written

    message.Attachments.Add(new Attachment(stream, "filename.csv", "text/csv"));

    mailClient.Send(message);
}

The StreamWriter and underlying stream should not be disposed until after the message has been sent (to avoid ObjectDisposedException: Cannot access a closed Stream).

How to print all session variables currently set?

Echo the session object as json. I like json because I have a browser extension that nicely formats json.

session_start();
echo json_encode($_SESSION);

How to get the system uptime in Windows?

Following are eight ways to find the Uptime in Windows OS.

1: By using the Task Manager

In Windows Vista and Windows Server 2008, the Task Manager has been beefed up to show additional information about the system. One of these pieces of info is the server’s running time.

  1. Right-click on the Taskbar, and click Task Manager. You can also click CTRL+SHIFT+ESC to get to the Task Manager.
  2. In Task Manager, select the Performance tab.
  3. The current system uptime is shown under System or Performance ⇒ CPU for Win 8/10.

    "Up Time" field in Task Manager

2: By using the System Information Utility

The systeminfo command line utility checks and displays various system statistics such as installation date, installed hotfixes and more. Open a Command Prompt and type the following command:

systeminfo

You can also narrow down the results to just the line you need:

systeminfo | find "System Boot Time:"

enter image description here

3: By using the Uptime Utility

Microsoft have published a tool called Uptime.exe. It is a simple command line tool that analyses the computer's reliability and availability information. It can work locally or remotely. In its simple form, the tool will display the current system uptime. An advanced option allows you to access more detailed information such as shutdown, reboots, operating system crashes, and Service Pack installation.

Read the following KB for more info and for the download links:

To use it, follow these steps:

  1. Download uptime.exe from the above link, and save it to a folder, preferably in one that's in the system's path (such as SYSTEM32).
  2. Open an elevated Command Prompt window. To open an elevated Command Prompt, click Start, click All Programs, click Accessories, right-click Command Prompt, and then click Run as administrator. You can also type CMD in the search box of the Start menu, and when you see the Command Prompt icon click on it to select it, hold CTRL+SHIFT and press ENTER.
  3. Navigate to where you've placed the uptime.exe utility.
  4. Run the uptime.exe utility. You can add a /? to the command in order to get more options. enter image description here

It does not offer many command line parameters:

C:\uptimefromcodeplex\> uptime /?
usage: Uptime [-V]
    -V   display version

C:\uptimefromcodeplex\> uptime -V
version 1.1.0

3.1: By using the old Uptime Utility

There is an older version of the "uptime.exe" utility. This has the advantage of NOT needing .NET. (It also has a lot more features beyond simple uptime.)

Download link: Windows NT 4.0 Server Uptime Tool (uptime.exe) (final x86)

C:\uptimev100download>uptime.exe /?

UPTIME, Version 1.00
(C) Copyright 1999, Microsoft Corporation

Uptime [server] [/s ] [/a] [/d:mm/dd/yyyy | /p:n] [/heartbeat] [/? | /help]
        server          Name or IP address of remote server to process.
        /s              Display key system events and statistics.
        /a              Display application failure events (assumes /s).
        /d:             Only calculate for events after mm/dd/yyyy.
        /p:             Only calculate for events in the previous n days.
        /heartbeat      Turn on/off the system's heartbeat
        /?              Basic usage.
        /help           Additional usage information.

4: By using the NET STATISTICS Utility

Another easy method, if you can remember it, is to use the approximate information found in the statistics displayed by the NET STATISTICS command. Open a Command Prompt and type the following command:

net statistics workstation

The statistics should tell you how long it’s been running, although in some cases this information is not as accurate as other methods.

enter image description here

5: By Using the Event Viewer

Probably the most accurate of them all, but it does require some clicking. It does not display an exact day or hour count since the last reboot, but it will display important information regarding why the computer was rebooted and when it did so. We need to look at Event ID 6005, which is an event that tells us that the computer has just finished booting, but you should be aware of the fact that there are virtually hundreds if not thousands of other event types that you could potentially learn from.

Note: BTW, the 6006 Event ID is what tells us when the server has gone down, so if there’s much time difference between the 6006 and 6005 events, the server was down for a long time.

Note: You can also open the Event Viewer by typing eventvwr.msc in the Run command, and you might as well use the shortcut found in the Administrative tools folder.

  1. Click on Event Viewer (Local) in the left navigation pane.
  2. In the middle pane, click on the Information event type, and scroll down till you see Event ID 6005. Double-click the 6005 Event ID, or right-click it and select View All Instances of This Event.
  3. A list of all instances of the 6005 Event ID will be displayed. You can examine this list, look at the dates and times of each reboot event, and so on.
  4. Open Server Manager tool by right-clicking the Computer icon on the start menu (or on the Desktop if you have it enabled) and select Manage. Navigate to the Event Viewer.

enter image description here

5.1: Eventlog via PowerShell

Get-WinEvent -ProviderName eventlog | Where-Object {$_.Id -eq 6005 -or $_.Id -eq 6006}

6: Programmatically, by using GetTickCount64

GetTickCount64 retrieves the number of milliseconds that have elapsed since the system was started.

7: By using WMI

wmic os get lastbootuptime

8: The new uptime.exe for Windows XP and up

Like the tool from Microsoft, but compatible with all operating systems up to and including Windows 10 and Windows Server 2016, this uptime utility does not require an elevated command prompt and offers an option to show the uptime in both DD:HH:MM:SS and in human-readable formats (when executed with the -h command-line parameter).

Additionally, this version of uptime.exe will run and show the system uptime even when launched normally from within an explorer.exe session (i.e. not via the command line) and pause for the uptime to be read:

enter image description here

and when executed as uptime -h:

enter image description here

How can I replace the deprecated set_magic_quotes_runtime in php?

Check if it's on first. That should get rid of the warning and it'll ensure that if your code is run on older versions of PHP that magic quotes are indeed off.

Don't just remove that line of code as suggested by others unless you can be 100% sure that the code will never be run on anything before PHP 5.3.

<?php
// Check if magic_quotes_runtime is active
if(get_magic_quotes_runtime())
{
    // Deactivate
    set_magic_quotes_runtime(false);
}
?>

get_magic_quotes_runtime is NOT deprecated in PHP 5.3.
Source: http://us2.php.net/get_magic_quotes_runtime/

How to prevent a click on a '#' link from jumping to top of page?

You can use #0 as href, since 0 isn't allowed as an id, the page won't jump.

<a href="#0" class="someclass">Text</a>

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

This error might occur when you return an object instead of a string in your __unicode__ method. For example:

class Author(models.Model):
    . . . 
    name = models.CharField(...)


class Book(models.Model):
    . . .
    author = models.ForeignKey(Author, ...)
    . . .
    def __unicode__(self):
        return self.author  # <<<<<<<< this causes problems

To avoid this error you can cast the author instance to unicode:

class Book(models.Model):
    . . . 
    def __unicode__(self):
        return unicode(self.author)  # <<<<<<<< this is OK

Undefined behavior and sequence points

C++17 (N4659) includes a proposal Refining Expression Evaluation Order for Idiomatic C++ which defines a stricter order of expression evaluation.

In particular, the following sentence

8.18 Assignment and compound assignment operators:
....

In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression. The right operand is sequenced before the left operand.

together with the following clarification

An expression X is said to be sequenced before an expression Y if every value computation and every side effect associated with the expression X is sequenced before every value computation and every side effect associated with the expression Y.

make several cases of previously undefined behavior valid, including the one in question:

a[++i] = i;

However several other similar cases still lead to undefined behavior.

In N4140:

i = i++ + 1; // the behavior is undefined

But in N4659

i = i++ + 1; // the value of i is incremented
i = i++ + i; // the behavior is undefined

Of course, using a C++17 compliant compiler does not necessarily mean that one should start writing such expressions.

Using multiple delimiters in awk

If your whitespace is consistent you could use that as a delimiter, also instead of inserting \t directly, you could set the output separator and it will be included automatically:

< file awk -v OFS='\t' -v FS='[/ ]' '{print $3, $5, $NF}'

Converting a float to a string without rounding it

len(repr(float(x)/3))

However I must say that this isn't as reliable as you think.

Floats are entered/displayed as decimal numbers, but your computer (in fact, your standard C library) stores them as binary. You get some side effects from this transition:

>>> print len(repr(0.1))
19
>>> print repr(0.1)
0.10000000000000001

The explanation on why this happens is in this chapter of the python tutorial.

A solution would be to use a type that specifically tracks decimal numbers, like python's decimal.Decimal:

>>> print len(str(decimal.Decimal('0.1')))
3

How can I test an AngularJS service from the console?

Angularjs Dependency Injection framework is responsible for injecting the dependancies of you app module to your controllers. This is possible through its injector.

You need to first identify the ng-app and get the associated injector. The below query works to find your ng-app in the DOM and retrieve the injector.

angular.element('*[ng-app]').injector()

In chrome, however, you can point to target ng-app as shown below. and use the $0 hack and issue angular.element($0).injector()

Once you have the injector, get any dependency injected service as below

injector = angular.element($0).injector();
injector.get('$mdToast');

enter image description here

Can anyone explain what JSONP is, in layman terms?

JSONP is a way of getting around the browser's same-origin policy. How? Like this:

enter image description here

The goal here is to make a request to otherdomain.com and alert the name in the response. Normally we'd make an AJAX request:

$.get('otherdomain.com', function (response) {
  var name = response.name;
  alert(name);
});

However, since the request is going out to a different domain, it won't work.

We can make the request using a <script> tag though. Both <script src="otherdomain.com"></script> and $.get('otherdomain.com') will result in the same request being made:

GET otherdomain.com

Q: But if we use the <script> tag, how could we access the response? We need to access it if we want to alert it.

A: Uh, we can't. But here's what we could do - define a function that uses the response, and then tell the server to respond with JavaScript that calls our function with the response as its argument.

Q: But what if the server won't do this for us, and is only willing to return JSON to us?

A: Then we won't be able to use it. JSONP requires the server to cooperate.

Q: Having to use a <script> tag is ugly.

A: Libraries like jQuery make it nicer. Ex:

$.ajax({
    url: "http://otherdomain.com",
    jsonp: "callback",
    dataType: "jsonp",
    success: function( response ) {
        console.log( response );
    }
});

It works by dynamically creating the <script> tag DOM element.

Q: <script> tags only make GET requests - what if we want to make a POST request?

A: Then JSONP won't work for us.

Q: That's ok, I just want to make a GET request. JSONP is awesome and I'm going to go use it - thanks!

A: Actually, it isn't that awesome. It's really just a hack. And it isn't the safest thing to use. Now that CORS is available, you should use it whenever possible.

Ruby Hash to array of values

There is also this one:

hash = { foo: "bar", baz: "qux" }
hash.map(&:last) #=> ["bar", "qux"]

Why it works:

The & calls to_proc on the object, and passes it as a block to the method.

something {|i| i.foo }
something(&:foo)

How to set TLS version on apache HttpClient

The solution is:

SSLContext sslContext = SSLContexts.custom()
    .useTLS()
    .build();

SSLConnectionSocketFactory f = new SSLConnectionSocketFactory(
    sslContext,
    new String[]{"TLSv1", "TLSv1.1"},   
    null,
    BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);

httpClient = HttpClients.custom()
    .setSSLSocketFactory(f)
    .build();

This requires org.apache.httpcomponents.httpclient 4.3.x though.

Extension exists but uuid_generate_v4 fails

if you do it from unix command (apart from PGAdmin) dont forget to pass the DB as a parameter. otherwise this extension will not be enabled when executing requests on this DB

psql -d -c "create EXTENSION pgcrypto;"

Selecting between two dates within a DateTime field - SQL Server

select * 
from blah 
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'

Depending on the country setting for the login, the month/day may need to be swapped around.

How do I get the difference between two Dates in JavaScript?

<html>
<head>
<script>
function dayDiff()
{
     var start = document.getElementById("datepicker").value;
     var end= document.getElementById("date_picker").value;
     var oneDay = 24*60*60*1000; 
     var firstDate = new Date(start);
     var secondDate = new Date(end);    
     var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
    document.getElementById("leave").value =diffDays ;
 }
</script>
</head>
<body>
<input type="text" name="datepicker"value=""/>
<input type="text" name="date_picker" onclick="function dayDiff()" value=""/>
<input type="text" name="leave" value=""/>
</body>
</html>

Node Sass couldn't find a binding for your current environment

I am able to fix issue with npm install --global --production windows-build-tools

npm install --msvs_version=2015

"devDependencies": { "babel-core": "^6.26.0", "babel-loader": "^7.1.4", "babel-plugin-transform-decorators-legacy": "^1.3.5", "babel-preset-env": "^1.6.1", "babel-preset-react": "^6.24.1", "babel-preset-stage-2": "^6.24.1", "css-loader": "^0.28.11", "mini-css-extract-plugin": "^0.4.0", "node-sass": "^4.11.0", "sass-loader": "^6.0.7", "webpack": "^4.4.1", "webpack-cli": "3.1.0", "webpack-dev-server": "^3.1.1" }

Instagram: Share photo from webpage

The short answer is: No. The only way to post images is through the mobile app.

From the Instagram API documentation: http://instagram.com/developer/endpoints/media/

At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:

  • Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
  • We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.

All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.

How to implement a binary search tree in Python?

Just something to help you to start on.

A (simple idea of) binary tree search would be quite likely be implement in python according the lines:

def search(node, key):
    if node is None: return None  # key not found
    if key< node.key: return search(node.left, key)
    elif key> node.key: return search(node.right, key)
    else: return node.value  # found key

Now you just need to implement the scaffolding (tree creation and value inserts) and you are done.

How to view the dependency tree of a given npm module?

If you want to get the actually dependency path of specific package and want to know why you have it, you can simply ask yarn why <MODULE>. example:

    $> yarn why mime-db
    yarn why v1.5.1
    [1/4] Why do we have the module "mime-db"...?
    [2/4] Initialising dependency graph...
    [3/4] Finding dependency...
    [4/4] Calculating file sizes...
    => Found "[email protected]"
    info Reasons this module exists
       - "coveralls#request#mime-types" depends on it
       - Hoisted from "coveralls#request#mime-types#mime-db"
    info Disk size without dependencies: "196kB"
    info Disk size with unique dependencies: "196kB"
    info Disk size with transitive dependencies: "196kB"
    info Number of shared dependencies: 0
    Done in 0.65s.

Postgresql: error "must be owner of relation" when changing a owner object

From the fine manual.

You must own the table to use ALTER TABLE.

Or be a database superuser.

ERROR: must be owner of relation contact

PostgreSQL error messages are usually spot on. This one is spot on.

HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))

This could also be an issue of building the code using a 64 bit configuration. You can try to select x86 as the build platform which can solve this issue. To do this right-click the solution and select Configuration Manager From there you can change the Platform of the project using the 32-bit .dll to x86

How to know which version of Symfony I have?

Use the following command in your Terminal/Command Prompt:

php bin/console --version

This will give you your Symfony Version.

How can I match on an attribute that contains a certain string?

Be aware that bobince's answer might be overly complicated if you can assume that the class name you are interested in is not a substring of another possible class name. If this is true, you can simply use substring matching via the contains function. The following will match any element whose class contains the substring 'atag':

//*[contains(@class,'atag')]

If the assumption above does not hold, a substring match will match elements you don't intend. In this case, you have to find the word boundaries. By using the space delimiters to find the class name boundaries, bobince's second answer finds the exact matches:

//*[contains(concat(' ', normalize-space(@class), ' '), ' atag ')]

This will match atag and not matag.

Reload activity in Android

After experimenting with this for a while I've found no unexpected consequences of restarting an activity. Also, I believe this is very similar to what Android does by default when the orientation changes, so I don't see a reason not to do it in a similar circumstance.

React.js: How to append a component on click?

Don't use jQuery to manipulate the DOM when you're using React. React components should render a representation of what they should look like given a certain state; what DOM that translates to is taken care of by React itself.

What you want to do is store the "state which determines what gets rendered" higher up the chain, and pass it down. If you are rendering n children, that state should be "owned" by whatever contains your component. eg:

class AppComponent extends React.Component {
  state = {
    numChildren: 0
  }

  render () {
    const children = [];

    for (var i = 0; i < this.state.numChildren; i += 1) {
      children.push(<ChildComponent key={i} number={i} />);
    };

    return (
      <ParentComponent addChild={this.onAddChild}>
        {children}
      </ParentComponent>
    );
  }

  onAddChild = () => {
    this.setState({
      numChildren: this.state.numChildren + 1
    });
  }
}

const ParentComponent = props => (
  <div className="card calculator">
    <p><a href="#" onClick={props.addChild}>Add Another Child Component</a></p>
    <div id="children-pane">
      {props.children}
    </div>
  </div>
);

const ChildComponent = props => <div>{"I am child " + props.number}</div>;

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

Enabling the legacy from app.config didn't work for me. For unknown reasons, my application wasn't activating V2 runtime policy. I found a work around here.

Enabling the legacy from app.config is a recommended approach but in some cases it doesn't work as expected. Use the following code with in your main application to force Legacy V2 policy:

public static class RuntimePolicyHelper
{
public static bool LegacyV2RuntimeEnabledSuccessfully { get; private set; }

static RuntimePolicyHelper()
{
    ICLRRuntimeInfo clrRuntimeInfo =
        (ICLRRuntimeInfo)RuntimeEnvironment.GetRuntimeInterfaceAsObject(
            Guid.Empty, 
            typeof(ICLRRuntimeInfo).GUID);
    try
    {
        clrRuntimeInfo.BindAsLegacyV2Runtime();
        LegacyV2RuntimeEnabledSuccessfully = true;
    }
    catch (COMException)
    {
        // This occurs with an HRESULT meaning 
        // "A different runtime was already bound to the legacy CLR version 2 activation policy."
        LegacyV2RuntimeEnabledSuccessfully = false;
    }
}

[ComImport]
[InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
[Guid("BD39D1D2-BA2F-486A-89B0-B4B0CB466891")]
private interface ICLRRuntimeInfo
{
    void xGetVersionString();
    void xGetRuntimeDirectory();
    void xIsLoaded();
    void xIsLoadable();
    void xLoadErrorString();
    void xLoadLibrary();
    void xGetProcAddress();
    void xGetInterface();
    void xSetDefaultStartupFlags();
    void xGetDefaultStartupFlags();

    [MethodImpl(MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime)]
    void BindAsLegacyV2Runtime();
}
}

Doctrine and LIKE query

This is not possible with the magic find methods. Try using the query builder:

$result = $em->getRepository("Orders")->createQueryBuilder('o')
   ->where('o.OrderEmail = :email')
   ->andWhere('o.Product LIKE :product')
   ->setParameter('email', '[email protected]')
   ->setParameter('product', 'My Products%')
   ->getQuery()
   ->getResult();

Image encryption/decryption using AES256 symmetric block ciphers

Old question but I upgrade the answers supporting Android prior and post 4.2 and considering all recent changes according to Android developers blog

Plus I leave a working example on my github repo.

import java.nio.charset.Charset;
import java.security.AlgorithmParameters;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;


/*
* This software is provided 'as-is', without any express or implied
* warranty.  In no event will Google be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, as long as the origin is not misrepresented.
* 
* @author: Ricardo Champa
* 
*/

public class MyCipher {

    private final static String ALGORITHM = "AES";
    private String mySecret;

    public MyCipher(String mySecret){
        this.mySecret = mySecret;
    }

    public MyCipherData encryptUTF8(String data){
        try{
            byte[] bytes = data.toString().getBytes("utf-8");
            byte[] bytesBase64 = Base64.encodeBase64(bytes);
            return encrypt(bytesBase64);
        }
        catch(Exception e){
            MyLogs.show(e.getMessage());
            return null;
        }

    }

    public String decryptUTF8(byte[] encryptedData, IvParameterSpec iv){
        try {
            byte[] decryptedData = decrypt(encryptedData, iv);
            byte[] decodedBytes = Base64.decodeBase64(decryptedData);
            String restored_data = new String(decodedBytes, Charset.forName("UTF8"));
            return restored_data;
        } catch (Exception e) {
            MyLogs.show(e.getMessage());;
            return null;
        }
    }

    //AES
    private MyCipherData encrypt(byte[] raw, byte[] clear) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //solved using PRNGFixes class
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
        byte[] data = cipher.doFinal(clear);

        AlgorithmParameters params = cipher.getParameters();
        byte[] iv = params.getParameterSpec(IvParameterSpec.class).getIV();
        return new MyCipherData(data, iv);
    }

    private byte[] decrypt(byte[] raw, byte[] encrypted, IvParameterSpec iv) throws Exception {
        SecretKeySpec skeySpec = new SecretKeySpec(raw, ALGORITHM);
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);
        byte[] decrypted = cipher.doFinal(encrypted);
        return decrypted;
    }

    private byte[] getKey() throws Exception{
        byte[] keyStart = this.mySecret.getBytes("utf-8");
        KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);

        SecureRandom sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        //      if (android.os.Build.VERSION.SDK_INT >= 17) {
        //          sr = SecureRandom.getInstance("SHA1PRNG", "Crypto");
        //      } else {
        //          sr = SecureRandom.getInstance("SHA1PRNG");
        //      }
        sr.setSeed(keyStart);
        kgen.init(128, sr); // 192 and 256 bits may not be available
        SecretKey skey = kgen.generateKey();
        byte[] key = skey.getEncoded();
        return key;

    }
    ////////////////////////////////////////////////////////////
    private MyCipherData encrypt(byte[] data) throws Exception{
        return encrypt(getKey(),data);
    }
    private byte[] decrypt(byte[] encryptedData, IvParameterSpec iv) throws Exception{
        return decrypt(getKey(),encryptedData, iv);
    }
}

Visual Studio SignTool.exe Not Found

Here is a solution for Visual Studio 2017. The installer looks a littlebit different from the VS 2015 version and the name of the installation packages are different.

Convert a timedelta to days, hours and minutes

timedeltas have a days and seconds attribute .. you can convert them yourself with ease.

Getting the current date in visual Basic 2008

Dim regDate As Date = Date.Now.date

This should fix your problem, though it's 2 years old!

MySQL select statement with CASE or IF ELSEIF? Not sure how to get the result

Syntax:

CASE value WHEN [compare_value] THEN result 
[WHEN [compare_value] THEN result ...] 
[ELSE result] 
END

Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]

mysql> SELECT CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END; 
+-------------------------------------------------------------+
| CASE  WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false                                               | 
+-------------------------------------------------------------+

I am use:

SELECT  act.*,
    CASE 
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
        WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
        WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
    END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND  lises.session_date >= now()
LEFT JOIN session AS ses ON  ses.activity_id = act.id AND  ses.session_date >= now()
WHERE act.id

How to select all and copy in vim?

In normal mode:

gg"+yG

In ex mode:

:%y+

Regular vs Context Free Grammars

Basically regular grammar is a subset of context free grammar,but we can not say Every Context free grammar is a regular grammar. Mainly context free grammar is ambiguous and regular grammar may be ambiguous.

How to get the current loop index when using Iterator?

Use your own variable and increment it in the loop.

decompiling DEX into Java sourcecode

Sometimes you get broken code, when using dex2jar/apktool, most notably in loops. To avoid this, use jadx, which decompiles dalvik bytecode into java source code, without creating a .jar/.class file first as dex2jar does (apktool uses dex2jar I think). It is also open-source and in active development. It even has a GUI, for GUI-fanatics. Try it!

How to grab substring before a specified character jQuery or JavaScript

var newString = string.substr(0,string.indexOf(','));

"if not exist" command in batch file

When testing for directories remember that every directory contains two special files.

One is called '.' and the other '..'

. is the directory's own name while .. is the name of it's parent directory.

To avoid trailing backslash problems just test to see if the directory knows it's own name.

eg:

if not exist %temp%\buffer\. mkdir %temp%\buffer

Using the Jersey client to do a POST operation

Simplest:

Form form = new Form();
form.add("id", "1");    
form.add("name", "supercobra");
ClientResponse response = webResource
  .type(MediaType.APPLICATION_FORM_URLENCODED_TYPE)
  .post(ClientResponse.class, form);

how to set the background image fit to browser using html

HTML

<img src="images/bg.jpg" id="bg" alt="">

CSS

#bg {
  position: fixed; 
  top: 0; 
  left: 0; 

  /* Preserve aspet ratio */
  min-width: 100%;
  min-height: 100%;
}

Setting timezone to UTC (0) in PHP

You can always check this maintained list to timezones

https://www.php.net/manual/en/function.date.php

How to run python script on terminal (ubuntu)?

Set the PATH as below:


In the csh shell - type setenv PATH "$PATH:/usr/local/bin/python" and press Enter.

In the bash shell (Linux) - type export PATH="$PATH:/usr/local/bin/python" and press Enter.

In the sh or ksh shell - type PATH="$PATH:/usr/local/bin/python" and press Enter.

Note - /usr/local/bin/python is the path of the Python directory


now run as below:

-bash-4.2$ python test.py

Hello, Python!

How to find nth occurrence of character in a string?

 ([.^/]*/){2}[^/]*(/)

Match anything followed by / two times, then again. The third one is the one you want

The Matcher state can be used to tell where the last / is

Simple Pivot Table to Count Unique Values

I found the easiest approach is to use the Distinct Count option under Value Field Settings (left click the field in the Values pane). The option for Distinct Count is at the very bottom of the list.

Location of where to click

Here are the before (TOP; normal Count) and after (BOTTOM; Distinct Count)

COUNT

DISTINCT COUNT

How to convert date into this 'yyyy-MM-dd' format in angular 2

I would suggest you to have a look into Moment.js if you have trouble with Angular. At least it is a quick workaround without spending too much time.

How to send POST request in JSON using HTTPClient in Android?

Too much code for this task, checkout this library https://github.com/kodart/Httpzoid Is uses GSON internally and provides API that works with objects. All JSON details are hidden.

Http http = HttpFactory.create(context);
http.get("http://example.com/users")
    .handler(new ResponseHandler<User[]>() {
        @Override
        public void success(User[] users, HttpResponse response) {
        }
    }).execute();

How to compare 2 dataTables

Try to make use of linq to Dataset

(from b in table1.AsEnumerable()  
    select new { id = b.Field<int>("id")}).Except(
         from a in table2.AsEnumerable() 
             select new {id = a.Field<int>("id")})

Check this article : Comparing DataSets using LINQ

Lumen: get URL parameter in a Blade view

As per official documentation 8.x

We use the helper request

The request function returns the current request instance or obtains an input field's value from the current request:

$request = request();

$value = request('key', $default);

the value of request is an array you can simply retrieve your input using the input key as follow

$id = request()->id; //for http://locahost:8000/example?id=10

How can I change the image of an ImageView?

Just to go a little bit further in the matter, you can also set a bitmap directly, like this:

ImageView imageView = new ImageView(this);  
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);

Of course, this technique is only useful if you need to change the image.

How can I make a jQuery UI 'draggable()' div draggable for touchscreen?

You can try using jquery.pep.js:

jquery.pep.js is a lightweight jQuery plugin which turns any DOM element into a draggable object. It works across mostly all browsers, from old to new, from touch to click. I built it to serve a need in which jQuery UI’s draggable was not fulfilling, since it didn’t work on touch devices (without some hackery).

Website, GitHub link

How to increment a datetime by one day?

Here is another method to add days on date using dateutil's relativedelta.

from datetime import datetime
from dateutil.relativedelta import relativedelta

print 'Today: ',datetime.now().strftime('%d/%m/%Y %H:%M:%S') 
date_after_month = datetime.now()+ relativedelta(day=1)
print 'After a Days:', date_after_month.strftime('%d/%m/%Y %H:%M:%S')

Output:

Today: 25/06/2015 20:41:44

After a Days: 01/06/2015 20:41:44

how to call a function from another function in Jquery

I think in this case you want something like this:

$(window).resize(resize=function resize(){ some code...}

Now u can call resize() within some other nested functions:

$(window).scroll(function(){ resize();}

Setting PHPMyAdmin Language

In config.inc.php in the top-level directory, set

$cfg['DefaultLang'] = 'en-utf-8'; // Language if no other language is recognized
// or
$cfg['Lang'] = 'en-utf-8'; // Force this language for all users

If Lang isn't set, you should be able to select the language in the initial welcome screen, and the language your browser prefers should be preselected there.

Efficient way to rotate a list in python

I don't know if this is 'efficient', but it also works:

x = [1,2,3,4]
x.insert(0,x.pop())

EDIT: Hello again, I just found a big problem with this solution! Consider the following code:

class MyClass():
    def __init__(self):
        self.classlist = []

    def shift_classlist(self): # right-shift-operation
        self.classlist.insert(0, self.classlist.pop())

if __name__ == '__main__':
    otherlist = [1,2,3]
    x = MyClass()

    # this is where kind of a magic link is created...
    x.classlist = otherlist

    for ii in xrange(2): # just to do it 2 times
        print '\n\n\nbefore shift:'
        print '     x.classlist =', x.classlist
        print '     otherlist =', otherlist
        x.shift_classlist() 
        print 'after shift:'
        print '     x.classlist =', x.classlist
        print '     otherlist =', otherlist, '<-- SHOULD NOT HAVE BIN CHANGED!'

The shift_classlist() method executes the same code as my x.insert(0,x.pop())-solution, otherlist is a list indipendent from the class. After passing the content of otherlist to the MyClass.classlist list, calling the shift_classlist() also changes the otherlist list:

CONSOLE OUTPUT:

before shift:
     x.classlist = [1, 2, 3]
     otherlist = [1, 2, 3]
after shift:
     x.classlist = [3, 1, 2]
     otherlist = [3, 1, 2] <-- SHOULD NOT HAVE BIN CHANGED!



before shift:
     x.classlist = [3, 1, 2]
     otherlist = [3, 1, 2]
after shift:
     x.classlist = [2, 3, 1]
     otherlist = [2, 3, 1] <-- SHOULD NOT HAVE BIN CHANGED!

I use Python 2.7. I don't know if thats a bug, but I think it's more likely that I missunderstood something here.

Does anyone of you know why this happens?

Android WebView, how to handle redirects in app instead of opening a browser

You will have to set your custom WebviewClient overriding shouldOverrideUrlLoading method for your webview before loading the url.

mWebView.setWebViewClient(new WebViewClient()
        {
            @SuppressWarnings("deprecation")
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url)
            {
                return shouldOverrideUrlLoading(url);
            }

            @TargetApi(Build.VERSION_CODES.N)
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
            {
                Uri uri = request.getUrl();
                return shouldOverrideUrlLoading(uri.toString());
            }

            private boolean shouldOverrideUrlLoading(final String url)
            {
                Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);

                // Here put your code

                return true; // Returning True means that application wants to leave the current WebView and handle the url itself, otherwise return false.
            }
        });

Checkout the example code for handling redirect urls and open PDF without download, in webview. https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500

PHP Warning: PHP Startup: Unable to load dynamic library

I had the same problem on XAMPP for Windows10 when I try to install composer.

Unable to load dynamic library '/xampp/php/ext/php_bz2.dll'

Then follow this steps

  1. just open your current_xampp_containing_drive:\xampp(default_xampp_folder)\php\php.ini in texteditor (like notepad++)
  2. now just find - is the current_xampp_containing_drive:\xampp exist?
  3. if not then find the "extension_dir" and get the drive name(c,d or your desired drive) like.

extension_dir="F:\xampp731\php\ext" (here finded_drive_name_from_the_file is F)

  1. again replace with finded_drive_name_from_the_file:\xampp with current_xampp_containing_drive:\xampp and save.
  2. now again start the composer installation progress, i think your problem will be solved.

Best way to store password in database

As a key-hardened salted hash, using a secure algorithm such as sha-512.

What are the differences between Deferred, Promise and Future in JavaScript?

  • A promise represents a value that is not yet known
  • A deferred represents work that is not yet finished

A promise is a placeholder for a result which is initially unknown while a deferred represents the computation that results in the value.

Reference

Hot deploy on JBoss - how do I make JBoss "see" the change?

I had the same problem in my bundle: (Eclipse IDE + JBoss server adapter) + JBoss AS 7.0.1 (community project).

My solution is very simple - you should go to JBoss administrative panel (by default localhost:9990), there in profile settings open Core - Deployment Scanners. Turn on Autodeploy-Exploded (set to true), and by your wishes you can set scanner time (by default 5000 ms) to appropriate for your (I set to 2000, for more fast incremental publish in Eclipse when I make changes to projects). That's it. Now JBoss makes HOT deploy not only for HTML (JSF, XHTML and so on) files, but also takes care of POJO classes (beans and so on) files.

Warn user before leaving web page with unsaved changes

You can use serialize() to create a URL encoded text string by serializing form values and check whether the form has changed beforeunload

$(document).ready(function(){
    var form = $('#some-form'),
        original = form.serialize()

    form.submit(function(){
        window.onbeforeunload = null
    })

    window.onbeforeunload = function(){
        if (form.serialize() != original)
            return 'Are you sure you want to leave?'
    }
})

Refer this link https://coderwall.com/p/gny70a/alert-when-leaving-page-with-unsaved-form Written by Vladimir Sidorenko

Find the PID of a process that uses a port on Windows

Command:

netstat -aon | findstr 4723

Output:

TCP    0.0.0.0:4723           0.0.0.0:0                LISTENING       10396

Now cut the process ID, "10396", using the for command in Windows.

Command:

for /f "tokens=5" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

10396

If you want to cut the 4th number of the value means "LISTENING" then command in Windows.

Command:

for /f "tokens=4" %a in ('netstat -aon ^| findstr 4723') do @echo %~nxa

Output:

LISTENING

How to find indices of all occurrences of one string in another in JavaScript?

I am a bit late to the party (by almost 10 years, 2 months), but one way for future coders is to do it using while loop and indexOf()

let haystack = "I learned to play the Ukulele in Lebanon.";
let needle = "le";
let pos = 0; // Position Ref
let result = []; // Final output of all index's.
let hayStackLower = haystack.toLowerCase();

// Loop to check all occurrences 
while (hayStackLower.indexOf(needle, pos) != -1) {
  result.push(hayStackLower.indexOf(needle , pos));
  pos = hayStackLower.indexOf(needle , pos) + 1;
}

console.log("Final ", result); // Returns all indexes or empty array if not found

Using TortoiseSVN via the command line

After some time, I used this workaround...

(at the .bat file)

SET "CHECKOUT=http://yoururl.url";
SET "PATH=your_folder_path"

start "C:\Program Files\TortoiseSVN\bin" svn.exe checkout %CHECKOUT% %PATH%

Java: Clear the console

This will work if you are doing this in Bluej or any other similar software.

System.out.print('\u000C');

How To Accept a File POST

I'm surprised that a lot of you seem to want to save files on the server. Solution to keep everything in memory is as follows:

[HttpPost("api/upload")]
public async Task<IHttpActionResult> Upload()
{
    if (!Request.Content.IsMimeMultipartContent())
        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); 

    var provider = new MultipartMemoryStreamProvider();
    await Request.Content.ReadAsMultipartAsync(provider);
    foreach (var file in provider.Contents)
    {
        var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
        var buffer = await file.ReadAsByteArrayAsync();
        //Do whatever you want with filename and its binary data.
    }

    return Ok();
}

node.js - how to write an array to file

A simple solution is to use writeFile :

require("fs").writeFile(
     somepath,
     arr.map(function(v){ return v.join(', ') }).join('\n'),
     function (err) { console.log(err ? 'Error :'+err : 'ok') }
);

Dealing with HTTP content in HTTPS pages

Your worst case scenario isn't as bad as you think.

You are already parsing the RSS feed, so you already have the image URLs. Say you have an image URL like http://otherdomain.com/someimage.jpg. You rewrite this URL as https://mydomain.com/imageserver?url=http://otherdomain.com/someimage.jpg&hash=abcdeafad. This way, the browser always makes request over https, so you get rid of the problems.

The next part - create a proxy page or servlet that does the following -

  1. Read the url parameter from the query string, and verify the hash
  2. Download the image from the server, and proxy it back to the browser
  3. Optionally, cache the image on disk

This solution has some advantages. You don't have to download the image at the time of creating the html. You don't have to store the images locally. Also, you are stateless; the url contains all the information necessary to serve the image.

Finally, the hash parameter is for security; you only want your servlet to serve images for urls you have constructed. So, when you create the url, compute md5(image_url + secret_key) and append it as the hash parameter. Before you serve the request, recompute the hash and compare it to what was passed to you. Since the secret_key is only known to you, nobody else can construct valid urls.

If you are developing in java, the Servlet is just a few lines of code. You should be able to port the code below on any other back-end technology.

/*
targetURL is the url you get from RSS feeds
request and response are wrt to the browser
Assumes you have commons-io in your classpath
*/

protected void proxyResponse (String targetURL, HttpServletRequest request,
 HttpServletResponse response) throws IOException {
    GetMethod get = new GetMethod(targetURL);
    get.setFollowRedirects(true);    
    /*
     * Proxy the request headers from the browser to the target server
     */
    Enumeration headers = request.getHeaderNames();
    while(headers!=null && headers.hasMoreElements())
    {
        String headerName = (String)headers.nextElement();

        String headerValue = request.getHeader(headerName);

        if(headerValue != null)
        {
            get.addRequestHeader(headerName, headerValue);
        }            
    }        

    /*Make a request to the target server*/
    m_httpClient.executeMethod(get);
    /*
     * Set the status code
     */
    response.setStatus(get.getStatusCode());

    /*
     * proxy the response headers to the browser
     */
    Header responseHeaders[] = get.getResponseHeaders();
    for(int i=0; i<responseHeaders.length; i++)
    {
        String headerName = responseHeaders[i].getName();
        String headerValue = responseHeaders[i].getValue();

        if(headerValue != null)
        {
            response.addHeader(headerName, headerValue);
        }
    }

    /*
     * Proxy the response body to the browser
     */
    InputStream in = get.getResponseBodyAsStream();
    OutputStream out = response.getOutputStream();

    /*
     * If the server sends a 204 not-modified response, the InputStream will be null.
     */
    if (in !=null) {
        IOUtils.copy(in, out);
    }    
}

Invariant Violation: Objects are not valid as a React child

Invariant Violation: Objects are not valid as a React child happened to me when using a component that needed a renderItem props, like:

renderItem={this.renderItem}

and my mistake was to make my renderItem method async.

Non-invocable member cannot be used like a method?

As the error clearly states, OffenceBox.Text() is not a function and therefore doesn't make sense.

How to get primary key column in Oracle?

Select constraint_name,constraint_type from user_constraints where table_name** **= ‘TABLE_NAME’ ;

(This will list the primary key and then)

Select column_name,position from user_cons_cloumns where constraint_name=’PK_XYZ’; 

(This will give you the column, here PK_XYZ is the primay key name)

AWS Lambda import module error in python

There are just so many gotchas when creating deployment packages for AWS Lambda (for Python). I have spent hours and hours on debugging sessions until I found a formula that rarely fails.

I have created a script that automates the entire process and therefore makes it less error prone. I have also wrote tutorial that explains how everything works. You may want to check it out:

Hassle-Free Python Lambda Deployment [Tutorial + Script]

How can I check if a jQuery plugin is loaded?

I would strongly recommend that you bundle the DateJS library with your plugin and document the fact that you've done it. Nothing is more frustrating than having to hunt down dependencies.

That said, for legal reasons, you may not always be able to bundle everything. It also never hurts to be cautious and check for the existence of the plugin using Eran Galperin's answer.

Installed Ruby 1.9.3 with RVM but command line doesn't show ruby -v

  • Open Terminal.
  • Go to Edit -> Profile Preferences.
  • Select the Title & command Tab in the window opened.
  • Mark the checkbox Run command as login shell.
  • close the window and restart the Terminal.

Check this Official Linkenter image description here

Insert picture into Excel cell

You can do it in a less than a minute with Google Drive (and free, no hassles)

• Bulk Upload all your images on imgur.com

• Copy the Links of all the images together, appended with .jpg. Only imgur lets you do copy all the image links together, do that using the image tab top right.

• Use http://TextMechanic.co to prepend and append each line with this: Prefix : =image(" AND Suffix : ", 1)

So that it looks like this =image("URL", 1)

• Copy All

• Paste it in Google Spreadsheet

• Voila!

References :

http://www.labnol.org/internet/images-in-google-spreadsheet/18167/

https://support.google.com/drive/bin/answer.py?hl=en&answer=87037&from=1068225&rd=1

Server certificate verification failed: issuer is not trusted

string cmdArguments = $@"/k svn log --trust-server-cert --non-interactive ""{servidor}"" --username alex --password alex -r {numeroRevisao}";
ProcessStartInfo cmd = new ProcessStartInfo("cmd.exe", cmdArguments);

cmd.CreateNoWindow = true;
cmd.RedirectStandardOutput = true;
cmd.RedirectStandardError = true;
cmd.WindowStyle = ProcessWindowStyle.Hidden;
cmd.UseShellExecute = false;

Process reg = Process.Start(cmd);
string output = "";

using (System.IO.StreamReader myOutput = reg.StandardOutput)
{
    output += myOutput.ReadToEnd();
}
using (System.IO.StreamReader myError = reg.StandardError)
{
    output += myError.ReadToEnd();
}

return output;

Change values on matplotlib imshow() graph axis

I had a similar problem and google was sending me to this post. My solution was a bit different and less compact, but hopefully this can be useful to someone.

Showing your image with matplotlib.pyplot.imshow is generally a fast way to display 2D data. However this by default labels the axes with the pixel count. If the 2D data you are plotting corresponds to some uniform grid defined by arrays x and y, then you can use matplotlib.pyplot.xticks and matplotlib.pyplot.yticks to label the x and y axes using the values in those arrays. These will associate some labels, corresponding to the actual grid data, to the pixel counts on the axes. And doing this is much faster than using something like pcolor for example.

Here is an attempt at this with your data:

import matplotlib.pyplot as plt

# ... define 2D array hist as you did

plt.imshow(hist, cmap='Reds')
x = np.arange(80,122,2) # the grid to which your data corresponds
nx = x.shape[0]
no_labels = 7 # how many labels to see on axis x
step_x = int(nx / (no_labels - 1)) # step between consecutive labels
x_positions = np.arange(0,nx,step_x) # pixel count at label position
x_labels = x[::step_x] # labels you want to see
plt.xticks(x_positions, x_labels)
# in principle you can do the same for y, but it is not necessary in your case

How do I fix a compilation error for unhandled exception on call to Thread.sleep()?

You can get rid of the first line. You don't need import java.lang.*;

Just change your 5th line to:

public static void main(String [] args) throws Exception

Can I execute a function after setState is finished updating?

render will be called every time you setState to re-render the component if there are changes. If you move your call to drawGrid there rather than calling it in your update* methods, you shouldn't have a problem.

If that doesn't work for you, there is also an overload of setState that takes a callback as a second parameter. You should be able to take advantage of that as a last resort.

can't start MySql in Mac OS 10.6 Snow Leopard

YOU MUST REINSTALL mySQL after upgrading to Snow Leopard and remove any previous versions as well as previous startup from the preference panel. install 86_64 10.5...I find the others did not work for me.

  1. Download MySQL version Mac OS X 10.5 (x86_64) located at http://dev.mysql.com/downloads/mysql/5.4.html#macosx-dmg
  2. Install startup Item (follow instructions)
  3. Then install the beta version (follow instructions)
  4. If you want the start up in the Preference Panel...install mySQL.prefpane I find that SQL does not run from the terminal unless you start mySQL in the preference panel.

What type of hash does WordPress use?

$hash_type$salt$password

If the hash does not use a salt, then there is no $ sign for that. The actual hash in your case is after the 2nd $

The reason for this is, so you can have many types of hashes with different salts and feeds that string into a function that knows how to match it with some other value.

MySQL Update Inner Join tables query

Try this:

UPDATE business AS b
INNER JOIN business_geocode AS g ON b.business_id = g.business_id
SET b.mapx = g.latitude,
  b.mapy = g.longitude
WHERE  (b.mapx = '' or b.mapx = 0) and
  g.latitude > 0

Update:

Since you said the query yielded a syntax error, I created some tables that I could test it against and confirmed that there is no syntax error in my query:

mysql> create table business (business_id int unsigned primary key auto_increment, mapx varchar(255), mapy varchar(255)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)

mysql> create table business_geocode (business_geocode_id int unsigned primary key auto_increment, business_id int unsigned not null, latitude varchar(255) not null, longitude varchar(255) not null, foreign key (business_id) references business(business_id)) engine=innodb;
Query OK, 0 rows affected (0.01 sec)

mysql> UPDATE business AS b
    -> INNER JOIN business_geocode AS g ON b.business_id = g.business_id
    -> SET b.mapx = g.latitude,
    ->   b.mapy = g.longitude
    -> WHERE  (b.mapx = '' or b.mapx = 0) and
    ->   g.latitude > 0;
Query OK, 0 rows affected (0.00 sec)
Rows matched: 0  Changed: 0  Warnings: 0

See? No syntax error. I tested against MySQL 5.5.8.

How to SFTP with PHP?

I performed a full-on cop-out and wrote a class which creates a batch file and then calls sftp via a system call. Not the nicest (or fastest) way of doing it but it works for what I need and it didn't require any installation of extra libraries or extensions in PHP.

Could be the way to go if you don't want to use the ssh2 extensions

Downgrade npm to an older version

Just need to add version of which you want

upgrade or downgrade

npm install -g npm@version

Example if you want to downgrade from npm 5.6.0 to 4.6.1 then,

npm install -g [email protected]

It is tested on linux

How to run Unix shell script from Java code?

Just the same thing that Solaris 5.10 it works like this ./batchstart.sh there is a trick I don´t know if your OS accept it use \\. batchstart.sh instead. This double slash may help.

How to use Lambda in LINQ select statement

using LINQ query expression

 IEnumerable<SelectListItem> stores =
        from store in database.Stores
        where store.CompanyID == curCompany.ID
        select new SelectListItem { Value = store.Name, Text = store.ID };

 ViewBag.storeSelector = stores;

or using LINQ extension methods with lambda expressions

 IEnumerable<SelectListItem> stores = database.Stores
        .Where(store => store.CompanyID == curCompany.ID)
        .Select(store => new SelectListItem { Value = store.Name, Text = store.ID });

 ViewBag.storeSelector = stores;

How do I use brew installed Python as the default Python?

See: How to symlink python in Homebrew?

$ brew link --overwrite python
Linking /usr/local/Cellar/python/2.7.3... 28 symlinks created
$ which python
/usr/local/bin/python

PHP send mail to multiple email addresses

Just separate them by comma, like $email_to = "[email protected], [email protected], John Doe <[email protected]>".

How can I check if a key exists in a dictionary?

Another method is has_key() (if still using Python 2.X):

>>> a={"1":"one","2":"two"}
>>> a.has_key("1")
True

Could not find com.google.android.gms:play-services:3.1.59 3.2.25 4.0.30 4.1.32 4.2.40 4.2.42 4.3.23 4.4.52 5.0.77 5.0.89 5.2.08 6.1.11 6.1.71 6.5.87

In addition to installing the repository and the SDK packages one should be aware that the version number changes periodically. A simple solution at this point is to replace the specific version number with a plus (+) symbol.

compile 'com.google.android.gms:play-services:+'

Google instructions indicate that one should be sure to upgrade the version numbers, however adding the plus deals with the changes in versioning. Also note that when building in Android Studio a message will appear in the status line when a new version is available.

One can view the available versions of play services by drilling down on the correct repository path:

play-services repository path

References

This site also has instructions for Eclipse, and other IDE's.

ADS-Setup

How to run Java program in command prompt

You can use javac *.java command to compile all you java sources. Also you should learn a little about classpath because it seems that you should set appropriate classpath for succesful compilation (because your IDE use some libraries for building WebService clients). Also I can recommend you to check wich command your IDE use to build your project.

Use images instead of radio buttons

Here is a simple jQuery UI solution based on the example here:

http://jqueryui.com/button/#radio

Modified code:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>jQuery UI Button - Radios</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.10.2.js"></script>
  <script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script>
  $(function() {
    $( "#radio" ).buttonset();
  });
  </script>
</head>
<body>

<form>
  <div id="radio">
    <input type="radio" id="radio1" name="radio"><label for="radio1"><img src="image1.gif" /></label>
    <input type="radio" id="radio2" name="radio" checked="checked"><label for="radio2"><img src="image2.gif" /></label>
    <input type="radio" id="radio3" name="radio"><label for="radio3"><img src="image3.gif" /></label>
  </div>
</form>

</body>
</html>

jQueryUI takes care of the image background so you know which button is checked.

Beware: If you want to set a button to checked or unchecked via Javascript, you must call the refresh function:

        $('#radio3').prop('checked', true).button("refresh");

Visual Studio window which shows list of methods

I have been using USysWare DPack since forever. It is very small and not intrusive so if all you want is a quick shortcut window showing list of methods of the current file you are using, it provides just that. Good thing is that the author is still active after more than 10 years just to keep providing the same features into latest VS release.

https://marketplace.visualstudio.com/items?itemName=SergeyM.DPack-16348

After installation, just use Alt + M to bring up the method list window. I prefer to show all members instead, but it's up to you.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

I had the same problem on Windows XP just recently. I tried to chmod 700 on my ~/.ssh/id_rsa file but it did not seem to work. When I had a look at the permissions using ls -l on the ~/.ssh/id_rsa I could see that my effective permissions still was 644.

Then I remembered that windows permissions also inherit permissions from the folders, and the folder was still open to everyone. A solution could be to set permissions for the folder as well, but I think a better way would be to tell the system to ignore inheritance for this file. This can be done using the advanced option on the security tab in the properties of the file, and unchecking "inherit from parent permissions..."

This might be helpful for others with the same problem.

How to copy file from HDFS to the local file system

if you are using docker you have to do the following steps:

  1. copy the file from hdfs to namenode (hadoop fs -get output/part-r-00000 /out_text). "/out_text" will be stored on the namenode.

  2. copy the file from namenode to local disk by (docker cp namenode:/out_text output.txt)

  3. output.txt will be there on your current working directory

Resolve absolute path from relative path and/or file name

I have not seen many solutions to this problem. Some solutions make use of directory traversal using CD and others make use of batch functions. My personal preference has been for batch functions and in particular, the MakeAbsolute function as provided by DosTips.

The function has some real benefits, primarily that it does not change your current working directory and secondly that the paths being evaluated don't even have to exist. You can find some helpful tips on how to use the function here too.

Here is an example script and its outputs:

@echo off

set scriptpath=%~dp0
set siblingfile=sibling.bat
set siblingfolder=sibling\
set fnwsfolder=folder name with spaces\
set descendantfolder=sibling\descendant\
set ancestorfolder=..\..\
set cousinfolder=..\uncle\cousin

call:MakeAbsolute siblingfile      "%scriptpath%"
call:MakeAbsolute siblingfolder    "%scriptpath%"
call:MakeAbsolute fnwsfolder       "%scriptpath%"
call:MakeAbsolute descendantfolder "%scriptpath%"
call:MakeAbsolute ancestorfolder   "%scriptpath%"
call:MakeAbsolute cousinfolder     "%scriptpath%"

echo scriptpath:       %scriptpath%
echo siblingfile:      %siblingfile%
echo siblingfolder:    %siblingfolder%
echo fnwsfolder:       %fnwsfolder%
echo descendantfolder: %descendantfolder%
echo ancestorfolder:   %ancestorfolder%
echo cousinfolder:     %cousinfolder%
GOTO:EOF

::----------------------------------------------------------------------------------
:: Function declarations
:: Handy to read http://www.dostips.com/DtTutoFunctions.php for how dos functions
:: work.
::----------------------------------------------------------------------------------
:MakeAbsolute file base -- makes a file name absolute considering a base path
::                      -- file [in,out] - variable with file name to be converted, or file name itself for result in stdout
::                      -- base [in,opt] - base path, leave blank for current directory
:$created 20060101 :$changed 20080219 :$categories Path
:$source http://www.dostips.com
SETLOCAL ENABLEDELAYEDEXPANSION
set "src=%~1"
if defined %1 set "src=!%~1!"
set "bas=%~2"
if not defined bas set "bas=%cd%"
for /f "tokens=*" %%a in ("%bas%.\%src%") do set "src=%%~fa"
( ENDLOCAL & REM RETURN VALUES
    IF defined %1 (SET %~1=%src%) ELSE ECHO.%src%
)
EXIT /b

And the output:

C:\Users\dayneo\Documents>myscript
scriptpath:       C:\Users\dayneo\Documents\
siblingfile:      C:\Users\dayneo\Documents\sibling.bat
siblingfolder:    C:\Users\dayneo\Documents\sibling\
fnwsfolder:       C:\Users\dayneo\Documents\folder name with spaces\
descendantfolder: C:\Users\dayneo\Documents\sibling\descendant\
ancestorfolder:   C:\Users\
cousinfolder:     C:\Users\dayneo\uncle\cousin

I hope this helps... It sure helped me :) P.S. Thanks again to DosTips! You rock!

How to replace comma with a dot in the number (or any replacement)

After replacing the character, you need to be asign to the variable.

var tt = "88,9827";
tt = tt.replace(/,/g, '.')
alert(tt)

In the alert box it will shows 88.9827

Copy files to network computers on windows command line

Why for? What do you want to iterate? Try this.

call :cpy pc-name-1
call :cpy pc-name-2
...

:cpy
net use \\%1\{destfolder} {password} /user:{username}
copy {file} \\%1\{destfolder}
goto :EOF

Golang append an item to a slice

In your example the slice argument of the Test function receives a copy of the variable a in the caller's scope.

Since a slice variable holds a "slice descriptor" which merely references an underlying array, in your Test function you modify the slice descriptor held in the slice variable several times in a row, but this does not affect the caller and its a variable.

Inside the Test function, the first append reallocates the backing array under the slice variable, copies its original contents over, appends 100 to it, and that's what you're observing. Upon exiting from Test, the slice variable goes out of scope and so does the (new) underlying array that slice references. (Jeff Lee is correct about that it's not what really happens, so the updated version follows; as he correctly states, this answer is correct, if maybe a bit too terse.)

Outside the Test function, a slice of length 7 and capacity 8 is allocated, and its 7 elements filled.
Inside the Test function, the first append sees the that the slice's capacity is still one element larger than its length — in other words, there is room for one more element to add without reallocation. So it "eats up" that remaining element and places 100 to it, after which it adjusts the length in the copy of the slice descriptor to become equal to the slice's capaticy. This does not affect the slice descriptor's in the caller's scope.

And that's what you're observing. Upon exiting from Test, the slice variable goes out of scope and so does the (new) underlying array that slice references.

If you want to make Test behave like append, you have to return the new slice from it — just like append does — and require the callers of Test to use it in the same way they would use append:

func Test(slice []int) []int {
    slice = append(slice, 100)

    fmt.Println(slice)

    return slice
}

a = Test(a)

Please read this article thoroughly as it basically shows you how to implement append by hand, after explaining how slices are working internally. Then read this.

Error:Execution failed for task ':app:transformClassesWithDexForDebug' in android studio

Error:Execution failed for task ':app:transformClassesWithDexForDebug'. com.android.build.api.transform.TransformException: java.lang.RuntimeException: com.android.ide.common.process.ProcessException: java.util.concurrent.ExecutionException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command 'C:\Program Files\Java\jdk1.7.0_79\bin\java.exe'' finished with non-zero exit value 1

The upper error occure due to lot of reason. So I can put why this error occure and how to solve it.

REASON 1 : Duplicate of class file name

SOLUTION :

when your refactoring of some of your class files to a library project. and that time you write name of class file So, double check that you do not have any duplicate names

REASON 2 : When you have lot of cache Memory

SOLUTION :

Sometime if you have lot of cache memory then this error occure so solve it. go to File/Invalidate caches / Restart then select Invalidate and Restart it will clean your cache memory.

REASON 3 : When there is internal bug or used beta Version to Switch back to stable version.

SOLUTION :

Solution is just simple go to Build menu and click Clean Project and after cleaning click Rebuild Project.

REASON 4 : When you memory of the system Configuration is low.

SOLUTION :

open Task Manager and stop the other application which are not most used at that time so it will free the space and solve OutOfMemory.

REASON 5 : The problem is your method count has exceed from 65K.

SOLUTION :

open your Project build.gradle file add

defaultConfig {
        ...
        multiDexEnabled true
    }

and in dependencies add below line.

dependencies 
    {
       compile 'com.android.support:multidex:1.0.0'
    }

SQL Group By with an Order By

MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses.

You can get around this limit with the deprecated syntax:

SELECT COUNT(id), `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY 1 DESC
LIMIT 20

1, since it's the first column you want to group on.

Select all DIV text with single mouse click

The answer of Neuroxik was really helpful. I had only a trouble with Chrome, because when I clicked on an external div, It did not work. I could solve it removing the old ranges before add the new range:

function selectText(containerid) {
    if (document.selection) {
        var range = document.body.createTextRange();
        range.moveToElementText(document.getElementById(containerid));
        range.select();
    } else if (window.getSelection()) {
        var range = document.createRange();
        range.selectNode(document.getElementById(containerid));
        window.getSelection().removeAllRanges();
        window.getSelection().addRange(range);
    }
}
<div id="selectable" onclick="selectText('selectable')">http://example.com/page.htm</div>

Method Call Chaining; returning a pointer vs a reference?

The difference between pointers and references is quite simple: a pointer can be null, a reference can not.

Examine your API, if it makes sense for null to be able to be returned, possibly to indicate an error, use a pointer, otherwise use a reference. If you do use a pointer, you should add checks to see if it's null (and such checks may slow down your code).

Here it looks like references are more appropriate.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

This is not an answer, but it's hard to read if I put results in comment.

I get these results with a Mac Pro (Westmere 6-Cores Xeon 3.33 GHz). I compiled it with clang -O3 -msse4 -lstdc++ a.cpp -o a (-O2 get same result).

clang with uint64_t size=atol(argv[1])<<20;

unsigned    41950110000 0.811198 sec    12.9263 GB/s
uint64_t    41950110000 0.622884 sec    16.8342 GB/s

clang with uint64_t size=1<<20;

unsigned    41950110000 0.623406 sec    16.8201 GB/s
uint64_t    41950110000 0.623685 sec    16.8126 GB/s

I also tried to:

  1. Reverse the test order, the result is the same so it rules out the cache factor.
  2. Have the for statement in reverse: for (uint64_t i=size/8;i>0;i-=4). This gives the same result and proves the compile is smart enough to not divide size by 8 every iteration (as expected).

Here is my wild guess:

The speed factor comes in three parts:

  • code cache: uint64_t version has larger code size, but this does not have an effect on my Xeon CPU. This makes the 64-bit version slower.

  • Instructions used. Note not only the loop count, but the buffer is accessed with a 32-bit and 64-bit index on the two versions. Accessing a pointer with a 64-bit offset requests a dedicated 64-bit register and addressing, while you can use immediate for a 32-bit offset. This may make the 32-bit version faster.

  • Instructions are only emitted on the 64-bit compile (that is, prefetch). This makes 64-bit faster.

The three factors together match with the observed seemingly conflicting results.

How to find the mime type of a file in python?

This may be old already, but why not use UploadedFile.content_type directly from Django? Is not the same?(https://docs.djangoproject.com/en/1.11/ref/files/uploads/#django.core.files.uploadedfile.UploadedFile.content_type)

Check whether a variable is a string in Ruby

foo.instance_of? String

or

foo.kind_of? String 

if you you only care if it is derrived from String somewhere up its inheritance chain

MVC3 EditorFor readOnly

I know the question states MVC 3, but it was 2012, so just in case:

As of MVC 5.1 you can now pass HTML attributes to EditorFor like so:

@Html.EditorFor(x => x.Name, new { htmlAttributes = new { @readonly = "", disabled = "" } })