Programs & Examples On #Dojo dnd

Exists Angularjs code/naming conventions?

Check out this GitHub repository that describes best practices for AngularJS apps. It has naming conventions for different components. It is not complete, but it is community-driven so everyone can contribute.

SQL WHERE ID IN (id1, id2, ..., idn)

Option 1 is the only good solution.

Why?

  • Option 2 does the same but you repeat the column name lots of times; additionally the SQL engine doesn't immediately know that you want to check if the value is one of the values in a fixed list. However, a good SQL engine could optimize it to have equal performance like with IN. There's still the readability issue though...

  • Option 3 is simply horrible performance-wise. It sends a query every loop and hammers the database with small queries. It also prevents it from using any optimizations for "value is one of those in a given list"

How to get AIC from Conway–Maxwell-Poisson regression via COM-poisson package in R?

I figured out myself.

cmp calls ComputeBetasAndNuHat which returns a list which has objective as minusloglik

So I can change the function cmp to get this value.

jQuery OR Selector?

Daniel A. White Solution works great for classes.

I've got a situation where I had to find input fields like donee_1_card where 1 is an index.

My solution has been

$("input[name^='donee']" && "input[name*='card']")

Though I am not sure how optimal it is.

Import mysql DB with XAMPP in command LINE

mysql -h localhost -u username -p databasename < dump.sql

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

Correct way to handle conditional styling in React

First, I agree with you as a matter of style - I would also (and do also) conditionally apply classes rather than inline styles. But you can use the same technique:

<div className={{completed ? "completed" : ""}}></div>

For more complex sets of state, accumulate an array of classes and apply them:

var classes = [];

if (completed) classes.push("completed");
if (foo) classes.push("foo");
if (someComplicatedCondition) classes.push("bar");

return <div className={{classes.join(" ")}}></div>;

MySQL Orderby a number, Nulls last

You can coalesce your NULLs in the ORDER BY statement:

select * from tablename
where <conditions>
order by
    coalesce(position, 0) ASC, 
    id DESC

If you want the NULLs to sort on the bottom, try coalesce(position, 100000). (Make the second number bigger than all of the other position's in the db.)

How to create string with multiple spaces in JavaScript

var a = 'something' + Array(10).fill('\xa0').join('') + 'something'

number inside Array(10) can be changed to needed number of spaces

AppFabric installation failed because installer MSI returned with error code : 1603

Last but not least, I've found this page. Is quite complete the cause and further explanation.

SOLVED: Error 1306 AppFabric + Windows Server 2012

User Control - Custom Properties

You do this via attributes on the properties, like this:

[Description("Test text displayed in the textbox"),Category("Data")] 
public string Text {
  get => myInnerTextBox.Text;
  set => myInnerTextBox.Text = value;
}

The category is the heading under which the property will appear in the Visual Studio Properties box. Here's a more complete MSDN reference, including a list of categories.

Warning: mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql.sock) in

For some reason mysql on OS X gets the locations of the required socket file a bit wrong, but thankfully the solution is as simple as setting up a symbolic link.

You may have a socket (appearing as a zero length file) as /tmp/mysql.sock or /var/mysql/mysql.sock, but one or more apps is looking in the other location for it. Find out with this command:

ls -l /tmp/mysql.sock /var/mysql/mysql.sock

Rather than move the socket, edit config files, and have to remember to keep edited files local and away from servers where the paths are correct, simply create a symbolic link so your Mac finds the required socket, even when it's looking in the wrong place!

If you have /tmp/mysql.sock but no /var/mysql/mysql.sock then...

cd /var 
sudo mkdir mysql
sudo chmod 755 mysql
cd mysql
sudo ln -s /tmp/mysql.sock mysql.sock

If you have /var/mysql/mysql.sock but no /tmp/mysql.sock then...

cd /tmp
ln -s /var/mysql/mysql.sock mysql.sock

You will need permissions to create the directory and link, so just prefix the commands above with sudo if necessary.

How to clear Route Caching on server: Laravel 5.2.37

For your case solution is :

php artisan cache:clear
php artisan route:cache

Optimizing Route Loading is a must on production :

If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:

php artisan route:cache

This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.

Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.

Laravel 5 clear cache from route, view, config and all cache data from application

I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.

Reoptimized class loader:

php artisan optimize

Clear Cache facade value:

php artisan cache:clear

Clear Route cache:

php artisan route:cache

Clear View cache:

php artisan view:clear

Clear Config cache:

php artisan config:cache

How to convert from java.sql.Timestamp to java.util.Date?

tl;dr

Instant instant = myResultSet.getObject( … , Instant.class ) ;

…or, if your JDBC driver does not support the optional Instant, it is required to support OffsetDateTime:

OffsetDateTime odt = myResultSet.getObject( … , OffsetDateTime.class ) ;

Avoid both java.util.Date & java.sql.Timestamp. They have been replaced by the java.time classes. Specifically, the Instant class representing a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).

Different Values ? Unverified Problem

To address the main part of the Question: "Why different dates between java.util.Date and java.sql.Timestamp objects when one is derived from the other?"

There must be a problem with your code. You did not post your code, so we cannot pinpoint the problem.

First, that string value you show for value of java.util.Date did not come from its default toString method, so you obviously were doing additional operations.

Secondly, when I run similar code I do indeed get exact same date-time values.

First create a java.sql.Timestamp object.

// Timestamp
long millis1 =  new java.util.Date().getTime();
java.sql.Timestamp ts = new java.sql.Timestamp(millis1);

Now extract the count-of-milliseconds-since-epoch to instantiate a java.util.Date object.

// Date
long millis2 = ts.getTime();
java.util.Date date = new java.util.Date( millis2 );

Dump values to console.

System.out.println("millis1 = " + millis1 );
System.out.println("ts = " + ts );
System.out.println("millis2 = " + millis2 );
System.out.println("date = " + date );

When run.

millis1 = 1434666385642
ts = 2015-06-18 15:26:25.642
millis2 = 1434666385642
date = Thu Jun 18 15:26:25 PDT 2015

So the code shown in the Question is indeed a valid way to convert from java.sql.Timestamp to java.util.Date, though you will lose any nanoseconds data.

java.util.Date someDate = new Date( someJUTimestamp.getTime() ); 

Different Formats Of String Output

Note that the output of the toString methods is a different format, as documented. The java.sql.Timestamp follows SQL format, similar to ISO 8601 format but without the T in middle.

Ignore Inheritance

As discussed on comments on other Answers and the Question, you should ignore the fact that java.sql.Timestamp inherits from java.util.Date. The j.s.Timestamp doc clearly states that you should not view one as a sub-type of the other: (emphasis mine)

Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date. The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.

If you ignore the Java team’s advice and take such a view, one critical problem is that you will lose data: any microsecond or nanosecond part of a second that may be coming from the database is lost as a Date has only millisecond resolution.

Basically, all the old date-time classes from early Java are a big mess: java.util.Date, j.u.Calendar, java.text.SimpleDateFormat, java.sql.Timestamp/.Date/.Time. They were one of the first valiant efforts at a date-time framework in the industry, but ultimately they fail. Specifically here, java.sql.Timestamp is a java.util.Date with nanoseconds tacked on; this is a hack, not good design.

java.time

Avoid the old date-time classes bundled with early versions of Java.

Instead use the java.time package (Tutorial) built into Java 8 and later whenever possible.

Basics of java.time… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

Example code using java.time as of Java 8. With a JDBC driver supporting JDBC 4.2 and later, you can directly exchange java.time classes with your database; no need for the legacy classes.

Instant instant = myResultSet.getObject( … , Instant.class) ;  // Instant is the raw underlying data, an instantaneous point on the time-line stored as a count of nanoseconds since epoch.

You may want to adjust into a time zone other than UTC.

ZoneId z = ZoneId.of( "America/Montreal" );  // Always make time zone explicit rather than relying implicitly on the JVM’s current default time zone being applied.
ZonedDateTime zdt = instant.atZone( z ) ;

Perform your business logic. Here we simply add a day.

ZonedDateTime zdtNextDay = zdt.plusDays( 1 ); // Add a day to get "day after".

At the last stage, if absolutely needed, convert to a java.util.Date for interoperability.

java.util.Date dateNextDay = Date.from( zdtNextDay.toInstant( ) );  // WARNING: Losing data (the nanoseconds resolution).

Dump to console.

System.out.println( "instant = " + instant );
System.out.println( "zdt = " + zdt );
System.out.println( "zdtNextDay = " + zdtNextDay );
System.out.println( "dateNextDay = " + dateNextDay );

When run.

instant = 2015-06-18T16:44:13.123456789Z
zdt = 2015-06-18T19:44:13.123456789-04:00[America/Montreal]
zdtNextDay = 2015-06-19T19:44:13.123456789-04:00[America/Montreal]
dateNextDay = Fri Jun 19 16:44:13 PDT 2015

Conversions

If you must use the legacy types to interface with old code not yet updated for java.time, you may convert. Use new methods added to the old java.util.Date and java.sql.* classes for conversion.

Instant instant = myJavaSqlTimestamp.toInstant() ;

…and…

java.sql.Timestamp ts = java.sql.Timestamp.from( instant ) ;

See the Tutorial chapter, Legacy Date-Time Code, for more info on conversions.

Fractional Second

Be aware of the resolution of the fractional second. Conversions from nanoseconds to milliseconds means potentially losing some data.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Cannot refer to a non-final variable inside an inner class defined in a different method

I just wrote something to handle something along the authors intention. I found the best thing to do was to let the constructor take all the objects and then in your implemented method use that constructor objects.

However, if you are writing a generic interface class, then you have to pass an Object, or better a list of Objects. This could be done by Object[] or even better, Object ... because it is easier to call.

See my example piece just below.

List<String> lst = new ArrayList<String>();
lst.add("1");
lst.add("2");        

SomeAbstractClass p = new SomeAbstractClass (lst, "another parameter", 20, true) {            

    public void perform( ) {                           
        ArrayList<String> lst = (ArrayList<String>)getArgs()[0];                        
    }

};

public abstract class SomeAbstractClass{    
    private Object[] args;

    public SomeAbstractClass(Object ... args) {
        this.args = args;           
    }      

    public abstract void perform();        

    public Object[] getArgs() {
        return args;
    }

}

Please see this post about Java closures that supports this out of the box: http://mseifed.blogspot.se/2012/09/closure-implementation-for-java-5-6-and.html

Version 1 supports passing of non-final closures with autocasting:
https://github.com/MSeifeddo/Closure-implementation-for-Java-5-6-and-7/blob/master/org/mo/closure/v1/Closure.java

    SortedSet<String> sortedNames = new TreeSet<String>();
    // NOTE! Instead of enforcing final, we pass it through the constructor
    eachLine(randomFile0, new V1<String>(sortedNames) {
        public void call(String line) {
            SortedSet<String> sortedNames = castFirst();  // Read contructor arg zero, and auto cast it
            sortedNames.add(extractName(line));
        }
    });

Convert a JSON string to object in Java ME?

Apart from www.json.org you can also implement your own parser using javacc and matching your personnal grammar/schema. See this note on my blog : http://plindenbaum.blogspot.com/2008/07/parsing-json-with-javacc-my-notebook.html

Quickly create large file on a Windows system

Open up Windows Task Manager, find the biggest process you have running right click, and click on Create dump file.

This will create a file relative to the size of the process in memory in your temporary folder.

You can easily create a file sized in gigabytes.

Enter image description here

Enter image description here

How to create a cron job using Bash automatically without the interactive editor?

echo "0 * * * * docker system prune --force >/dev/null 2>&1" | sudo tee /etc/cron.daily/dockerprune

Change Select List Option background colour on hover

The problem is that even JavaScript does not see the option element being hovered. This is just to put emphasis on how it's not going to be solved (any time soon at least) by using just CSS:

window.onmouseover = function(e)
{
 console.log(e.target.nodeName);
}

The only way to resolve this issue (besides waiting a millennia for browser vendors to fix bugs, let alone one that afflicts what you're trying to do) is to replace the drop-down menu with your own HTML/XML using JavaScript. This would likely involve the use of replacing the select element with a ul element and the use of a radio input element per li element.

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Show week number with Javascript?

Simply add it to your current code, then call (new Date()).getWeek()

<script>
    Date.prototype.getWeek = function() {
        var onejan = new Date(this.getFullYear(), 0, 1);
        return Math.ceil((((this - onejan) / 86400000) + onejan.getDay() + 1) / 7);
    }

    var weekNumber = (new Date()).getWeek();

    var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
    var now = new Date();
    document.write(dayNames[now.getDay()] + " (" + weekNumber + ").");
</script>

Gem Command not found

I know this is kind of late for a response. But I did run into this error and I found a solution here: https://rvm.io/integration/gnome-terminal

You just have to enable 'Run command as login shell' under the terminal preferences.

How to convert from []byte to int in Go Programming

(reposting this answer)

You can use encoding/binary's ByteOrder to do this for 16, 32, 64 bit types

Play

package main

import "fmt"
import "encoding/binary"

func main() {
    var mySlice = []byte{244, 244, 244, 244, 244, 244, 244, 244}
    data := binary.BigEndian.Uint64(mySlice)
    fmt.Println(data)
}

Download old version of package with NuGet

Another option is to change the version number in the packages.config file. This will cause NuGet to download the dlls for that version the next time you build.

how to set default main class in java?

you can right click on the project select "set configuration" then "Customize", from there you can choose your main class. ScreenShot

CSS How to set div height 100% minus nPx

I haven't seen anything like this posted yet, but I thought I'd put it out there.

<div class="main">
<header>Header</header>
<div class="content">Content</div>

Then CSS:

body, html {
    height: 100%;
    margin: 0;
    padding: 0;
}

.main {
    height: 100%;
    padding-top: 50px;
    box-sizing: border-box;
}

header {
    height: 50px;
    margin-top: -50px;
    width: 100%;
    background-color: #5078a5;
}

.content {
    height: 100%;
    background-color: #999999;
}

Here is a working jsfiddle

Note: I have no idea what the browser compatability is for this. I was just playing around with alternate solutions and this seemed to work well.

How to restore PostgreSQL dump file into Postgres databases?

You didn't mention how your backup was made, so the generic answer is: Usually with the psql tool.

Depending on what pg_dump was instructed to dump, the SQL file can have different sets of SQL commands. For example, if you instruct pg_dump to dump a database using --clean and --schema-only, you can't expect to be able to restore the database from that dump as there will be no SQL commands for COPYing (or INSERTing if --inserts is used ) the actual data in the tables. A dump like that will contain only DDL SQL commands, and will be able to recreate the schema but not the actual data.

A typical SQL dump is restored with psql:

psql (connection options here) database  < yourbackup.sql

or alternatively from a psql session,

psql (connection options here) database
database=# \i /path/to/yourbackup.sql

In the case of backups made with pg_dump -Fc ("custom format"), which is not a plain SQL file but a compressed file, you need to use the pg_restore tool.

If you're working on a unix-like, try this:

man psql
man pg_dump
man pg_restore

otherwise, take a look at the html docs. Good luck!

Android: How do bluetooth UUIDs work?

UUID is just a number. It has no meaning except you create on the server side of an Android app. Then the client connects using that same UUID.

For example, on the server side you can first run uuid = UUID.randomUUID() to generate a random number like fb36491d-7c21-40ef-9f67-a63237b5bbea. Then save that and then hard code that into your listener program like this:

 UUID uuid = UUID.fromString("fb36491d-7c21-40ef-9f67-a63237b5bbea"); 

Your Android server program will listen for incoming requests with that UUID like this:

    BluetoothServerSocket server = mBluetoothAdapter.listenUsingRfcommWithServiceRecord("anyName", uuid);

BluetoothSocket socket = server.accept();

Back button and refreshing previous activity

One option would be to use the onResume of your first activity.

@Override
public void onResume()
    {  // After a pause OR at startup
    super.onResume();
    //Refresh your stuff here
     }

Or you can start Activity for Result:

Intent i = new Intent(this, SecondActivity.class);
startActivityForResult(i, 1);

In secondActivity if you want to send back data:

 Intent returnIntent = new Intent();
 returnIntent.putExtra("result",result);
 setResult(RESULT_OK,returnIntent);     
 finish();

if you don't want to return data:

Intent returnIntent = new Intent();
setResult(RESULT_CANCELED, returnIntent);        
finish();

Now in your FirstActivity class write following code for onActivityResult() method

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

  if (requestCode == 1) {

     if(resultCode == RESULT_OK){      
         //Update List         
     }
     if (resultCode == RESULT_CANCELED) {    
         //Do nothing?
     }
  }
}//onActivityResult

Plotting a 2D heatmap with Matplotlib

Seaborn takes care of a lot of the manual work and automatically plots a gradient at the side of the chart etc.

import numpy as np
import seaborn as sns
import matplotlib.pylab as plt

uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, linewidth=0.5)
plt.show()

enter image description here

Or, you can even plot upper / lower left / right triangles of square matrices, for example a correlation matrix which is square and is symmetric, so plotting all values would be redundant anyway.

corr = np.corrcoef(np.random.randn(10, 200))
mask = np.zeros_like(corr)
mask[np.triu_indices_from(mask)] = True
with sns.axes_style("white"):
    ax = sns.heatmap(corr, mask=mask, vmax=.3, square=True,  cmap="YlGnBu")
    plt.show()

enter image description here

How to draw interactive Polyline on route google maps v2 android

I've created a couple of map tutorials that will cover what you need

Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.

Take a look at these 2 tutorials and the Github project containing the sample app.

It contains some tips to make your code cleaner and more efficient:

  • Using Google HTTP Library for more efficient API access and easy JSON handling.
  • Using google-map-utils library for maps-related functions (like decoding the polylines)
  • Animating markers

logout and redirecting session in php

<?php

session_start();

session_unset();

session_destroy();

header("location:home.php");

exit();

?>

Can two Java methods have same name with different return types?

You can have two methods with the same arguments and different return types only if one of the methods is inherited and the return types are compatible.

For example:

public class A
{
    Object foo() { return null; }
}

public class B
    extends A
{
    String foo() { return null; }
}

Passing a String by Reference in Java?

The answer is simple. In java strings are immutable. Hence its like using 'final' modifier (or 'const' in C/C++). So, once assigned, you cannot change it like the way you did.

You can change which value to which a string points, but you can NOT change the actual value to which this string is currently pointing.

Ie. String s1 = "hey". You can make s1 = "woah", and that's totally ok, but you can't actually change the underlying value of the string (in this case: "hey") to be something else once its assigned using plusEquals, etc. (ie. s1 += " whatup != "hey whatup").

To do that, use the StringBuilder or StringBuffer classes or other mutable containers, then just call .toString() to convert the object back to a string.

note: Strings are often used as hash keys hence that's part of the reason why they are immutable.

Sequence contains more than one element

SingleOrDefault method throws an Exception if there is more than one element in the sequence.

Apparently, your query in GetCustomer is finding more than one match. So you will either need to refine your query or, most likely, check your data to see why you're getting multiple results for a given customer number.

Passing struct to function

The line function implementation should be:

void addStudent(struct student person) {

}

person is not a type but a variable, you cannot use it as the type of a function parameter.

Also, make sure your struct is defined before the prototype of the function addStudent as the prototype uses it.

Converting string to date in mongodb

Using MongoDB 4.0 and newer

The $toDate operator will convert the value to a date. If the value cannot be converted to a date, $toDate errors. If the value is null or missing, $toDate returns null:

You can use it within an aggregate pipeline as follows:

db.collection.aggregate([
    { "$addFields": {
        "created_at": {
            "$toDate": "$created_at"
        }
    } }
])

The above is equivalent to using the $convert operator as follows:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$convert": { 
                "input": "$created_at", 
                "to": "date" 
            } 
        }
    } }
])

Using MongoDB 3.6 and newer

You cab also use the $dateFromString operator which converts the date/time string to a date object and has options for specifying the date format as well as the timezone:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$dateFromString": { 
                "dateString": "$created_at",
                "format": "%m-%d-%Y" /* <-- option available only in version 4.0. and newer */
            } 
        }
    } }
])

Using MongoDB versions >= 2.6 and < 3.2

If MongoDB version does not have the native operators that do the conversion, you would need to manually iterate the cursor returned by the find() method by either using the forEach() method or the cursor method next() to access the documents. Withing the loop, convert the field to an ISODate object and then update the field using the $set operator, as in the following example where the field is called created_at and currently holds the date in string format:

var cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }}); 
while (cursor.hasNext()) { 
    var doc = cursor.next(); 
    db.collection.update(
        {"_id" : doc._id}, 
        {"$set" : {"created_at" : new ISODate(doc.created_at)}}
    ) 
};

For improved performance especially when dealing with large collections, take advantage of using the Bulk API for bulk updates as you will be sending the operations to the server in batches of say 1000 which gives you a better performance as you are not sending every request to the server, just once in every 1000 requests.

The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2. It updates all the documents in the collection by changing the created_at fields to date fields:

var bulk = db.collection.initializeUnorderedBulkOp(),
    counter = 0;

db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
    var newDate = new ISODate(doc.created_at);
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "created_at": newDate}
    });

    counter++;
    if (counter % 1000 == 0) {
        bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
        bulk = db.collection.initializeUnorderedBulkOp();
    }
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }

Using MongoDB 3.2

The next example applies to the new MongoDB version 3.2 which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite():

var bulkOps = [],
    cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }});

cursor.forEach(function (doc) { 
    var newDate = new ISODate(doc.created_at);
    bulkOps.push(         
        { 
            "updateOne": { 
                "filter": { "_id": doc._id } ,              
                "update": { "$set": { "created_at": newDate } } 
            }         
        }           
    );

    if (bulkOps.length === 500) {
        db.collection.bulkWrite(bulkOps);
        bulkOps = [];
    }     
});

if (bulkOps.length > 0) db.collection.bulkWrite(bulkOps);

C++ [Error] no matching function for call to

You are trying to call DeckOfCards::shuffle with a deckOfCards parameter:

deckOfCards cardDeck; // create DeckOfCards object
cardDeck.shuffle(cardDeck); // shuffle the cards in the deck

But the method takes a vector<Card>&:

void deckOfCards::shuffle(vector<Card>& deck)

The compiler error messages are quite clear on this. I'll paraphrase the compiler as it talks to you.

Error:

[Error] no matching function for call to 'deckOfCards::shuffle(deckOfCards&)'

Paraphrased:

Hey, pal. You're trying to call a function called shuffle which apparently takes a single parameter of type reference-to-deckOfCards, but there is no such function.

Error:

[Note] candidate is:

In file included from main.cpp

[Note] void deckOfCards::shuffle(std::vector&)

Paraphrased:

I mean, maybe you meant this other function called shuffle, but that one takes a reference-tovector<something>.

Error:

[Note] no known conversion for argument 1 from 'deckOfCards' to 'std::vector&'

Which I'd be happy to call if I knew how to convert from a deckOfCards to a vector; but I don't. So I won't.

How to convert int to float in C?

I routinely multiply by 1.0 if I want floating point, it's easier than remembering the rules.

How to find files modified in last x minutes (find -mmin does not work as expected)

This may work for you. I used it for cleaning folders during deployments for deleting old deployment files.

clean_anyfolder() {
    local temp2="$1/**"; //PATH
    temp3=( $(ls -d $temp2 -t | grep "`date | awk '{print $2" "$3}'`") )
    j=0;
    while [ $j -lt ${#temp3[@]} ]
    do
            echo "to be removed ${temp3[$j]}"
            delete_file_or_folder ${temp3[$j]} 0 //DELETE HERE
        fi
        j=`expr $j + 1`
    done
}

How do I get LaTeX to hyphenate a word that contains a dash?

multi-disciplinary will not be hyphenated, as explained by kennytm. But multi-\-disciplinary has the same hyphenation opportunities that multidisciplinary has.

I admit that I don't know why this works. It is different from the behaviour described here (emphasis mine):

The command \- inserts a discretionary hyphen into a word. This also becomes the only point where hyphenation is allowed in this word.

Convert .cer certificate to .jks

Just to be sure that this is really the "conversion" you need, please note that jks files are keystores, a file format used to store more than one certificate and allows you to retrieve them programmatically using the Java security API, it's not a one-to-one conversion between equivalent formats.

So, if you just want to import that certificate in a new ad-hoc keystore you can do it with Keystore Explorer, a graphical tool. You'll be able to modify the keystore and the certificates contained therein like you would have done with the java terminal utilities like keytool (but in a more accessible way).

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="0.01" /> if you are targeting 2 decimal places :-).

Convert a string date into datetime in Oracle

Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') and all I received was 2017-02-20 the time disappeared

My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS') now the time doesn't disappear.

How to get input text length and validate user in javascript

JavaScript validation is not secure as anybody can change what your script does in the browser. Using it for enhancing the visual experience is ok though.

var textBox = document.getElementById("myTextBox");
var textLength = textBox.value.length;
if(textLength > 5)
{
    //red
    textBox.style.backgroundColor = "#FF0000";
}
else
{
    //green
    textBox.style.backgroundColor = "#00FF00";
}

htaccess redirect to https://www

I try first answer and it doesnt work... This work:

<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /

RewriteCond %{ENV:HTTPS} !=on
RewriteRule ^.*$ https://%{SERVER_NAME}%{REQUEST_URI} [R,L]

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

How do I set response headers in Flask?

You can do this pretty easily:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Look at flask.Response and flask.make_response()

But something tells me you have another problem, because the after_request should have handled it correctly too.

EDIT
I just noticed you are already using make_response which is one of the ways to do it. Like I said before, after_request should have worked as well. Try hitting the endpoint via curl and see what the headers are:

curl -i http://127.0.0.1:5000/your/endpoint

You should see

> curl -i 'http://127.0.0.1:5000/'
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 11
Access-Control-Allow-Origin: *
Server: Werkzeug/0.8.3 Python/2.7.5
Date: Tue, 16 Sep 2014 03:47:13 GMT

Noting the Access-Control-Allow-Origin header.

EDIT 2
As I suspected, you are getting a 500 so you are not setting the header like you thought. Try adding app.debug = True before you start the app and try again. You should get some output showing you the root cause of the problem.

For example:

@app.route("/")
def home():
    resp = flask.Response("Foo bar baz")
    user.weapon = boomerang
    resp.headers['Access-Control-Allow-Origin'] = '*'
    return resp

Gives a nicely formatted html error page, with this at the bottom (helpful for curl command)

Traceback (most recent call last):
...
  File "/private/tmp/min.py", line 8, in home
    user.weapon = boomerang
NameError: global name 'boomerang' is not defined

Angular js init ng-model from default values

I tried what @Mark Rajcok suggested. Its working for String values (Visa-4242). Please refer this fiddle.

From the fiddle:

The same thing that is done in the fiddle can be done using ng-repeat, which everybody could recommend. But after reading the answer given by @Mark Rajcok, i just wanted to try the same for a form with array of profiles. Things work well untill i have the $scope.profiles = [{},{}]; code in the controller. If i remove this code, im getting errors. But in normal scenarios i cant print $scope.profiles = [{},{}]; as i print or echo html from the server. Will it be possible to execute the above, in a similar fashion as @Mark Rajcok did for the string values like <input name="card[description]" ng-model="card.description" ng-init="card.description='Visa-4242'">, without having to echo the JavaScript part from the server.

Write HTML to string

return string.Format(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.01//EN""      ""http://www.w3.org/TR/html4/strict.dtd"">
<html>
<title>{0}</title>
<link rel=""stylesheet"" type=""text/css"" href=""style.css"">
</head>
<body>
", title);

Set field value with reflection

You can try this:

static class Student {
    private int age;
    private int number;

    public Student(int age, int number) {
        this.age = age;
        this.number = number;
    }

    public Student() {
    }
}
public static void main(String[] args) throws IllegalAccessException, NoSuchFieldException {
    Student student1=new Student();
   // Class g=student1.getClass();
    Field[]fields=student1.getClass().getDeclaredFields();
    Field age=student1.getClass().getDeclaredField("age");
    age.setAccessible(true);
    age.setInt(student1,13);
    Field number=student1.getClass().getDeclaredField("number");
    number.setAccessible(true);
    number.setInt(student1,936);

    for (Field f:fields
         ) {
        f.setAccessible(true);

        System.out.println(f.getName()+" "+f.getInt(student1));

    }
}

}

Why do I have to "git push --set-upstream origin <branch>"?

The -u flag is specifying that you want to link your local branch to the upstream branch. This will also create an upstream branch if one does not exist. None of these answers cover how i do it (in complete form) so here it is:

git push -u origin <your-local-branch-name>

So if your local branch name is coffee

git push -u origin coffee

how to list all sub directories in a directory

show all directry and sub directories

def dir():

from glob import glob

dir = []

dir = glob("path")

def all_sub_dir(dir):
{

     for item in dir:

            {
                b = "{}\*".format(item)
                dir += glob(b)
            }
         print(dir)
}

docker build with --build-arg with multiple arguments

If you want to use environment variable during build. Lets say setting username and password.

username= Ubuntu
password= swed24sw

Dockerfile

FROM ubuntu:16.04
ARG SMB_PASS
ARG SMB_USER
# Creates a new User
RUN useradd -ms /bin/bash $SMB_USER
# Enters the password twice.
RUN echo "$SMB_PASS\n$SMB_PASS" | smbpasswd -a $SMB_USER

Terminal Command

docker build --build-arg SMB_PASS=swed24sw --build-arg SMB_USER=Ubuntu . -t IMAGE_TAG

SQL Server convert select a column and convert it to a string

Use simplest way of doing this-

SELECT GROUP_CONCAT(Column) from table

What is "pom" packaging in maven?

POM(Project Object Model) is nothing but the automation script for building the project,we can write the automation script in XML, the building script files are named diffrenetly in different Automation tools

like we call build.xml in ANT,pom.xml in MAVEN

MAVEN can packages jars,wars, ears and POM which new thing to all of us

if you want check WHAT IS POM.XML

Redirecting exec output to a buffer or file

After forking, use dup2(2) to duplicate the file's FD into stdout's FD, then exec.

Best way to get hostname with php

You could also use...

$hostname = getenv('HTTP_HOST');

When do you use Git rebase instead of Git merge?

When do I use git rebase? Almost never, because it rewrites history. git merge is almost always the preferable choice, because it respects what actually happened in your project.

Convert a Python list with strings all to lowercase or uppercase

If you are trying to convert all string to lowercase in the list, You can use pandas :

import pandas as pd

data = ['Study', 'Insights']

pd_d = list(pd.Series(data).str.lower())

output:

['study', 'insights']

How to vertically center an image inside of a div element in HTML using CSS?

Have you tried setting margin on the div? e.g.

div {
    padding: 25px, 0
}

for top and bottom. You may also be able to use a percentage:

div {
    padding: 25%, 0
}

How to get number of rows using SqlDataReader in C#

to complete of Pit answer and for better perfromance : get all in one query and use NextResult method.

using (var sqlCon = new SqlConnection("Server=127.0.0.1;Database=MyDb;User Id=Me;Password=glop;"))
{
    sqlCon.Open();
    var com = sqlCon.CreateCommand();
    com.CommandText = "select * from BigTable;select @@ROWCOUNT;";
    using (var reader = com.ExecuteReader())
    {
        while(reader.read()){
            //iterate code
        }
        int totalRow = 0 ;
        reader.NextResult(); // 
        if(reader.read()){
            totalRow = (int)reader[0];
        }
    }
    sqlCon.Close();
}

In SQL, how can you "group by" in ranges?

James Curran's answer was the most concise in my opinion, but the output wasn't correct. For SQL Server the simplest statement is as follows:

SELECT 
    [score range] = CAST((Score/10)*10 AS VARCHAR) + ' - ' + CAST((Score/10)*10+9 AS VARCHAR), 
    [number of occurrences] = COUNT(*)
FROM #Scores
GROUP BY Score/10
ORDER BY Score/10

This assumes a #Scores temporary table I used to test it, I just populated 100 rows with random number between 0 and 99.

SQL Server: Cannot insert an explicit value into a timestamp column

If you have a need to copy the exact same timestamp data, change the data type in the destination table from timestamp to binary(8) -- i used varbinary(8) and it worked fine.

This obviously breaks any timestamp functionality in the destination table, so make sure you're ok with that first.

Writing a new line to file in PHP (line feed)

Replace '\n' with "\n". The escape sequence is not recognized when you use '.

See the manual.

For the question of how to write line endings, see the note here. Basically, different operating systems have different conventions for line endings. Windows uses "\r\n", unix based operating systems use "\n". You should stick to one convention (I'd chose "\n") and open your file in binary mode (fopen should get "wb", not "w").

How can I remove Nan from list Python/NumPy

In your example 'nan' is a string so instead of using isnan() just check for the string

like this:

cleanedList = [x for x in countries if x != 'nan']

How can I set response header on express.js assets

@klode's answer is right.

However, you are supposed to set another response header to make your header accessible to others.


Example:

First, you add 'page-size' in response header

response.set('page-size', 20);

Then, all you need to do is expose your header

response.set('Access-Control-Expose-Headers', 'page-size')

SQL QUERY replace NULL value in a row with a value from the previous known value

I know it is a very old forum, but I came across this while troubleshooting my problem :) just realised that the other guys have given bit complex solution to the above problem. Please see my solution below:

DECLARE @A TABLE(ID INT, Val INT)

INSERT INTO @A(ID,Val) SELECT 1, 3
INSERT INTO @A(ID,Val) SELECT 2, NULL
INSERT INTO @A(ID,Val) SELECT 3, 5
INSERT INTO @A(ID,Val) SELECT 4, NULL
INSERT INTO @A(ID,Val) SELECT 5, NULL
INSERT INTO @A(ID,Val) SELECT 6, 2

UPDATE D
    SET D.VAL = E.VAL
    FROM (SELECT A.ID C_ID, MAX(B.ID) P_ID
          FROM  @A AS A
           JOIN @A AS B ON A.ID > B.ID
          WHERE A.Val IS NULL
            AND B.Val IS NOT NULL
          GROUP BY A.ID) AS C
    JOIN @A AS D ON C.C_ID = D.ID
    JOIN @A AS E ON C.P_ID = E.ID

SELECT * FROM @A

Hope this may help someone:)

Automatic date update in a cell when another cell's value changes (as calculated by a formula)

You could fill the dependend cell (D2) by a User Defined Function (VBA Macro Function) that takes the value of the C2-Cell as input parameter, returning the current date as ouput.

Having C2 as input parameter for the UDF in D2 tells Excel that it needs to reevaluate D2 everytime C2 changes (that is if auto-calculation of formulas is turned on for the workbook).

EDIT:

Here is some code:

For the UDF:

    Public Function UDF_Date(ByVal data) As Date

        UDF_Date = Now()

    End Function

As Formula in D2:

=UDF_Date(C2)

You will have to give the D2-Cell a Date-Time Format, or it will show a numeric representation of the date-value.

And you can expand the formula over the desired range by draging it if you keep the C2 reference in the D2-formula relative.

Note: This still might not be the ideal solution because every time Excel recalculates the workbook the date in D2 will be reset to the current value. To make D2 only reflect the last time C2 was changed there would have to be some kind of tracking of the past value(s) of C2. This could for example be implemented in the UDF by providing also the address alonside the value of the input parameter, storing the input parameters in a hidden sheet, and comparing them with the previous values everytime the UDF gets called.

Addendum:

Here is a sample implementation of an UDF that tracks the changes of the cell values and returns the date-time when the last changes was detected. When using it, please be aware that:

  • The usage of the UDF is the same as described above.

  • The UDF works only for single cell input ranges.

  • The cell values are tracked by storing the last value of cell and the date-time when the change was detected in the document properties of the workbook. If the formula is used over large datasets the size of the file might increase considerably as for every cell that is tracked by the formula the storage requirements increase (last value of cell + date of last change.) Also, maybe Excel is not capable of handling very large amounts of document properties and the code might brake at a certain point.

  • If the name of a worksheet is changed all the tracking information of the therein contained cells is lost.

  • The code might brake for cell-values for which conversion to string is non-deterministic.

  • The code below is not tested and should be regarded only as proof of concept. Use it at your own risk.

    Public Function UDF_Date(ByVal inData As Range) As Date
    
        Dim wb As Workbook
        Dim dProps As DocumentProperties
        Dim pValue As DocumentProperty
        Dim pDate As DocumentProperty
        Dim sName As String
        Dim sNameDate As String
    
        Dim bDate As Boolean
        Dim bValue As Boolean
        Dim bChanged As Boolean
    
        bDate = True
        bValue = True
    
        bChanged = False
    
    
        Dim sVal As String
        Dim dDate As Date
    
        sName = inData.Address & "_" & inData.Worksheet.Name
        sNameDate = sName & "_dat"
    
        sVal = CStr(inData.Value)
        dDate = Now()
    
        Set wb = inData.Worksheet.Parent
    
        Set dProps = wb.CustomDocumentProperties
    
    On Error Resume Next
    
        Set pValue = dProps.Item(sName)
    
        If Err.Number <> 0 Then
            bValue = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bValue Then
            bChanged = True
            Set pValue = dProps.Add(sName, False, msoPropertyTypeString, sVal)
        Else
            bChanged = pValue.Value <> sVal
            If bChanged Then
                pValue.Value = sVal
            End If
        End If
    
    On Error Resume Next
    
        Set pDate = dProps.Item(sNameDate)
    
        If Err.Number <> 0 Then
            bDate = False
            Err.Clear
        End If
    
    On Error GoTo 0
    
        If Not bDate Then
            Set pDate = dProps.Add(sNameDate, False, msoPropertyTypeDate, dDate)
        End If
    
        If bChanged Then
            pDate.Value = dDate
        Else
            dDate = pDate.Value
        End If
    
    
        UDF_Date = dDate
     End Function
    

Make the insertion of the date conditional upon the range.

This has an advantage of not changing the dates unless the content of the cell is changed, and it is in the range C2:C2, even if the sheet is closed and saved, it doesn't recalculate unless the adjacent cell changes.

Adapted from this tip and @Paul S answer

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim R1 As Range
 Dim R2 As Range
 Dim InRange As Boolean
    Set R1 = Range(Target.Address)
    Set R2 = Range("C2:C20")
    Set InterSectRange = Application.Intersect(R1, R2)

  InRange = Not InterSectRange Is Nothing
     Set InterSectRange = Nothing
   If InRange = True Then
     R1.Offset(0, 1).Value = Now()
   End If
     Set R1 = Nothing
     Set R2 = Nothing
 End Sub

"id cannot be resolved or is not a field" error?

select Project tab and click Build automatically so Build all option will be activated and then click on build all.and always start xml file name with lowercase.

Jquery onclick on div

Check out this fiddle ... you're doing it correctly. Make sure the id is content and also check to see there are no other elements with the same id. If there are multiple elements with the same id, it will bind to the first one. That might be why you arn't seeing it.

Specify multiple attribute selectors in CSS

Concatenate the attribute selectors:

input[name="Sex"][value="M"]

Exit from app when click button in android phonegap?

sorry i can't reply in comment. just FYI, these codes

if (navigator.app) {
navigator.app.exitApp();
}
else if (navigator.device) {
  navigator.device.exitApp();
}
else {
          window.close();
}

i confirm doesn't work. i use phonegap 6.0.5 and cordova 6.2.0

Can I have multiple primary keys in a single table?

Yes, Its possible in SQL, but we can't set more than one primary keys in MsAccess. Then, I don't know about the other databases.

CREATE TABLE CHAPTER (
    BOOK_ISBN VARCHAR(50) NOT NULL,
    IDX INT NOT NULL,
    TITLE VARCHAR(100) NOT NULL,
    NUM_OF_PAGES INT,
    PRIMARY KEY (BOOK_ISBN, IDX)
);

git stash -> merge stashed change with current changes

May be, it is not the very worst idea to merge (via difftool) from ... yes ... a branch!

> current_branch=$(git status | head -n1 | cut -d' ' -f3)
> stash_branch="$current_branch-stash-$(date +%yy%mm%dd-%Hh%M)"
> git stash branch $stash_branch
> git checkout $current_branch
> git difftool $stash_branch

Ignore .classpath and .project from Git

Use a .gitignore file. This allows you to ignore certain files. http://git-scm.com/docs/gitignore

Here's an example Eclipse one, which handles your classpath and project files: https://github.com/github/gitignore/blob/master/Global/Eclipse.gitignore

SQL Developer is returning only the date, not the time. How do I fix this?

Neither of these answers would work for me, not the Preferences NLS configuration option or the ALTER statement. This was the only approach that worked in my case:

dbms_session.set_nls('nls_date_format','''DD-MM-YYYY HH24:MI:SS''');

*added after the BEGIN statement

I am using PL/SQL Developer v9.03.1641

Hopefully this is of help to someone!

where is gacutil.exe?

gacutil comes with Visual Studio, not with VSTS. It is part of Windows SDK and can be download separately at http://www.microsoft.com/downloads/details.aspx?FamilyId=F26B1AA4-741A-433A-9BE5-FA919850BDBF&displaylang=en . This installation will have gacutil.exe included. But first check it here

C:\Program Files\Microsoft SDKs\Windows\v6.0A\bin

you might have it installed.

As @devi mentioned

If you decide to grab gacutil files from existing installation, note that from .NET 4.0 is three files: gacutil.exe gacutil.exe.config and 1033/gacutlrc.dll

A monad is just a monoid in the category of endofunctors, what's the problem?

The answers here do an excellent job in defining both monoids and monads, however, they still don't seem to answer the question:

And on a less important note, is this true and if so could you give an explanation (hopefully one that can be understood by someone who doesn't have much Haskell experience)?

The crux of the matter that is missing here, is the different notion of "monoid", the so-called categorification more precisely -- the one of monoid in a monoidal category. Sadly Mac Lane's book itself makes it very confusing:

All told, a monad in X is just a monoid in the category of endofunctors of X, with product × replaced by composition of endofunctors and unit set by the identity endofunctor.

Main confusion

Why is this confusing? Because it does not define what is "monoid in the category of endofunctors" of X. Instead, this sentence suggests taking a monoid inside the set of all endofunctors together with the functor composition as binary operation and the identity functor as a monoidal unit. Which works perfectly fine and turns into a monoid any subset of endofunctors that contains the identity functor and is closed under functor composition.

Yet this is not the correct interpretation, which the book fails to make clear at that stage. A Monad f is a fixed endofunctor, not a subset of endofunctors closed under composition. A common construction is to use f to generate a monoid by taking the set of all k-fold compositions f^k = f(f(...)) of f with itself, including k=0 that corresponds to the identity f^0 = id. And now the set S of all these powers for all k>=0 is indeed a monoid "with product × replaced by composition of endofunctors and unit set by the identity endofunctor".

And yet:

  • This monoid S can be defined for any functor f or even literally for any self-map of X. It is the monoid generated by f.
  • The monoidal structure of S given by the functor composition and the identity functor has nothing do with f being or not being a monad.

And to make things more confusing, the definition of "monoid in monoidal category" comes later in the book as you can see from the table of contents. And yet understanding this notion is absolutely critical to understanding the connection with monads.

(Strict) monoidal categories

Going to Chapter VII on Monoids (which comes later than Chapter VI on Monads), we find the definition of the so-called strict monoidal category as triple (B, *, e), where B is a category, *: B x B-> B a bifunctor (functor with respect to each component with other component fixed) and e is a unit object in B, satisfying the associativity and unit laws:

(a * b) * c = a * (b * c)
a * e = e * a = a

for any objects a,b,c of B, and the same identities for any morphisms a,b,c with e replaced by id_e, the identity morphism of e. It is now instructive to observe that in our case of interest, where B is the category of endofunctors of X with natural transformations as morphisms, * the functor composition and e the identity functor, all these laws are satisfied, as can be directly verified.

What comes after in the book is the definition of the "relaxed" monoidal category, where the laws only hold modulo some fixed natural transformations satisfying so-called coherence relations, which is however not important for our cases of the endofunctor categories.

Monoids in monoidal categories

Finally, in section 3 "Monoids" of Chapter VII, the actual definition is given:

A monoid c in a monoidal category (B, *, e) is an object of B with two arrows (morphisms)

mu: c * c -> c
nu: e -> c

making 3 diagrams commutative. Recall that in our case, these are morphisms in the category of endofunctors, which are natural transformations corresponding to precisely join and return for a monad. The connection becomes even clearer when we make the composition * more explicit, replacing c * c by c^2, where c is our monad.

Finally, notice that the 3 commutative diagrams (in the definition of a monoid in monoidal category) are written for general (non-strict) monoidal categories, while in our case all natural transformations arising as part of the monoidal category are actually identities. That will make the diagrams exactly the same as the ones in the definition of a monad, making the correspondence complete.

Conclusion

In summary, any monad is by definition an endofunctor, hence an object in the category of endofunctors, where the monadic join and return operators satisfy the definition of a monoid in that particular (strict) monoidal category. Vice versa, any monoid in the monoidal category of endofunctors is by definition a triple (c, mu, nu) consisting of an object and two arrows, e.g. natural transformations in our case, satisfying the same laws as a monad.

Finally, note the key difference between the (classical) monoids and the more general monoids in monoidal categories. The two arrows mu and nu above are not anymore a binary operation and a unit in a set. Instead, you have one fixed endofunctor c. The functor composition * and the identity functor alone do not provide the complete structure needed for the monad, despite that confusing remark in the book.

Another approach would be to compare with the standard monoid C of all self-maps of a set A, where the binary operation is the composition, that can be seen to map the standard cartesian product C x C into C. Passing to the categorified monoid, we are replacing the cartesian product x with the functor composition *, and the binary operation gets replaced with the natural transformation mu from c * c to c, that is a collection of the join operators

join: c(c(T))->c(T)

for every object T (type in programming). And the identity elements in classical monoids, which can be identified with images of maps from a fixed one-point-set, get replaced with the collection of the return operators

return: T->c(T) 

But now there are no more cartesian products, so no pairs of elements and thus no binary operations.

Footnotes for tables in LaTeX

What @dmckee said.

It's not difficult to write your own bespoke footnote-queuing code. What you need to do is:

  1. Write code to queue Latex code — like a hook in emacs: very standard technique, if not every Latex hacker can actually do this right;
  2. Temporarily redefine \footnote to add a footnote macro to your queue;
  3. Ensure that the hook gets called when the table/figure exits and we return to regular vertical mode.

If this is interesting, I show some code that does this.

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

Questions every good PHP Developer should be able to answer

Explain why the following code displays 2.5 instead of 3:

$a = 012;
echo $a / 4;

Answer: When a number is preceded by a 0 in PHP, the number is treated as an octal number (base-8). Therefore the octal number 012 is equal to the decimal number 10.

Animate element transform rotate

Ryley's answer is great, but I have text within the element. In order to rotate the text along with everything else, I used the border-spacing property instead of text-indent.

Also, to clarify a bit, in the element's style, set your initial value:

#foo {
    border-spacing: 0px;
}

Then in the animate chunk, your final value:

$('#foo').animate({  borderSpacing: -90 }, {
    step: function(now,fx) {
      $(this).css('transform','rotate('+now+'deg)');  
    },
    duration:'slow'
},'linear');

In my case, it rotates 90 degrees counter-clockwise.

Here is the live demo.

PHP Date Time Current Time Add Minutes

In addition to Khriz's answer.

If you need to add 5 minutes to the current time in Mysql format you can do:

$cur_time=date("Y-m-d H:i:s");
$duration='+5 minutes';
echo date('Y-m-d H:i:s', strtotime($duration, strtotime($cur_time)));

How to get all count of mongoose model?

Using mongoose.js you can count documents,

  • count all
const count = await Schema.countDocuments();
  • count specific
const count = await Schema.countDocuments({ key: value });

Reading all files in a directory, store them in objects, and send the object

If you have Node.js 8 or later, you can use the new util.promisify. (I'm marking as optional the parts of the code that have to do with reformatting as an object, which the original post requested.)

  const fs = require('fs');
  const { promisify } = require('util');

  let files; // optional
  promisify(fs.readdir)(directory).then((filenames) => {
    files = filenames; // optional
    return Promise.all(filenames.map((filename) => {
      return promisify(fs.readFile)(directory + filename, {encoding: 'utf8'});
    }));
  }).then((strArr) => {
    // optional:
    const data = {};
    strArr.forEach((str, i) => {
      data[files[i]] = str;
    });
    // send data here
  }).catch((err) => {
    console.log(err);
  });

How to use execvp()

The first argument is the file you wish to execute, and the second argument is an array of null-terminated strings that represent the appropriate arguments to the file as specified in the man page.

For example:

char *cmd = "ls";
char *argv[3];
argv[0] = "ls";
argv[1] = "-la";
argv[2] = NULL;

execvp(cmd, argv); //This will run "ls -la" as if it were a command

jquery get height of iframe content when loaded

simple one-liner starts with a default min-height and increases to contents size.

_x000D_
_x000D_
<iframe src="http://url.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
_x000D_
_x000D_
_x000D_

startForeground fail after upgrade to Android 8.1

Java Solution (Android 9.0, API 28)

In your Service class, add this:

@Override
public void onCreate(){
    super.onCreate();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
        startMyOwnForeground();
    else
        startForeground(1, new Notification());
}

private void startMyOwnForeground(){
    String NOTIFICATION_CHANNEL_ID = "com.example.simpleapp";
    String channelName = "My Background Service";
    NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
    chan.setLightColor(Color.BLUE);
    chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    assert manager != null;
    manager.createNotificationChannel(chan);

    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
    Notification notification = notificationBuilder.setOngoing(true)
            .setSmallIcon(R.drawable.icon_1)
            .setContentTitle("App is running in background")
            .setPriority(NotificationManager.IMPORTANCE_MIN)
            .setCategory(Notification.CATEGORY_SERVICE)
            .build();
    startForeground(2, notification);
}

UPDATE: ANDROID 9.0 PIE (API 28)

Add this permission to your AndroidManifest.xml file:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />

How can I rename column in laravel using migration?

The above answer is great or if it will not hurt you, just rollback the migration and change the name and run migration again.

 php artisan migrate:rollback

Android: Reverse geocoding - getFromLocation

It looks like there's two things happening here.

1) You've missed the new keyword from before calling the constructor.

2) The parameter you're passing in to the Geocoder constructor is incorrect. You're passing in a Locale where it's expecting a Context.

There are two Geocoder constructors, both of which require a Context, and one also taking a Locale:

Geocoder(Context context, Locale locale)
Geocoder(Context context)

Solution

Modify your code to pass in a valid Context and include new and you should be good to go.

Geocoder myLocation = new Geocoder(getApplicationContext(), Locale.getDefault());   
List<Address> myList = myLocation.getFromLocation(latPoint, lngPoint, 1);

Note

If you're still having problems it may be a permissioning issue. Geocoding implicitly uses the Internet to perform the lookups, so your application will require an INTERNET uses-permission tag in your manifest.

Add the following uses-permission node within the manifest node of your manifest.

<uses-permission android:name="android.permission.INTERNET" />

JQuery Find #ID, RemoveClass and AddClass

jQuery('#testID2').find('.test2').replaceWith('.test3');

Semantically, you are selecting the element with the ID testID2, then you are looking for any descendent elements with the class test2 (does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3) that also do not exist.

You need to do this:

jQuery('#testID2').addClass('test3').removeClass('test2');

This selects the element with the ID testID2, then adds the class test3 to it. Last, it removes the class test2 from that element.

matplotlib: plot multiple columns of pandas data frame on the bar chart

Although the accepted answer works fine, since v0.21.0rc1 it gives a warning

UserWarning: Pandas doesn't allow columns to be created via a new attribute name

Instead, one can do

df[["X", "A", "B", "C"]].plot(x="X", kind="bar")

Removing multiple keys from a dictionary safely

Why not like this:

entries = ('a', 'b', 'c')
the_dict = {'b': 'foo'}

def entries_to_remove(entries, the_dict):
    for key in entries:
        if key in the_dict:
            del the_dict[key]

A more compact version was provided by mattbornski using dict.pop()

Python vs Cpython

So what is CPython?

CPython is the original Python implementation. It is the implementation you download from Python.org. People call it CPython to distinguish it from other, later, Python implementations, and to distinguish the implementation of the language engine from the Python programming language itself.

The latter part is where your confusion comes from; you need to keep Python-the-language separate from whatever runs the Python code.

CPython happens to be implemented in C. That is just an implementation detail, really. CPython compiles your Python code into bytecode (transparently) and interprets that bytecode in a evaluation loop.

CPython is also the first to implement new features; Python-the-language development uses CPython as the base; other implementations follow.

What about Jython, etc.?

Jython, IronPython and PyPy are the current "other" implementations of the Python programming language; these are implemented in Java, C# and RPython (a subset of Python), respectively. Jython compiles your Python code to Java bytecode, so your Python code can run on the JVM. IronPython lets you run Python on the Microsoft CLR. And PyPy, being implemented in (a subset of) Python, lets you run Python code faster than CPython, which rightly should blow your mind. :-)

Actually compiling to C

So CPython does not translate your Python code to C by itself. Instead, it runs an interpreter loop. There is a project that does translate Python-ish code to C, and that is called Cython. Cython adds a few extensions to the Python language, and lets you compile your code to C extensions, code that plugs into the CPython interpreter.

How to normalize a signal to zero mean and unit variance?

You can determine the mean of the signal, and just subtract that value from all the entries. That will give you a zero mean result.

To get unit variance, determine the standard deviation of the signal, and divide all entries by that value.

Difference between static and shared libraries?

Static libraries are compiled as part of an application, whereas shared libraries are not. When you distribute an application that depends on shared libaries, the libraries, eg. dll's on MS Windows need to be installed.

The advantage of static libraries is that there are no dependencies required for the user running the application - e.g. they don't have to upgrade their DLL of whatever. The disadvantage is that your application is larger in size because you are shipping it with all the libraries it needs.

As well as leading to smaller applications, shared libraries offer the user the ability to use their own, perhaps better version of the libraries rather than relying on one that's part of the application

image.onload event and browser cache

As you're generating the image dynamically, set the onload property before the src.

var img = new Image();
img.onload = function () {
   alert("image is loaded");
}
img.src = "img.jpg";

Fiddle - tested on latest Firefox and Chrome releases.

You can also use the answer in this post, which I adapted for a single dynamically generated image:

var img = new Image();
// 'load' event
$(img).on('load', function() {
  alert("image is loaded");
});
img.src = "img.jpg";

Fiddle

How to let an ASMX file output JSON

Alternative: Use a generic HTTP handler (.ashx) and use your favorite json library to manually serialize and deserialize your JSON.

I've found that complete control over the handling of a request and generating a response beats anything else .NET offers for simple, RESTful web services.

Not Able To Debug App In Android Studio

I did clean build using below command.. Surprisingly worked.

sh gradlew clean build

Hopefully someone get help!

Check the current number of connections to MongoDb

db.runCommand( { "connPoolStats" : 1 } )

{
    "numClientConnections" : 0,
    "numAScopedConnections" : 0,
    "totalInUse" : 0,
    "totalAvailable" : 0,
    "totalCreated" : 0,
    "hosts" : {

    },
    "replicaSets" : {

    },
    "ok" : 1
}

How do I find out which computer is the domain controller in Windows programmatically?

In C#/.NET 3.5 you could write a little program to do:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    string controller = context.ConnectedServer;
    Console.WriteLine( "Domain Controller:" + controller );
} 

This will list all the users in the current domain:

using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
{
    using (UserPrincipal searchPrincipal = new UserPrincipal(context))
    {
       using (PrincipalSearcher searcher = new PrincipalSearcher(searchPrincipal))
       {
           foreach (UserPrincipal principal in searcher.FindAll())
           {
               Console.WriteLine( principal.SamAccountName);
           }
       }
    }
}

No value accessor for form control

If you must use the label for the formControl. Like the Ant Design Checkbox. It may throw this error while running tests. You can use ngDefaultControl

<label nz-checkbox formControlName="isEnabled" ngDefaultControl>
    Hello
</label>

<nz-switch nzSize="small" formControlName="mandatory" ngDefaultControl></nz-switch>

How to set background image in Java?

The answer will vary slightly depending on whether the application or applet is using AWT or Swing.

(Basically, classes that start with J such as JApplet and JFrame are Swing, and Applet and Frame are AWT.)

In either case, the basic steps would be:

  1. Draw or load an image into a Image object.
  2. Draw the background image in the painting event of the Component you want to draw the background in.

Step 1. Loading the image can be either by using the Toolkit class or by the ImageIO class.

The Toolkit.createImage method can be used to load an Image from a location specified in a String:

Image img = Toolkit.getDefaultToolkit().createImage("background.jpg");

Similarly, ImageIO can be used:

Image img = ImageIO.read(new File("background.jpg");

Step 2. The painting method for the Component that should get the background will need to be overridden and paint the Image onto the component.

For AWT, the method to override is the paint method, and use the drawImage method of the Graphics object that is handed into the paint method:

public void paint(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}

For Swing, the method to override is the paintComponent method of the JComponent, and draw the Image as with what was done in AWT.

public void paintComponent(Graphics g)
{
    // Draw the previously loaded image to Component.
    g.drawImage(img, 0, 0, null);

    // Draw sprites, and other things.
    // ....
}

Simple Component Example

Here's a Panel which loads an image file when instantiated, and draws that image on itself:

class BackgroundPanel extends Panel
{
    // The Image to store the background image in.
    Image img;
    public BackgroundPanel()
    {
        // Loads the background image and stores in img object.
        img = Toolkit.getDefaultToolkit().createImage("background.jpg");
    }

    public void paint(Graphics g)
    {
        // Draws the img to the BackgroundPanel.
        g.drawImage(img, 0, 0, null);
    }
}

For more information on painting:

What does body-parser do with express?

Keep it simple :

  • if you used post so you will need the body of the request, so you will need body-parser.

  • No need to install body-parser with express, but you have to use it if you will receive post request.

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

    { extended: false } false meaning, you do not have nested data inside your body object.

    Note that: the request data embedded within the request as a body Object.

Use Awk to extract substring

You just want to set the field separator as . using the -F option and print the first field:

$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}'
aaa0

Same thing but using cut:

$ echo aaa0.bbb.ccc | cut -d'.' -f1
aaa0

Or with sed:

$ echo aaa0.bbb.ccc | sed 's/[.].*//'
aaa0

Even grep:

$ echo aaa0.bbb.ccc | grep -o '^[^.]*'
aaa0

Any good boolean expression simplifiers out there?

Try Logic Friday 1 It includes tools from the Univerity of California (Espresso and misII) and makes them usable with a GUI. You can enter boolean equations and truth tables as desired. It also features a graphical gate diagram input and output.

The minimization can be carried out two-level or multi-level. The two-level form yields a minimized sum of products. The multi-level form creates a circuit composed out of logical gates. The types of gates can be restricted by the user.

Your expression simplifies to C.

Python list subtraction operation

For many use cases, the answer you want is:

ys = set(y)
[item for item in x if item not in ys]

This is a hybrid between aaronasterling's answer and quantumSoup's answer.

aaronasterling's version does len(y) item comparisons for each element in x, so it takes quadratic time. quantumSoup's version uses sets, so it does a single constant-time set lookup for each element in x—but, because it converts both x and y into sets, it loses the order of your elements.

By converting only y into a set, and iterating x in order, you get the best of both worlds—linear time, and order preservation.*


However, this still has a problem from quantumSoup's version: It requires your elements to be hashable. That's pretty much built into the nature of sets.** If you're trying to, e.g., subtract a list of dicts from another list of dicts, but the list to subtract is large, what do you do?

If you can decorate your values in some way that they're hashable, that solves the problem. For example, with a flat dictionary whose values are themselves hashable:

ys = {tuple(item.items()) for item in y}
[item for item in x if tuple(item.items()) not in ys]

If your types are a bit more complicated (e.g., often you're dealing with JSON-compatible values, which are hashable, or lists or dicts whose values are recursively the same type), you can still use this solution. But some types just can't be converted into anything hashable.


If your items aren't, and can't be made, hashable, but they are comparable, you can at least get log-linear time (O(N*log M), which is a lot better than the O(N*M) time of the list solution, but not as good as the O(N+M) time of the set solution) by sorting and using bisect:

ys = sorted(y)
def bisect_contains(seq, item):
    index = bisect.bisect(seq, item)
    return index < len(seq) and seq[index] == item
[item for item in x if bisect_contains(ys, item)]

If your items are neither hashable nor comparable, then you're stuck with the quadratic solution.


* Note that you could also do this by using a pair of OrderedSet objects, for which you can find recipes and third-party modules. But I think this is simpler.

** The reason set lookups are constant time is that all it has to do is hash the value and see if there's an entry for that hash. If it can't hash the value, this won't work.

How do I load external fonts into an HTML document?

I did not see any reference to Raphael.js. So I thought I'd include it here. Raphael.js is backwards compatible all the way back to IE5 and a very early Firefox as well as all of the rest of the browsers. It uses SVG when it can and VML when it can not. What you do with it is to draw onto a canvas. Some browsers will even let you select the text that is generated. Raphael.js can be found here:

http://raphaeljs.com/

It can be as simple as creating your paper drawing area, specifying the font, font-weight, size, etc... and then telling it to put your string of text onto the paper. I am not sure if it gets around the licensing issues or not but it is drawing the text so I'm fairly certain it does circumvent the licensing issues. But check with your lawyer to be sure. :-)

How to generate the whole database script in MySQL Workbench?

Using Windows 10 and MySql Workbench 8.0

  1. Go to Server tab
  2. Go to Database Export

This opens up something like this

MySQL Workbench

  1. Select the schema to export in the Tables to export
  2. Click the button Start Export

Border Radius of Table is not working

<div class="leads-search-table">
                    <div class="row col-md-6 col-md-offset-2 custyle">
                    <table class="table custab bordered">
                    <thead>

                        <tr>
                            <th>ID</th>
                            <th>Title</th>
                            <th>Parent ID</th>
                            <th class="text-center">Action</th>
                        </tr>
                    </thead>
                            <tr>
                                <td>1</td>
                                <td>News</td>
                                <td>News Cate</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                            <tr>
                                <td>2</td>
                                <td>Products</td>
                                <td>Main Products</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                            <tr>
                                <td>3</td>
                                <td>Blogs</td>
                                <td>Parent Blogs</td>
                                <td class="text-center"><a class='btn btn-info btn-xs' href="#"><span class="glyphicon glyphicon-edit"></span> Edit</a> <a href="#" class="btn btn-danger btn-xs"><span class="glyphicon glyphicon-remove"></span> Del</a></td>
                            </tr>
                    </table>
                    </div>
                </div>

Css

.custab{
    border: 1px solid #ccc;
    margin: 5% 0;
    transition: 0.5s;
    background-color: #fff;
    -webkit-border-radius:4px;
    border-radius: 4px;
    border-collapse: separate;
}

Regex in JavaScript for validating decimal numbers

as compared from the answer gven by mic... it doesnt validate anything in some of the platforms which i work upon... to be precise it doesnt actually work out in Dream Viewer..

hereby.. i re-write it again..which will work on any platform.. "^[0-9]+(.[0-9]{1,2})?$".. thnkss..

Check if enum exists in Java

Just use valueOf() method. If the value doesn't exist, it throws IllegalArgumentException and you can catch it like that:

      boolean isSettingCodeValid = true;

       try {
            SettingCode.valueOf(settingCode.toUpperCase());
        } catch (IllegalArgumentException e) {
            // throw custom exception or change the isSettingCodeValid value
            isSettingCodeValid = false;
        }

How to fetch Java version using single line command in Linux

  1. Redirect stderr to stdout.
  2. Get first line
  3. Filter the version number.

    java -version 2>&1 | head -n 1 | awk -F '"' '{print $2}'
    

A general tree implementation?

anytree

I recommend https://pypi.python.org/pypi/anytree

Example

from anytree import Node, RenderTree

udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)

print(udo)
Node('/Udo')
print(joe)
Node('/Udo/Dan/Joe')

for pre, fill, node in RenderTree(udo):
    print("%s%s" % (pre, node.name))
Udo
+-- Marc
¦   +-- Lian
+-- Dan
    +-- Jet
    +-- Jan
    +-- Joe

print(dan.children)
(Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe'))

Features

anytree has also a powerful API with:

  • simple tree creation
  • simple tree modification
  • pre-order tree iteration
  • post-order tree iteration
  • resolve relative and absolute node paths
  • walking from one node to an other.
  • tree rendering (see example above)
  • node attach/detach hookups

Eclipse JPA Project Change Event Handler (waiting)

I have disabled (unchecked) the JPA validator.

Now whenever I save the file, it shows only one task for JPA Project Change Event Handler and only 2 or 3 for JPA Java Change Event Handler.

And most important, the UI Hang issue is resolved.

Please refer following screen shot for the setting I have made :

enter image description here

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

This one line answer comes from someone related Ask Ubuntu Q&A:

[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :
#     This is useful boilerplate code for shell scripts.  Put it at the top  of
#     the  shell script you want to lock and it'll automatically lock itself on
#     the first run.  If the env var $FLOCKER is not set to  the  shell  script
#     that  is being run, then execute flock and grab an exclusive non-blocking
#     lock (using the script itself as the lock file) before re-execing  itself
#     with  the right arguments.  It also sets the FLOCKER env var to the right
#     value so it doesn't run again.

How to achieve pagination/table layout with Angular.js?

here i have solve my angularJS pagination issue with some more tweak in server side + view end you can check the code it will be more efficient. all i have to do is put two value start number and end number , it will represent index of the returned json array.

here is the angular

var refresh = function () {
    $('.loading').show();
    $http.get('http://put.php?OutputType=JSON&r=all&s=' + $scope.CountStart + '&l=' + $scope.CountEnd).success(function (response) {
        $scope.devices = response;


        $('.loading').hide();
    });
};

if you see carefully $scope.CountStart and $scope.CountStart are two argument i am passing with the api

here is the code for next button

$scope.nextPage = function () {
    $('.loading').css("display", "block");
    $scope.nextPageDisabled();


    if ($scope.currentPage >= 0) {
        $scope.currentPage++;

        $scope.CountStart = $scope.CountStart + $scope.DevicePerPage;
        $scope.CountEnd = $scope.CountEnd + $scope.DevicePerPage;
        refresh();
    }
};

here is the code for previous button

$scope.prevPage = function () {
    $('.loading').css("display", "block");
    $scope.nextPageDisabled();

    if ($scope.currentPage > 0) {
        $scope.currentPage--;

        $scope.CountStart = $scope.CountStart - $scope.DevicePerPage;
        $scope.CountEnd = $scope.CountEnd - $scope.DevicePerPage;

        refresh();

    }
};

if the page number is zero my previous button will be deactivated

   $scope.nextPageDisabled = function () {

    console.log($scope.currentPage);

    if ($scope.currentPage === 0) {
        return false;
    } else {
        return true;
    }
};

Regular expression for decimal number

There is an alternative approach, which does not have I18n problems (allowing ',' or '.' but not both): Decimal.TryParse.

Just try converting, ignoring the value.

bool IsDecimalFormat(string input) {
  Decimal dummy;
  return Decimal.TryParse(input, out dummy);
}

This is significantly faster than using a regular expression, see below.

(The overload of Decimal.TryParse can be used for finer control.)


Performance test results: Decimal.TryParse: 0.10277ms, Regex: 0.49143ms

Code (PerformanceHelper.Run is a helper than runs the delegate for passed iteration count and returns the average TimeSpan.):

using System;
using System.Text.RegularExpressions;
using DotNetUtils.Diagnostics;

class Program {
    static private readonly string[] TestData = new string[] {
        "10.0",
        "10,0",
        "0.1",
        ".1",
        "Snafu",
        new string('x', 10000),
        new string('2', 10000),
        new string('0', 10000)
    };

    static void Main(string[] args) {
        Action parser = () => {
            int n = TestData.Length;
            int count = 0;
            for (int i = 0; i < n; ++i) {
                decimal dummy;
                count += Decimal.TryParse(TestData[i], out dummy) ? 1 : 0;
            }
        };
        Regex decimalRegex = new Regex(@"^[0-9]([\.\,][0-9]{1,3})?$");
        Action regex = () => {
            int n = TestData.Length;
            int count = 0;
            for (int i = 0; i < n; ++i) {
                count += decimalRegex.IsMatch(TestData[i]) ? 1 : 0;
            }
        };

        var paserTotal = 0.0;
        var regexTotal = 0.0;
        var runCount = 10;
        for (int run = 1; run <= runCount; ++run) {
            var parserTime = PerformanceHelper.Run(10000, parser);
            var regexTime = PerformanceHelper.Run(10000, regex);

            Console.WriteLine("Run #{2}: Decimal.TryParse: {0}ms, Regex: {1}ms",
                              parserTime.TotalMilliseconds, 
                              regexTime.TotalMilliseconds,
                              run);
            paserTotal += parserTime.TotalMilliseconds;
            regexTotal += regexTime.TotalMilliseconds;
        }

        Console.WriteLine("Overall averages: Decimal.TryParse: {0}ms, Regex: {1}ms",
                          paserTotal/runCount,
                          regexTotal/runCount);
    }
}

How to add a class to a given element?

Add Class

  • Cross Compatible

    In the following example we add a classname to the <body> element. This is IE-8 compatible.

    var a = document.body;
    a.classList ? a.classList.add('classname') : a.className += ' classname';
    

    This is shorthand for the following..

    var a = document.body;
    if (a.classList) {
        a.classList.add('wait');
    } else {
        a.className += ' wait';
    }
    

  • Performance

    If your more concerned with performance over cross-compatibility you can shorten it to the following which is 4% faster.

    var z = document.body;
    document.body.classList.add('wait');
    

  • Convenience

    Alternatively you could use jQuery but the resulting performance is significantly slower. 94% slower according to jsPerf

    $('body').addClass('wait');
    


Removing the class

  • Performance

    Using jQuery selectively is the best method for removing a class if your concerned with performance

    var a = document.body, c = ' classname';
    $(a).removeClass(c);
    

  • Without jQuery it's 32% slower

    var a = document.body, c = ' classname';
    a.className = a.className.replace( c, '' );
    a.className = a.className + c;
    

References

  1. jsPerf Test Case: Adding a Class
  2. jsPerf Test Case: Removing a Class

Using Prototype

Element("document.body").ClassNames.add("classname")
Element("document.body").ClassNames.remove("classname")
Element("document.body").ClassNames.set("classname")

Using YUI

YAHOO.util.Dom.hasClass(document.body,"classname")
YAHOO.util.Dom.addClass(document.body,"classname")
YAHOO.util.Dom.removeClass(document.body,"classname")

When should I use the new keyword in C++?

The simple answer is yes - new() creates an object on the heap (with the unfortunate side effect that you have to manage its lifetime (by explicitly calling delete on it), whereas the second form creates an object in the stack in the current scope and that object will be destroyed when it goes out of scope.

How to fast get Hardware-ID in C#?

For more details refer to this link

The following code will give you CPU ID:

namespace required System.Management

var mbs = new ManagementObjectSearcher("Select ProcessorId From Win32_processor");
ManagementObjectCollection mbsList = mbs.Get();
string id = "";
foreach (ManagementObject mo in mbsList)
{
    id = mo["ProcessorId"].ToString();
    break;
}

For Hard disk ID and motherboard id details refer this-link

To speed up this procedure, make sure you don't use SELECT *, but only select what you really need. Use SELECT * only during development when you try to find out what you need to use, because then the query will take much longer to complete.

How to avoid 'undefined index' errors?

You could try using a nice little function that will return the value if it exists or an empty string if not. This is what I use:

function arrayValueForKey($arrayName, $key) {
   if (isset($GLOBALS[$arrayName]) && isset($GLOBALS[$arrayName][$key])) {
      return $GLOBALS[$variable][$key];
   } else {
      return '';
   }
}

Then you can use it like this:

echo ' Values: ' . arrayValueForKey('output', 'admin_link') 
                 . arrayValueForKey('output', 'update_frequency');

And it won't throw up any errors!

Hope this helps!

SQL: How To Select Earliest Row

Simply use min()

SELECT company, workflow, MIN(date) 
FROM workflowTable 
GROUP BY company, workflow

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

What is Bootstrap?

It is an HTML, CSS, and JavaScript open-source framework (initially created by Twitter) that you can use as a basis for creating web sites or web applications.

Update

The official bootstrap website is updated and includes a clear definition.

"Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web."

"Designed and built with all the love in the world by @mdo and @fat."

How can I set the form action through JavaScript?

Setting form action after selection of option using JavaScript

<script>
    function onSelectedOption(sel) {
        if ((sel.selectedIndex) == 0) {
            document.getElementById("edit").action =
            "http://www.example.co.uk/index.php";
            document.getElementById("edit").submit();
        }
        else
        {
            document.getElementById("edit").action =
            "http://www.example.co.uk/different.php";
            document.getElementById("edit").submit();
        }
    }
</script>

<form name="edit" id="edit" action="" method="GET">
    <input type="hidden" name="id" value="{ID}" />
</form>

<select name="option" id="option" onchange="onSelectedOption(this);">
    <option name="contactBuyer">Edit item</option>
    <option name="relist">End listing</option>
</select>

Python, how to check if a result set is empty?

MySQLdb will not raise an exception if the result set is empty. Additionally cursor.execute() function will return a long value which is number of rows in the fetched result set. So if you want to check for empty results, your code can be re-written as

rows_count = cursor.execute(query_sql)
if rows_count > 0:
     rs = cursor.fetchall()
else:
     // handle empty result set

How to use variables in a command in sed?

This may also can help

input="inputtext"
output="outputtext"
sed "s/$input/${output}/" inputfile > outputfile

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

It looks like the problem had been resolved with the latest Chrome update... I'm running the Chrome Version 36.0.1964.4 dev-m.

I was limited too warning the user from closing print preview window by doing the following:

if(navigator.userAgent.toLowerCase().indexOf('chrome') > -1){   // Chrome Browser Detected?
    window.PPClose = false;                                     // Clear Close Flag
    window.onbeforeunload = function(){                         // Before Window Close Event
        if(window.PPClose === false){                           // Close not OK?
            return 'Leaving this page will block the parent window!\nPlease select "Stay on this Page option" and use the\nCancel button instead to close the Print Preview Window.\n';
        }
    }                   
    window.print();                                             // Print preview
    window.PPClose = true;                                      // Set Close Flag to OK.
}

Now the warning is no longer coming up after the Chrome update.

Codeigniter : calling a method of one controller from other

You can use the redirect() function. Like this

class ControllerA extends CI_Controller{
    public function MethodA(){
       redirect("ControllerB/MethodB");
    }
}

How to set enum to null

would it not be better to explicitly assign value 0 to None constant? Why?

Because default enum value is equal to 0, if You would call default(Color) it would print None.

Because it is at first position, assigning literal value 0 to any other constant would change that behaviour, also changing order of occurrence would change output of default(Color) (https://stackoverflow.com/a/4967673/8611327)

C++ code file extension? .cc vs .cpp

As with most style conventions, there are only two things that matter:

  1. Be consistent in what you use, wherever possible.
  2. Don't design anything that depends on a specific choice being used.

Those may seem to contradict, but they each have value for their own reasons.

How to remove/ignore :hover css style on touch devices

try this:

@media (hover:<s>on-demand</s>) {
    button:hover {
        background-color: #color-when-NOT-touch-device;
    }
}

UPDATE: unfortunately W3C has removed this property from the specs (https://github.com/w3c/csswg-drafts/commit/2078b46218f7462735bb0b5107c9a3e84fb4c4b1).

How to make (link)button function as hyperlink?

There is a middle way. If you want a HTML control but you need to access it server side you can simply add the runat="server" attribute:

<a runat="server" Id="lnkBack">Back</a>

You can then alter the href server side using Attributes

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
       lnkBack.Attributes.Add("href", url);
    }
}

resulting in:

<a id="ctl00_ctl00_mainContentPlaceHolder_contentPlaceHolder_lnkBack" 
      href="url.aspx">Back</a>

Meaning of *& and **& in C++

Typically, you can read the declaration of the variable from right to left. Therefore in the case of int *ptr; , it means that you have a Pointer * to an Integer variable int. Also when it's declared int **ptr2;, it is a Pointer variable * to a Pointer variable * pointing to an Integer variable int , which is the same as "(int *)* ptr2;"

Now, following the syntax by declaring int*& rPtr;, we say it's a Reference & to a Pointer * that points to a variable of type int. Finally, you can apply again this approach also for int**& rPtr2; concluding that it signifies a Reference & to a Pointer * to a Pointer * to an Integer int.

Call of overloaded function is ambiguous

Cast the value so the compiler knows which function to call:

p.setval(static_cast<const char *>( 0 ));

Note, that you have a segmentation fault in your code after you get it to compile (depending on which function you really wanted to call).

IsNullOrEmpty with Object

IsNullOrEmpty is essentially shorthand for the following:

return str == null || str == String.Empty;

So, no there is no function that just checks for nulls because it would be too simple. obj != null is the correct way. But you can create such a (superfluous) function yourself using the following extension:

public bool IsNull(this object obj)
{
    return obj == null;
}

Then you are able to run anyObject.IsNull().

UnicodeDecodeError, invalid continuation byte

I had the same error when I tried to open a CSV file by pandas.read_csv method.

The solution was change the encoding to latin-1:

pd.read_csv('ml-100k/u.item', sep='|', names=m_cols , encoding='latin-1')

Percentage calculation

Mathematically, to get percentage from two numbers:

percentage = (yourNumber / totalNumber) * 100;

And also, to calculate from a percentage :

number = (percentage / 100) * totalNumber;

What is the use of verbose in Keras while validating the model?

By default verbose = 1,

verbose = 1, which includes both progress bar and one line per epoch

verbose = 0, means silent

verbose = 2, one line per epoch i.e. epoch no./total no. of epochs

How do I set up Eclipse/EGit with GitHub?

In Eclipse, go to Help -> Install New Software -> Add -> Name: any name like egit; Location: http://download.eclipse.org/egit/updates -> Okay. Now Search for egit in Work with and select all the check boxes and press Next till finish.

File -> Import -> search Git and select "Projects from Git" -> Clone URI. In the URI, paste the HTTPS URL of the repository (the one with .git extension). -> Next ->It will show all the branches "Next" -> Local Destination "Next" -> "Import as a general project" -> Next till finish.

You can refer to this Youtube tutorial: https://www.youtube.com/watch?v=ptK9-CNms98

How do I write to a Python subprocess' stdin?

You can provide a file-like object to the stdin argument of subprocess.call().

The documentation for the Popen object applies here.

To capture the output, you should instead use subprocess.check_output(), which takes similar arguments. From the documentation:

>>> subprocess.check_output(
...     "ls non_existent_file; exit 0",
...     stderr=subprocess.STDOUT,
...     shell=True)
'ls: non_existent_file: No such file or directory\n'

Parsing Json rest api response in C#

1> Add this namspace. using Newtonsoft.Json.Linq;

2> use this source code.

JObject joResponse = JObject.Parse(response);                   
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());

Find a file with a certain extension in folder

Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:

 string[] files = System.IO.Directory.GetFiles(path, "*.txt");

Elegant solution for line-breaks (PHP)

For linebreaks, PHP as "\n" (see double quote strings) and PHP_EOL.

Here, you are using <br />, which is not a PHP line-break : it's an HTML linebreak.


Here, you can simplify what you posted (with HTML linebreaks) : no need for the strings concatenations : you can put everything in just one string, like this :

$var = "Hi there<br/>Welcome to my website<br/>";

Or, using PHP linebreaks :

$var = "Hi there\nWelcome to my website\n";

Note : you might also want to take a look at the nl2br() function, which inserts <br> before \n.

Split a python list into other "sublists" i.e smaller lists

Actually I think using plain slices is the best solution in this case:

for i in range(0, len(data), 100):
    chunk = data[i:i + 100]
    ...

If you want to avoid copying the slices, you could use itertools.islice(), but it doesn't seem to be necessary here.

The itertools() documentation also contains the famous "grouper" pattern:

def grouper(n, iterable, fillvalue=None):
    "grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

You would need to modify it to treat the last chunk correctly, so I think the straight-forward solution using plain slices is preferable.

.NET Events - What are object sender & EventArgs e?

  1. 'sender' is called object which has some action perform on some control

  2. 'event' its having some information about control which has some behavoiur and identity perform by some user.when action will generate by occuring for event add it keep within array is called event agrs

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

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

The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

Gets last digit of a number

You have just created an empty integer array. The array guess does not contain anything to my knowledge. The rest you should work out to get better.

How do I get an element to scroll into view, using jQuery?

Here's a quick jQuery plugin to map the built in browser functionality nicely:

$.fn.ensureVisible = function () { $(this).each(function () { $(this)[0].scrollIntoView(); }); };

...

$('.my-elements').ensureVisible();

Stop MySQL service windows

I got the same problem and here my solution:

  1. go to service.msc and find mysql service. set it as start manually.
  2. go to task manager - processes tab and find mysqld. stop it
  3. go to task manager - services tab find mysql service and stop it

How to allow user to pick the image with Swift?

Try this one it's easy.. to Pic a Image using UIImagePickerControllerDelegate

    @objc func masterAction(_ sender: UIButton)
    {
        if UIImagePickerController.isSourceTypeAvailable(.savedPhotosAlbum){
            print("Button capture")

            imagePicker.delegate = self
            imagePicker.sourceType = .savedPhotosAlbum;
            imagePicker.allowsEditing = false

            self.present(imagePicker, animated: true, completion: nil)
        }

        print("hello i'm touch \(sender.tag)")
    }

    func imagePickerControllerDidCancel(_ picker:
        UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }

    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let chosenImage = info[UIImagePickerControllerOriginalImage] as? UIImage {
            print("Get Image \(chosenImage)")
            ImageList.insert(chosenImage, at: 0)
            ArrayList.insert("", at: 0)
            Collection_Vw.reloadData()
        } else{
            print("Something went wrong")
        }

        self.dismiss(animated: true, completion: nil)
    }

How to Run Terminal as Administrator on Mac Pro

This is not Windows, you do not "run the Terminal as admin". What you do is you run commands in the terminal as admin, typically using sudo:

$ sudo some command here

Is it not possible to stringify an Error using JSON.stringify?

You can solve this with a one-liner( errStringified ) in plain javascript:

var error = new Error('simple error message');
var errStringified = (err => JSON.stringify(Object.getOwnPropertyNames(Object.getPrototypeOf(err)).reduce(function(accumulator, currentValue) { return accumulator[currentValue] = err[currentValue], accumulator}, {})))(error);
console.log(errStringified);

It works with DOMExceptions as well.

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

Returning anonymous type in C#

You can only use dynamic keyword,

   dynamic obj = GetAnonymousType();

   Console.WriteLine(obj.Name);
   Console.WriteLine(obj.LastName);
   Console.WriteLine(obj.Age); 


   public static dynamic GetAnonymousType()
   {
       return new { Name = "John", LastName = "Smith", Age=42};
   }

But with dynamic type keyword you will loose compile time safety, IDE IntelliSense etc...

Getting Textarea Value with jQuery

It can be done at easily like as:

     <a id="send-thoughts" href="">Click</a>
     <textarea id="message"></textarea>

        $("a#send-thoughts").click(function() {
            var thought = $("#message").val();
            alert(thought);
        });

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

Adding Apostrophe in every field in particular column for excel

i use concantenate. works for me.

  1. fill j2-j14 with '(appostrophe)
  2. enter L2 with formula =concantenate(j2,k2)
  3. copy L2 to L3-L14

How do I register a DLL file on Windows 7 64-bit?

There is a difference in Windows 7. Logging on as Administrator does not give the same rights as when running a program as Administrator.

Go to Start - All Programs - Accesories. Right click on the Command window and select "Run as administrator" Now register the dll normally via : regsrvr32 xxx.dll

How can I get column names from a table in SQL Server?

SELECT c.Name 
FROM sys.columns c
JOIN sys.objects o ON o.object_id = c.object_id
WHERE o.object_id = OBJECT_ID('TABLE_NAME')
ORDER BY c.Name

PHP + MySQL transactions examples

One more procedural style example with mysqli_multi_query, assumes $query is filled with semicolon-separated statements.

mysqli_begin_transaction ($link);

for (mysqli_multi_query ($link, $query);
    mysqli_more_results ($link);
    mysqli_next_result ($link) );

! mysqli_errno ($link) ?
    mysqli_commit ($link) : mysqli_rollback ($link);

Launch Image does not show up in my iOS App

Xcode 8:

Images used in LaunchScreen.xib should not be on a .xcassets, try dropping them in the bundle.

Looks like that by the time that the .xib gets loaded, the images in the .xcassets are not yet available.

EDIT: For some opaque reason after adding some localizations, launch screen stopped working, now it works with an image from the assets, extremely weird.

Make a div into a link

I pulled in a variable because some values in my link will change depending on what record the user is coming from. This worked for testing :

   <div onclick="location.href='page.html';"  style="cursor:pointer;">...</div> 

and this works too :

   <div onclick="location.href='<%=Webpage%>';"  style="cursor:pointer;">...</div> 

Using NotNull Annotation in method argument

To test your method validation in a test, you have to wrap it a proxy in the @Before method.

@Before
public void setUp() {
    this.classAutowiredWithFindStuffMethod = MethodValidationProxyFactory.createProxy(this.classAutowiredWithFindStuffMethod);
}

With MethodValidationProxyFactory as :

import org.springframework.context.support.StaticApplicationContext;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;

public class MethodValidationProxyFactory {

private static final StaticApplicationContext ctx = new StaticApplicationContext();

static {
    MethodValidationPostProcessor processor = new MethodValidationPostProcessor();
    processor.afterPropertiesSet(); // init advisor
    ctx.getBeanFactory()
            .addBeanPostProcessor(processor);
}

@SuppressWarnings("unchecked")
public static <T> T createProxy(T instance) {

    return (T) ctx.getAutowireCapableBeanFactory()
            .applyBeanPostProcessorsAfterInitialization(instance, instance.getClass()
                    .getName());
}

}

And then, add your test :

@Test
public void findingNullStuff() {
 assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(() -> this.classAutowiredWithFindStuffMethod.findStuff(null));

}

Insert image after each list item

ul li + li:before
{
    content:url(imgs/separator.gif);
}

How to find sum of several integers input by user using do/while, While statement or For statement

You should do:

#include<iostream>
using namespace std;
int main ()
{

    int sum = 0;
    int number;
    int numberitems;


    cout << "Enter number of items: \n";
    cin >> numberitems;

    for(int i=0;i<numberitems;i++)
    {
        cout << "Enter number <<i<<":" \n";
        cin >> number; sum+=number;
    }
    cout<<"sum is: "<< sum<<endl;
}

And with a while statement

#include <iostream>
using namespace std;
int main ()
{
    int sum = 0;
    int number;
    int numberitems;
    cin>>numberitems;

    cout << "Enter number: \n";

    while (count <=numberitems)
    {
        cin >> number;
        sum+=number;
    }
    cout << sum << endl;
}

Get clicked element using jQuery on event?

As simple as it can be

Use $(this) here too

$(document).on("click",".appDetails", function () {
   var clickedBtnID = $(this).attr('id'); // or var clickedBtnID = this.id
   alert('you clicked on button #' + clickedBtnID);
});

How can I switch views programmatically in a view controller? (Xcode, iPhone)

#import "YourViewController.h"

To push a view including the navigation bar and/or tab bar:

UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"YourStoryboard" bundle:nil];
YourViewController *viewController = (YourViewcontroller *)[storyboard instantiateViewControllerWithIdentifier:@"YourViewControllerIdentifier"];
[self.navigationController pushViewController:viewController animated:YES];

To set identifier to a view controller, Open YourStoryboard.storyboard. Select YourViewController View-> Utilities -> ShowIdentityInspector. There you can specify the identifier.

Set variable value to array of strings

declare  @tab table(FirstName  varchar(100))
insert into @tab   values('John'),('Sarah'),('George')

SELECT * 
FROM @tab
WHERE 'John' in (FirstName)

Construct pandas DataFrame from items in nested dictionary

So I used to use a for loop for iterating through the dictionary as well, but one thing I've found that works much faster is to convert to a panel and then to a dataframe. Say you have a dictionary d

import pandas as pd
d
{'RAY Index': {datetime.date(2014, 11, 3): {'PX_LAST': 1199.46,
'PX_OPEN': 1200.14},
datetime.date(2014, 11, 4): {'PX_LAST': 1195.323, 'PX_OPEN': 1197.69},
datetime.date(2014, 11, 5): {'PX_LAST': 1200.936, 'PX_OPEN': 1195.32},
datetime.date(2014, 11, 6): {'PX_LAST': 1206.061, 'PX_OPEN': 1200.62}},
'SPX Index': {datetime.date(2014, 11, 3): {'PX_LAST': 2017.81,
'PX_OPEN': 2018.21},
datetime.date(2014, 11, 4): {'PX_LAST': 2012.1, 'PX_OPEN': 2015.81},
datetime.date(2014, 11, 5): {'PX_LAST': 2023.57, 'PX_OPEN': 2015.29},
datetime.date(2014, 11, 6): {'PX_LAST': 2031.21, 'PX_OPEN': 2023.33}}}

The command

pd.Panel(d)
<class 'pandas.core.panel.Panel'>
Dimensions: 2 (items) x 2 (major_axis) x 4 (minor_axis)
Items axis: RAY Index to SPX Index
Major_axis axis: PX_LAST to PX_OPEN
Minor_axis axis: 2014-11-03 to 2014-11-06

where pd.Panel(d)[item] yields a dataframe

pd.Panel(d)['SPX Index']
2014-11-03  2014-11-04  2014-11-05 2014-11-06
PX_LAST 2017.81 2012.10 2023.57 2031.21
PX_OPEN 2018.21 2015.81 2015.29 2023.33

You can then hit the command to_frame() to turn it into a dataframe. I use reset_index as well to turn the major and minor axis into columns rather than have them as indices.

pd.Panel(d).to_frame().reset_index()
major   minor      RAY Index    SPX Index
PX_LAST 2014-11-03  1199.460    2017.81
PX_LAST 2014-11-04  1195.323    2012.10
PX_LAST 2014-11-05  1200.936    2023.57
PX_LAST 2014-11-06  1206.061    2031.21
PX_OPEN 2014-11-03  1200.140    2018.21
PX_OPEN 2014-11-04  1197.690    2015.81
PX_OPEN 2014-11-05  1195.320    2015.29
PX_OPEN 2014-11-06  1200.620    2023.33

Finally, if you don't like the way the frame looks you can use the transpose function of panel to change the appearance before calling to_frame() see documentation here http://pandas.pydata.org/pandas-docs/dev/generated/pandas.Panel.transpose.html

Just as an example

pd.Panel(d).transpose(2,0,1).to_frame().reset_index()
major        minor  2014-11-03  2014-11-04  2014-11-05  2014-11-06
RAY Index   PX_LAST 1199.46    1195.323     1200.936    1206.061
RAY Index   PX_OPEN 1200.14    1197.690     1195.320    1200.620
SPX Index   PX_LAST 2017.81    2012.100     2023.570    2031.210
SPX Index   PX_OPEN 2018.21    2015.810     2015.290    2023.330

Hope this helps.

Image resizing in React Native

This worked for me,

image: {
    width: 200,
    height:220,
    resizeMode: 'cover'
}

You can also set your resizeMode: 'contain'. I defined the style for my network images as:

<Image 
   source={{uri:rowData.banner_path}}
   style={{
     width: 80,
     height: 80,
     marginRight: 10,
     marginBottom: 12,
     marginTop: 12}}
/>

If you are using flex, use it in all the components of parent View, else it is redundant with height: 200, width: 220.

Create pandas Dataframe by appending one row at a time

You could use pandas.concat() or DataFrame.append(). For details and examples, see Merge, join, and concatenate.

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

Scripts are raw java embedded in the page code, and if you declare variables in your scripts, then they become local variables embedded in the page.

In contrast, JSTL works entirely with scoped attributes, either at page, request or session scope. You need to rework your scriptlet to fish test out as an attribute:

<c:set var="test" value="test1"/>
<%
  String resp = "abc";
  String test = pageContext.getAttribute("test");
  resp = resp + test;
  pageContext.setAttribute("resp", resp);
%>
<c:out value="${resp}"/>

If you look at the docs for <c:set>, you'll see you can specify scope as page, request or session, and it defaults to page.

Better yet, don't use scriptlets at all: they make the baby jesus cry.

C# string reference type?

As others have stated, the String type in .NET is immutable and it's reference is passed by value.

In the original code, as soon as this line executes:

test = "after passing";

then test is no longer referring to the original object. We've created a new String object and assigned test to reference that object on the managed heap.

I feel that many people get tripped up here since there's no visible formal constructor to remind them. In this case, it's happening behind the scenes since the String type has language support in how it is constructed.

Hence, this is why the change to test is not visible outside the scope of the TestI(string) method - we've passed the reference by value and now that value has changed! But if the String reference were passed by reference, then when the reference changed we will see it outside the scope of the TestI(string) method.

Either the ref or out keyword are needed in this case. I feel the out keyword might be slightly better suited for this particular situation.

class Program
{
    static void Main(string[] args)
    {
        string test = "before passing";
        Console.WriteLine(test);
        TestI(out test);
        Console.WriteLine(test);
        Console.ReadLine();
    }

    public static void TestI(out string test)
    {
        test = "after passing";
    }
}

Batch script: how to check for admin rights

whoami /groups | find "S-1-16-12288" > nul
if not errorlevel 1 (
  echo ...  connected as admin
)

Is a new line = \n OR \r\n?

The given answer is far from complete. In fact, it is so far from complete that it tends to lead the reader to believe that this answer is OS dependent when it isn't. It also isn't something which is programming language dependent (as some commentators have suggested). I'm going to add more information in order to make this more clear. First, lets give the list of current new line variations (as in, what they've been since 1999):

  • \r\n is only used on Windows Notepad, the DOS command line, most of the Windows API and in some (older) Windows apps.
  • \n is used for all other systems, applications and the Internet.

You'll notice that I've put most Windows apps in the \n group which may be slightly controversial but before you disagree with this statement, please grab a UNIX formatted text file and try it in 10 web friendly Windows applications of your choice (which aren't listed in my exceptions above). What percentage of them handled it just fine? You'll find that they (practically) all implement auto detection of line endings or just use \n because, while Windows may use \r\n, the Internet uses \n. Therefore, it is best practice for applications to use \n alone if you want your output to be Internet friendly.

PHP also defines a newline character called PHP_EOL. This constant is set to the OS specific newline string for the machine PHP is running on (\r\n for Windows and \n for everything else). This constant is not very useful for webpages and should be avoided for HTML output or for writing most text to files. It becomes VERY useful when we move to command line output from PHP applications because it will allow your application to output to a terminal Window in a consistent manner across all supported OSes.

If you want your PHP applications to work from any server they are placed on, the two biggest things to remember are that you should always just use \n unless it is terminal output (in which case you use PHP_EOL) and you should also ALWAYS use / for your path separator (not \).

The even longer explanation:

An application may choose to use whatever line endings it likes regardless of the default OS line ending style. If I want my text editor to print a newline every time it encounters a period that is no harder than using the \n to represent a newline because I'm interpreting the text as I display it anyway. IOW, I'm fiddling around with measuring the width of each character so it knows where to display the next so it is very simple to add a statement saying that if the current char is a period then perform a newline action (or if it is a \n then display a period).

Aside from the null terminator, no character code is sacred and when you write a text editor or viewer you are in charge of translating the bits in your file into glyphs (or carriage returns) on the screen. The only thing that distinguishes a control character such as the newline from other characters is that most font sets don't include them (meaning they don't have a visual representation available).

That being said, if you are working at a higher level of abstraction then you probably aren't making your own textbox controls. If this is the case then you're stuck with whatever line ending that control makes available to you. Even in this case it is a simple matter to automatically detect the line ending style of any string and make the conversion before you load your text into the control and then undo it when you read from that control. Meaning, that if you're a desktop application dev and your application doesn't recognize \n as a newline then it isn't a very friendly application and you really have no excuse because it isn't hard to make it the right way. It also means that whomever wrote Notepad should be ashamed of himself because it really is very easy to do much better and so many people suffer through using it every day.

Equivalent function for DATEADD() in Oracle

Method1: ADD_MONTHS

ADD_MONTHS(SYSDATE, -6)

Method 2: Interval

SYSDATE - interval '6' month

Note: if you want to do the operations from start of the current month always, TRUNC(SYSDATE,'MONTH') would give that. And it expects a Date datatype as input.

How to vertically center a "div" element for all browsers using CSS?

To center the div on a page, check the fiddle link.

_x000D_
_x000D_
#vh {_x000D_
    margin: auto;_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    left: 0;_x000D_
    bottom: 0;_x000D_
    right: 0;_x000D_
}_x000D_
.box{_x000D_
    border-radius: 15px;_x000D_
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);_x000D_
    padding: 25px;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: white;_x000D_
}
_x000D_
<div id="vh" class="box">Div to be aligned vertically</div>
_x000D_
_x000D_
_x000D_

Another option is to use flex box, check the fiddle link.

_x000D_
_x000D_
.vh {_x000D_
    background-color: #ddd;_x000D_
    height: 400px;_x000D_
    align-items: center;_x000D_
    display: flex;_x000D_
}_x000D_
.vh > div {_x000D_
    width: 100%;_x000D_
    text-align: center;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<div class="vh">_x000D_
    <div>Div to be aligned vertically</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Another option is to use a CSS 3 transform:

_x000D_
_x000D_
#vh {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    /*transform: translateX(-50%) translateY(-50%);*/_x000D_
    transform: translate(-50%, -50%);_x000D_
}_x000D_
.box{_x000D_
    border-radius: 15px;_x000D_
    box-shadow: 0 0 8px rgba(0, 0, 0, 0.4);_x000D_
    padding: 25px;_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: white;_x000D_
}
_x000D_
<div id="vh" class="box">Div to be aligned vertically</div>
_x000D_
_x000D_
_x000D_

Why do we always prefer using parameters in SQL statements?

In Sql when any word contain @ sign it means it is variable and we use this variable to set value in it and use it on number area on the same sql script because it is only restricted on the single script while you can declare lot of variables of same type and name on many script. We use this variable in stored procedure lot because stored procedure are pre-compiled queries and we can pass values in these variable from script, desktop and websites for further information read Declare Local Variable, Sql Stored Procedure and sql injections.

Also read Protect from sql injection it will guide how you can protect your database.

Hope it help you to understand also any question comment me.

Where are $_SESSION variables stored?

In my Ubuntu machine sessions are stored at

/var/lib/php/sessions

and you have to sudo ls in this directory only ls it will throw

ls: cannot open directory '.': Permission denied

And on my Windows Wamp server php sessions are stored in

C:\wamp64\tmp

and if you install standalone php on windows then there is no value set by default

session.save_path => no value => no value

Excel Define a range based on a cell value

Based on answer by @Cici I give here a more generic solution:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

In Italian version of Excel:

=SOMMA(INDIRETTO(CONCATENA(B1;C1)):INDIRETTO(CONCATENA(B2;C2)))

Where B1-C2 cells hold these values:

  • A, 1
  • A, 5

You can change these valuese to change the final range at wish.


Splitting the formula in parts:

  • SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
  • CONCATENATE(B1,C1) - result is A1
  • INDIRECT(CONCATENATE(B1,C1)) - result is reference to A1

Hence:

=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))

results in

=SUM(A1:A5)


I'll write down here a couple of SEO keywords for Italian users:

  • come creare dinamicamente l'indirizzo di un intervallo in excel
  • formula per definire un intervallo di celle in excel.

Con la formula indicata qui sopra basta scrivere nelle caselle da B1 a C2 gli estremi dell'intervallo per vedelo cambiare dentro la formula stessa.

Difference between database and schema

A database is the main container, it contains the data and log files, and all the schemas within it. You always back up a database, it is a discrete unit on its own.

Schemas are like folders within a database, and are mainly used to group logical objects together, which leads to ease of setting permissions by schema.

EDIT for additional question

drop schema test1

Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'test1' because it is being referenced by object 'copyme'.

You cannot drop a schema when it is in use. You have to first remove all objects from the schema.

Related reading:

  1. What good are SQL Server schemas?
  2. MSDN: User-Schema Separation

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

JQuery string contains check

You can use javascript's indexOf function.

_x000D_
_x000D_
var str1 = "ABCDEFGHIJKLMNOP";_x000D_
var str2 = "DEFG";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
    console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_

Is it good practice to use the xor operator for boolean checks?

I think it'd be okay if you commented it, e.g. // ^ == XOR.

MVC web api: No 'Access-Control-Allow-Origin' header is present on the requested resource

@Mihai-Andrei Dinculescu's answer worked for me, e.g.:

  • Adding a <httpProtocol>in the web.config's <system.webServer> section
  • Returning empty response for OPTIONS requests via the mentioned Application_BeginRequest() in global.asax

Except that his check for Request.Headers.AllKeys.Contains("Origin") did NOT work for me, because the request contained an origing, so with lowercase. I think my browser (Chrome) sends it like this for CORS requests.

I solved this a bit more generically by using a case insensitive variant of his Contains check instead: if (culture.CompareInfo.IndexOf(string.Join(",", Request.Headers.AllKeys), "Origin", CompareOptions.IgnoreCase) >= 0) {

Why does JSON.parse fail with the empty string?

Because '' is not a valid Javascript/JSON object. An empty object would be '{}'

For reference: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Add a tooltip to a div

You don't need JavaScript for this at all; just set the title attribute:

<div title="Hello, World!">
  <label>Name</label>
  <input type="text"/>
</div>

Note that the visual presentation of the tooltip is browser/OS dependent, so it might fade in and it might not. However, this is the semantic way to do tooltips, and it will work correctly with accessibility software like screen readers.

Demo in Stack Snippets

_x000D_
_x000D_
<div title="Hello, World!">_x000D_
  <label>Name</label>_x000D_
  <input type="text"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

There is already an object named in the database

In my case I had re-named the assembly that contained the code-first entity framework model. Although the actual schema hadn't changed at all the migrations table called

dbo.__MigrationHistory

contains a list of already performed migrations based on the old assembly name. I updated the old name in the migrations table to match the new and the migration then worked again.

Good font for code presentations?

I do a lot of such presentation and use Monaco for code and Chalkboard for text (within a template that, overall, has only small changes from the Blackboard one supplied with Keynote). Look at any of my presentations' PDFs (e.g. this one) and you can decide whether you like the effect.

AngularJS Dropdown required validation

You need to add a name attribute to your dropdown list, then you need to add a required attribute, and then you can reference the error using myForm.[input name].$error.required:

HTML:

        <form name="myForm" ng-controller="Ctrl" ng-submit="save(myForm)" novalidate>
        <input type="text" name="txtServiceName" ng-model="ServiceName" required>
<span ng-show="myForm.txtServiceName.$error.required">Enter Service Name</span>
<br/>
          <select name="service_id" class="Sitedropdown" style="width: 220px;"          
                  ng-model="ServiceID" 
                  ng-options="service.ServiceID as service.ServiceName for service in services"
                  required> 
            <option value="">Select Service</option> 
          </select> 
          <span ng-show="myForm.service_id.$error.required">Select service</span>

        </form>

    Controller:

        function Ctrl($scope) {
          $scope.services = [
            {ServiceID: 1, ServiceName: 'Service1'},
            {ServiceID: 2, ServiceName: 'Service2'},
            {ServiceID: 3, ServiceName: 'Service3'}
          ];

    $scope.save = function(myForm) {
    console.log('Selected Value: '+ myForm.service_id.$modelValue);
    alert('Data Saved! without validate');
    };
        }

Here's a working plunker.

getActivity() returns null in Fragment function

You can using onAttach or if you do not want to put onAttach everywhere then you can put a method that returns ApplicationContext on the main App class :

public class App {
    ...  
    private static Context context;

    @Override
    public void onCreate() {
        super.onCreate();
        context = this;
    }

    public static Context getContext() {
        return context;
    }
    ...
}

After that you can re-use it everywhere in all over your project, like this :

App.getContext().getString(id)

Please let me know if this does not work for you.

fail to change placeholder color with Bootstrap 3

Bootstrap has 3 lines of CSS, within your bootstrap.css generated file that control the placeholder text color:

.form-control::-moz-placeholder {
  color: #999999;
  opacity: 1;
}
.form-control:-ms-input-placeholder {
  color: #999999;
}
.form-control::-webkit-input-placeholder {
  color: #999999;
}

Now if you add this to your own CSS file it won't override bootstrap's because it is less specific. So assmuning your form inside a then add that to your CSS:

form .form-control::-moz-placeholder {
  color: #fff;
  opacity: 1;
}
form .form-control:-ms-input-placeholder {
  color: #fff;
}
form .form-control::-webkit-input-placeholder {
  color: #fff;
}

Voila that will override bootstrap's CSS.