Programs & Examples On #Ftp server

Server for the File Transfer Protocol (FTP), a standard network protocol used to transfer files from one host to another host over a TCP-based network.

One line ftp server in python

Obligatory Twisted example:

twistd -n ftp

And probably useful:

twistd ftp --help

Usage: twistd [options] ftp [options].
WARNING: This FTP server is probably INSECURE do not use it.
Options:
  -p, --port=           set the port number [default: 2121]
  -r, --root=           define the root of the ftp-site. [default:
                    /usr/local/ftp]
  --userAnonymous=  Name of the anonymous user. [default: anonymous]
  --password-file=  username:password-style credentials database
  --version         
  --help            Display this help and exit.

Vue.js dynamic images not working

You can try the require function. like this:

<img :src="require(`@/xxx/${name}.png`)" alt class="icon" />

How to draw a graph in LaTeX?

In my experience, I always just use an external program to generate the graph (mathematica, gnuplot, matlab, etc.) and export the graph as a pdf or eps file. Then I include it into the document with includegraphics.

Click event on select option element in chrome

I use a two part solution

  • Part 1 - Register my click events on the options like I usually would
  • Part 2 - Detect that the selected item changed, and call the click handler of the new selected item.

HTML

<select id="sneaky-select">
  <option id="select-item-1">Hello</option>
  <option id="select-item-2">World</option>
</select>

JS

$("#select-item-1").click(function () { alert('hello') });
$("#select-item-2").click(function () { alert('world') });

$("#sneaky-select").change(function ()
{
   $("#sneaky-select option:selected").click();
});

SELECT only rows that contain only alphanumeric characters in MySQL

Try this:

REGEXP '^[a-z0-9]+$'

As regexp is not case sensitive except for binary fields.

Merge some list items in a Python List

That example is pretty vague, but maybe something like this?

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [''.join(items[3:6])]

It basically does a splice (or assignment to a slice) operation. It removes items 3 to 6 and inserts a new list in their place (in this case a list with one item, which is the concatenation of the three items that were removed.)

For any type of list, you could do this (using the + operator on all items no matter what their type is):

items = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
items[3:6] = [reduce(lambda x, y: x + y, items[3:6])]

This makes use of the reduce function with a lambda function that basically adds the items together using the + operator.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

It's pretty simple. You're trying to test the wrapper component generated by calling connect()(MyPlainComponent). That wrapper component expects to have access to a Redux store. Normally that store is available as context.store, because at the top of your component hierarchy you'd have a <Provider store={myStore} />. However, you're rendering your connected component by itself, with no store, so it's throwing an error.

You've got a few options:

  • Create a store and render a <Provider> around your connected component
  • Create a store and directly pass it in as <MyConnectedComponent store={store} /> , as the connected component will also accept "store" as a prop
  • Don't bother testing the connected component. Export the "plain", unconnected version, and test that instead. If you test your plain component and your mapStateToProps function, you can safely assume the connected version will work correctly.

You probably want to read through the "Testing" page in the Redux docs: https://redux.js.org/recipes/writing-tests.

edit:

After actually seeing that you posted source, and re-reading the error message, the real problem is not with the SportsTopPane component. The problem is that you're trying to "fully" render SportsTopPane, which also renders all of its children, rather than doing a "shallow" render like you were in the first case. The line searchComponent = <SportsDatabase sportsWholeFramework="desktop" />; is rendering a component that I assume is also connected, and therefore expects a store to be available in React's "context" feature.

At this point, you have two new options:

  • Only do "shallow" rendering of SportsTopPane, so that you're not forcing it to fully render its children
  • If you do want to do "deep" rendering of SportsTopPane, you'll need to provide a Redux store in context. I highly suggest you take a look at the Enzyme testing library, which lets you do exactly that. See http://airbnb.io/enzyme/docs/api/ReactWrapper/setContext.html for an example.

Overall, I would note that you might be trying to do too much in this one component and might want to consider breaking it into smaller pieces with less logic per component.

How to select a radio button by default?

They pretty much got it there... just like a checkbox, all you have to do is add the attribute checked="checked" like so:

<input type="radio" checked="checked">

...and you got it.

Cheers!

How to download and save a file from Internet using Java?

You can do this in 1 line using netloader for Java:

new NetFile(new File("my/zips/1.zip"), "https://example.com/example.zip", -1).load(); //returns true if succeed, otherwise false.

What is an idempotent operation?

Just wanted to throw out a real use case that demonstrates idempotence. In JavaScript, say you are defining a bunch of model classes (as in MVC model). The way this is often implemented is functionally equivalent to something like this (basic example):

function model(name) {
  function Model() {
    this.name = name;
  }

  return Model;
}

You could then define new classes like this:

var User = model('user');
var Article = model('article');

But if you were to try to get the User class via model('user'), from somewhere else in the code, it would fail:

var User = model('user');
// ... then somewhere else in the code (in a different scope)
var User = model('user');

Those two User constructors would be different. That is,

model('user') !== model('user');

To make it idempotent, you would just add some sort of caching mechanism, like this:

var collection = {};

function model(name) {
  if (collection[name])
    return collection[name];

  function Model() {
    this.name = name;
  }

  collection[name] = Model;
  return Model;
}

By adding caching, every time you did model('user') it will be the same object, and so it's idempotent. So:

model('user') === model('user');

Material Design not styling alert dialogs

Material Design styling alert dialogs: Custom Font, Button, Color & shape,..

 MaterialAlertDialogBuilder(requireContext(),
                R.style.MyAlertDialogTheme
            )
                .setIcon(R.drawable.ic_dialogs_24px)
                .setTitle("Feedback")
                //.setView(R.layout.edit_text)
                .setMessage("Do you have any additional comments?")
                .setPositiveButton("Send") { dialog, _ ->

                    val input =
                        (dialog as AlertDialog).findViewById<TextView>(
                            android.R.id.text1
                        )
                    Toast.makeText(context, input!!.text, Toast.LENGTH_LONG).show()

                }
                .setNegativeButton("Cancel") { _, _ ->
                    Toast.makeText(requireContext(), "Clicked cancel", Toast.LENGTH_SHORT).show()
                }
                .show()

Style:

  <style name="MyAlertDialogTheme" parent="Theme.MaterialComponents.DayNight.Dialog.Alert">
  
        <item name="android:textAppearanceSmall">@style/MyTextAppearance</item>
        <item name="android:textAppearanceMedium">@style/MyTextAppearance</item>
        <item name="android:textAppearanceLarge">@style/MyTextAppearance</item>

        <item name="buttonBarPositiveButtonStyle">@style/Alert.Button.Positive</item>
        <item name="buttonBarNegativeButtonStyle">@style/Alert.Button.Neutral</item>
        <item name="buttonBarNeutralButtonStyle">@style/Alert.Button.Neutral</item>

        <item name="android:backgroundDimEnabled">true</item>

        <item name="shapeAppearanceOverlay">@style/ShapeAppearanceOverlay.MyApp.Dialog.Rounded
        </item>

    </style>




    <style name="MyTextAppearance" parent="TextAppearance.AppCompat">
        <item name="android:fontFamily">@font/rosarivo</item>
    </style>


        <style name="Alert.Button.Positive" parent="Widget.MaterialComponents.Button.TextButton">
   <!--     <item name="backgroundTint">@color/colorPrimaryDark</item>-->
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
       <!-- <item name="android:textColor">@android:color/white</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


    <style name="Alert.Button.Neutral" parent="Widget.MaterialComponents.Button.TextButton">
        <item name="backgroundTint">@android:color/transparent</item>
        <item name="rippleColor">@color/colorAccent</item>
        <item name="android:textColor">@color/colorPrimary</item>
        <!--<item name="android:textColor">@android:color/darker_gray</item>-->
        <item name="android:textSize">14sp</item>
        <item name="android:textAllCaps">false</item>
    </style>


  <style name="ShapeAppearanceOverlay.MyApp.Dialog.Rounded" parent="">
        <item name="cornerFamily">rounded</item>
        <item name="cornerSize">8dp</item>
    </style>

Output: enter image description here

How do I use modulus for float/double?

Unlike C, Java allows using the % for both integer and floating point and (unlike C89 and C++) it is well-defined for all inputs (including negatives):

From JLS §15.17.3:

The result of a floating-point remainder operation is determined by the rules of IEEE arithmetic:

  • If either operand is NaN, the result is NaN.
  • If the result is not NaN, the sign of the result equals the sign of the dividend.
  • If the dividend is an infinity, or the divisor is a zero, or both, the result is NaN.
  • If the dividend is finite and the divisor is an infinity, the result equals the dividend.
  • If the dividend is a zero and the divisor is finite, the result equals the dividend.
  • In the remaining cases, where neither an infinity, nor a zero, nor NaN is involved, the floating-point remainder r from the division of a dividend n by a divisor d is defined by the mathematical relation r=n-(d·q) where q is an integer that is negative only if n/d is negative and positive only if n/d is positive, and whose magnitude is as large as possible without exceeding the magnitude of the true mathematical quotient of n and d.

So for your example, 0.5/0.3 = 1.6... . q has the same sign (positive) as 0.5 (the dividend), and the magnitude is 1 (integer with largest magnitude not exceeding magnitude of 1.6...), and r = 0.5 - (0.3 * 1) = 0.2

Dynamically add script tag with src that may include document.write

When scripts are loaded asynchronously they cannot call document.write. The calls will simply be ignored and a warning will be written to the console.

You can use the following code to load the script dynamically:

var scriptElm = document.createElement('script');
scriptElm.src = 'source.js';
document.body.appendChild(scriptElm);

This approach works well only when your source belongs to a separate file.

But if you have source code as inline functions which you want to load dynamically and want to add other attributes to the script tag, e.g. class, type, etc., then the following snippet would help you:

var scriptElm = document.createElement('script');
scriptElm.setAttribute('class', 'class-name');
var inlineCode = document.createTextNode('alert("hello world")');
scriptElm.appendChild(inlineCode); 
document.body.appendChild(scriptElm);

How can a Java program get its own process ID?

Here is my solution:

public static boolean isPIDInUse(int pid) {

        try {

            String s = null;
            int java_pid;

            RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
            java_pid = Integer.parseInt(rt.getName().substring(0, rt.getName().indexOf("@")));

            if (java_pid == pid) {
                System.out.println("In Use\n");
                return true;
            }
        } catch (Exception e) {
            System.out.println("Exception:  " + e.getMessage());
        }
        return false;
    }

Git - push current branch shortcut

With the help of ceztko's answer I wrote this little helper function to make my life easier:

function gpu()
{
    if git rev-parse --abbrev-ref --symbolic-full-name @{u} > /dev/null 2>&1; then
        git push origin HEAD
    else
        git push -u origin HEAD
    fi
}

It pushes the current branch to origin and also sets the remote tracking branch if it hasn't been setup yet.

How to delete a record by id in Flask-SQLAlchemy

Just want to share another option:

# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)

# commit (or flush)
session.commit()

http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting

In this example, the following codes shall works fine:

obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()

Select box arrow style

The select box arrow is a native ui element, it depends on the desktop theme or the web browser. Use a jQuery plugin (e.g. Select2, Chosen) or CSS.

How often should Oracle database statistics be run?

When I was managing a large multi-user planning system backed by Oracle, our DBA had a weekly job that gathered statistics. Also, when we rolled out a significant change that could affect or be affected by statistics, we would force the job to run out of cycle to get things caught up.

What causes a java.lang.StackOverflowError

Solution for Hibernate users when parsing datas:

I had this error because I was parsing a list of objects mapped on both sides @OneToMany and @ManyToOne to json using jackson which caused an infinite loop.

If you are in the same situation you can solve this by using @JsonManagedReference and @JsonBackReference annotations.

Definitions from API :

  • JsonManagedReference (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonManagedReference.html) :

    Annotation used to indicate that annotated property is part of two-way linkage between fields; and that its role is "parent" (or "forward") link. Value type (class) of property must have a single compatible property annotated with JsonBackReference. Linkage is handled such that the property annotated with this annotation is handled normally (serialized normally, no special handling for deserialization); it is the matching back reference that requires special handling

  • JsonBackReference: (https://fasterxml.github.io/jackson-annotations/javadoc/2.5/com/fasterxml/jackson/annotation/JsonBackReference.html):

    Annotation used to indicate that associated property is part of two-way linkage between fields; and that its role is "child" (or "back") link. Value type of the property must be a bean: it can not be a Collection, Map, Array or enumeration. Linkage is handled such that the property annotated with this annotation is not serialized; and during deserialization, its value is set to instance that has the "managed" (forward) link.

Example:

Owner.java:

@JsonManagedReference
@OneToMany(mappedBy = "owner", fetch = FetchType.EAGER)
Set<Car> cars;

Car.java:

@JsonBackReference
@ManyToOne(fetch = FetchType.EAGER)
@JoinColumn(name = "owner_id")
private Owner owner;

Another solution is to use @JsonIgnore which will just set null to the field.

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

That particular phrasing is by James Iry, from his highly entertaining Brief, Incomplete and Mostly Wrong History of Programming Languages, in which he fictionally attributes it to Philip Wadler.

The original quote is from Saunders Mac Lane in Categories for the Working Mathematician, one of the foundational texts of Category Theory. Here it is in context, which is probably the best place to learn exactly what it means.

But, I'll take a stab. The original sentence is this:

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.

X here is a category. Endofunctors are functors from a category to itself (which is usually all Functors as far as functional programmers are concerned, since they're mostly dealing with just one category; the category of types - but I digress). But you could imagine another category which is the category of "endofunctors on X". This is a category in which the objects are endofunctors and the morphisms are natural transformations.

And of those endofunctors, some of them might be monads. Which ones are monads? Exactly the ones which are monoidal in a particular sense. Instead of spelling out the exact mapping from monads to monoids (since Mac Lane does that far better than I could hope to), I'll just put their respective definitions side by side and let you compare:

A monoid is...

  • A set, S
  • An operation, • : S × S ? S
  • An element of S, e : 1 ? S

...satisfying these laws:

  • (a • b) • c = a • (b • c), for all a, b and c in S
  • e • a = a • e = a, for all a in S

A monad is...

  • An endofunctor, T : X ? X (in Haskell, a type constructor of kind * -> * with a Functor instance)
  • A natural transformation, µ : T × T ? T, where × means functor composition (µ is known as join in Haskell)
  • A natural transformation, ? : I ? T, where I is the identity endofunctor on X (? is known as return in Haskell)

...satisfying these laws:

  • µ ° Tµ = µ ° µT
  • µ ° T? = µ ° ?T = 1 (the identity natural transformation)

With a bit of squinting you might be able to see that both of these definitions are instances of the same abstract concept.

SQL : BETWEEN vs <= and >=

Logically there are no difference at all. Performance-wise there are -typically, on most DBMSes- no difference at all.

Skip certain tables with mysqldump

Dump all databases with all tables but skip certain tables

on github: https://github.com/rubo77/mysql-backup.sh/blob/master/mysql-backup.sh

#!/bin/bash
# mysql-backup.sh

if [ -z "$1" ] ; then
  echo
  echo "ERROR: root password Parameter missing."
  exit
fi
DB_host=localhost
MYSQL_USER=root
MYSQL_PASS=$1
MYSQL_CONN="-u${MYSQL_USER} -p${MYSQL_PASS}"
#MYSQL_CONN=""

BACKUP_DIR=/backup/mysql/

mkdir $BACKUP_DIR -p

MYSQLPATH=/var/lib/mysql/

IGNORE="database1.table1, database1.table2, database2.table1,"

# strpos $1 $2 [$3]
# strpos haystack needle [optional offset of an input string]
strpos()
{
    local str=${1}
    local offset=${3}
    if [ -n "${offset}" ]; then
        str=`substr "${str}" ${offset}`
    else
        offset=0
    fi
    str=${str/${2}*/}
    if [ "${#str}" -eq "${#1}" ]; then
        return 0
    fi
    echo $((${#str}+${offset}))
}

cd $MYSQLPATH
for i in */; do
    if [ $i != 'performance_schema/' ] ; then 
    DB=`basename "$i"` 
    #echo "backup $DB->$BACKUP_DIR$DB.sql.lzo"
    mysqlcheck "$DB" $MYSQL_CONN --silent --auto-repair >/tmp/tmp_grep_mysql-backup
    grep -E -B1 "note|warning|support|auto_increment|required|locks" /tmp/tmp_grep_mysql-backup>/tmp/tmp_grep_mysql-backup_not
    grep -v "$(cat /tmp/tmp_grep_mysql-backup_not)" /tmp/tmp_grep_mysql-backup

    tbl_count=0
    for t in $(mysql -NBA -h $DB_host $MYSQL_CONN -D $DB -e 'show tables') 
    do
      found=$(strpos "$IGNORE" "$DB"."$t,")
      if [ "$found" == "" ] ; then 
        echo "DUMPING TABLE: $DB.$t"
        mysqldump -h $DB_host $MYSQL_CONN $DB $t --events --skip-lock-tables | lzop -3 -f -o $BACKUP_DIR/$DB.$t.sql.lzo
        tbl_count=$(( tbl_count + 1 ))
      fi
    done
    echo "$tbl_count tables dumped from database '$DB' into dir=$BACKUP_DIR"
    fi
done

With a little help of https://stackoverflow.com/a/17016410/1069083

It uses lzop which is much faster, see:http://pokecraft.first-world.info/wiki/Quick_Benchmark:_Gzip_vs_Bzip2_vs_LZMA_vs_XZ_vs_LZ4_vs_LZO

Using classes with the Arduino

On Arduino 1.0, this compiles just fine:

class A
{
  public:
   int x;
   virtual void f() { x=1; }
};

class B : public A
{
  public:
    int y;
    virtual void f() { x=2; }
};


A *a;
B *b;
const int TEST_PIN = 10;

void setup()
{
   a=new A(); 
   b=new B();
   pinMode(TEST_PIN,OUTPUT);
}

void loop()
{
   a->f();
   b->f();
   digitalWrite(TEST_PIN,(a->x == b->x) ? HIGH : LOW);
}

How to resolve TypeError: Cannot convert undefined or null to object

I solved the same problem in a React Native project. I solved it using this.

let data = snapshot.val();
if(data){
  let items = Object.values(data);
}
else{
  //return null
}

How to download Google Play Services in an Android emulator?

Check out Setting Up Google Play Services which says:

To develop an app using the Google Play services APIs, you need to set up your project with the Google Play services SDK.

If you haven't installed the Google Play services SDK yet, go get it now by following the guide to Adding SDK Packages.

To test your app when using the Google Play services SDK, you must use either:

  • A compatible Android device that runs Android 2.3 or higher and includes Google Play Store.
  • The Android emulator with an AVD that runs the Google APIs platform based on Android 4.2.2 or higher.

Switching to a TabBar tab view programmatically?

My opinion is that selectedIndex or using objectAtIndex is not necessarily the best way to switch the tab. If you reorder your tabs, a hard coded index selection might mess with your former app behavior.

If you have the object reference of the view controller you want to switch to, you can do:

tabBarController.selectedViewController = myViewController

Of course you must make sure, that myViewController really is in the list of tabBarController.viewControllers.

Read file As String

You can use org.apache.commons.io.IOUtils.toString(InputStream is, Charset chs) to do that.

e.g.

IOUtils.toString(context.getResources().openRawResource(<your_resource_id>), StandardCharsets.UTF_8)

For adding the correct library:

Add the following to your app/build.gradle file:

dependencies {
    compile 'org.apache.directory.studio:org.apache.commons.io:2.4'
}

or for the Maven repo see -> this link

For direct jar download see-> https://commons.apache.org/proper/commons-io/download_io.cgi

converting a base 64 string to an image and saving it

In my case it works only with two line of code. Test the below C# code:

String dirPath = "C:\myfolder\";
String imgName = "my_mage_name.bmp";

byte[] imgByteArray = Convert.FromBase64String("your_base64_string");
File.WriteAllBytes(dirPath + imgName, imgByteArray);

That's it. Kindly up vote if you really find this solution works for you. Thanks in advance.

How can I open a .db file generated by eclipse(android) form DDMS-->File explorer-->data--->data-->packagename-->database?

Download this Sqlite manager its the easiest one to use Sqlite manager

and drag and drop your fetched file on its running instance

only drawback of this Sqlite Manager it stop responding if you run some SQL statement that has Syntax Error in it.

So i Use Firefox Plugin Side by side also which you can find at FireFox addons

Making a <button> that's a link in HTML

A little bit easier and it looks exactly like the button in the form. Just use the input and wrap the anchor tag around it.

<a href="#"><input type="button" value="Button Text"></a>

Attach the Java Source Code

The easiest way to do this, is to install a JDK and tell Eclipse to use it as the default JRE. Use the default install.

(from memory)

Open Window -> Prefences. Select Installed Java runtimes, and choose Add. Navigate to root of your JDK (\Programs...\Java) and click Ok. Then select it to be the default JRE (checkmark).

After a workspace rebuild, you should have source attached to all JRE classes.

Scroll to a specific Element Using html

Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.

There are demo on the author's site and let our company site serve as a real-world example too.

How to force deletion of a python object?

Perhaps you are looking for a context manager?

>>> class Foo(object):
...   def __init__(self):
...     self.bar = None
...   def __enter__(self):
...     if self.bar != 'open':
...       print 'opening the bar'
...       self.bar = 'open'
...   def __exit__(self, type_, value, traceback):
...     if self.bar != 'closed':
...       print 'closing the bar', type_, value, traceback
...       self.bar = 'close'
... 
>>> 
>>> with Foo() as f:
...     # oh no something crashes the program
...     sys.exit(0)
... 
opening the bar
closing the bar <type 'exceptions.SystemExit'> 0 <traceback object at 0xb7720cfc>

Best practice to call ConfigureAwait for all server-side code

The biggest draw back I've found with using ConfigureAwait(false) is that the thread culture is reverted to the system default. If you've configured a culture e.g ...

<system.web>
    <globalization culture="en-AU" uiCulture="en-AU" />    
    ...

and you're hosting on a server whose culture is set to en-US, then you will find before ConfigureAwait(false) is called CultureInfo.CurrentCulture will return en-AU and after you will get en-US. i.e.

// CultureInfo.CurrentCulture ~ {en-AU}
await xxxx.ConfigureAwait(false);
// CultureInfo.CurrentCulture ~ {en-US}

If your application is doing anything which requires culture specific formatting of data, then you'll need to be mindful of this when using ConfigureAwait(false).

Should I use Python 32bit or Python 64bit

You do not need to use 64bit since windows will emulate 32bit programs using wow64. But using the native version (64bit) will give you more performance.

JSON.stringify doesn't work with normal Javascript array

Alternatively you can use like this

var test = new Array();
test[0]={};
test[0]['a'] = 'test';
test[1]={};
test[1]['b'] = 'test b';
var json = JSON.stringify(test);
alert(json);

Like this you JSON-ing a array.

Fixed size div?

You can set the height and width of your divs with css.

<style type="text/css">
.box {
     height: 150px;
     width: 150px;
}
</style> 

Is this what you're looking for?

Using WGET to run a cronjob PHP

If you want get output only when php fail:

php -r 'echo file_get_contents(http://www.example.com/cronit.php);'

This way you receive an email from cronjob only when the script fails and not whenever the php is called.

Removing first x characters from string?

>>> text = 'lipsum'
>>> text[3:]
'sum'

See the official documentation on strings for more information and this SO answer for a concise summary of the notation.

How to move an element into another element?

You can use:

To Insert After,

jQuery("#source").insertAfter("#destination");

To Insert inside another element,

jQuery("#source").appendTo("#destination");

The openssl extension is required for SSL/TLS protection

After trying everything, I finally managed to get this sorted. None of the above suggested solutions worked for me. My system is A PC Windows 10. In order to get this sorted I had to change the config.json file located here C:\Users\[Your User]\AppData\Roaming\Composer\. In there, you will find:

{
    "config": {
        "disable-tls": true},
    "repositories": {
        "packagist": {
            "type": "composer",
            "url": "http://repo.packagist.org" // this needs to change to 'https'
        }
    }
}

where you need to update the packagist repo url to point to the 'https' url version.

I am aware that the above selected solution will work for 95% of the cases, but as I said, that did not work for me. Hope this helps someone.

Happy coding!

How to pass data to view in Laravel?

You can pass data to the view using the with method.

return View::make('blog')->with('posts', $posts);

Could not load file or assembly Microsoft.SqlServer.management.sdk.sfc version 11.0.0.0

For those who are running into a slight variation of this problem, I just found a solution.

Pre-requisites: using VS 2015 and SQL Server 2012.

Symptom: can't load this subsystem: Microsoft.SqlServer.management.sdk.sfc version 12.0.0.0

At this point you might be like me and confused that you are using SQL Server 2012 but VS 2015 is trying to use version 12.0.0.0, which comes from SQL Server 2014. It turns out that when you install SQL Server 2012, it installs a couple of components from SQL Server 2014. At one point I removed all traces of SQL Server from my machine (using the Add Programs control panel). When I re-installed SQL Server 2012, it either didn't re-install the 2014 components or I deleted them again thinking I missed them the first time around.

The result was that I didn't have the necessary 2014 libraries on my system. I also tried to install the 2014 Shared Management Objects as pointed out above, but that didn't work because I didn't have the CLR runtime from 2014. So in order to get a VS 2015 system working with a SQL Server 2012, you have to make sure that these two 2014 packages are installed:

  • ENU\x64\SQLSysClrTypes.msi
  • ENU\x64\SharedManagementObjects.msi

from SQL Server 2014 Feature Pack. Pick the 32 bit versions if you need to.

Here is the site that helped me figure this out.

select dept names who have more than 2 employees whose salary is greater than 1000

hope this helps

select DeptName from DEPARTMENT inner join EMPLOYEE using (DeptId) where Salary>1000 group by DeptName having count(*)>2

How to delete an SVN project from SVN repository

I too felt like the accepted answer was a bit misleading as it could lead to a user inadvertently deleting multiple Projects. It is not accurate to state that the words Repository, Project and Directory are ambiguous within the context of SVN. They have specific meanings, even if the system itself doesn't enforce those meanings. The community and more importantly the SVN Clients have an agreed upon understanding of these terms which allow them to Tag, Branch and Merge.

Ideally this will help clear any confusion. As someone that has had to go from git to svn for a few projects, it can be frustrating until you learn that SVN branching and SVN projects are really talking about folder structures.

SVN Terminology

Repository

The database of commits and history for your folders and files. A repository can contain multiple 'projects' or no projects.

Project

A specific SVN folder structure which enables SVN tools to perform tagging, merging and branching. SVN does not inherently support branching. Branching was added later and is a result of a special folder structure as follows:

  • /project
    • /tags
    • /branches
    • /trunk

Note: Remember, an SVN 'Project' is a term used to define a specific folder strcuture within a Repository

Projects in a Repository

Repository Layout

As a repository is just a database of the files and directory commits, it can host multiple projects. When discussing Repositories and Projects be sure the correct term is being used.

Removing a Repository could mean removing multiple Projects!

Local SVN Directory (.svn directory at root)

When using a URL commits occur automatically.

  • svn co http://svn.server.local/svn/myrepo
  • cd myrepo

  • Remove a Project: svn rm skunkworks + svn commit

  • Remove a Directory: svn rm regulardir/subdir + svn commit
  • Remove a Project (Without Checking Out): svn rm http://svn.server.local/svn/myrepo/app1
  • Remove a Directory (Without Checking Out): svn rm http://svn.server.local/svn/myrepo/regulardir

Because an SVN Project is really a specific directory structure, removing a project is the same as removing a directory.

SVN Repository Management

There are several SVN servers available to host your repositories. The management of repositories themselves are typically done through the admin consoles of the servers. For example, Visual SVN allows you to create Repositories (databases), directories and Projects. But you cannot remove files, manage commits, rename folders, etc. from within the server console as those are SVN specific tasks. The SVN server typically manages the creation of a repository. Once a repository has been created and you have a new URL, the rest of your work is done through the svn command.

Detect click inside/outside of element with single event handler

Here's a one liner that doesn't require jquery using Node.contains:

// Get arbitrary element with id "my-element"
var myElementToCheckIfClicksAreInsideOf = document.querySelector('#my-element');
// Listen for click events on body
document.body.addEventListener('click', function (event) {
    if (myElementToCheckIfClicksAreInsideOf.contains(event.target)) {
        console.log('clicked inside');
    } else {
        console.log('clicked outside');
    }
});

If you're wondering about the edge case of checking if the click is on the element itself, Node.contains returns true for the element itself (e.g. element.contains(element) === true) so this snippet should always work.

Browser support seems to cover pretty much everything according to that MDN page as well.

Counter in foreach loop in C#

It depends what you mean by "it". The iterator knows what index it's reached, yes - in the case of a List<T> or an array. But there's no general index within IEnumerator<T>. Whether it's iterating over an indexed collection or not is up to the implementation. Plenty of collections don't support direct indexing.

(In fact, foreach doesn't always use an iterator at all. If the compile-time type of the collection is an array, the compiler will iterate over it using array[0], array[1] etc. Likewise the collection can have a method called GetEnumerator() which returns a type with the appropriate members, but without any implementation of IEnumerable/IEnumerator in sight.)

Options for maintaining an index:

  • Use a for loop
  • Use a separate variable
  • Use a projection which projects each item to an index/value pair, e.g.

     foreach (var x in list.Select((value, index) => new { value, index }))
     {
         // Use x.value and x.index in here
     }
    
  • Use my SmartEnumerable class which is a little bit like the previous option

All but the first of these options will work whether or not the collection is naturally indexed.

What is the difference between id and class in CSS, and when should I use them?

For more info on this click here.

Example

<div id="header_id" class="header_class">Text</div>

#header_id {font-color:#fff}
.header_class {font-color:#000}

(Note that CSS uses the prefix # for IDs and . for Classes.)

However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5. In CSS there is no "font-color", the style is color so the above should read:

Example

<div id="header_id" class="header_class">Text</div>

#header_id {color:#fff}
.header_class {color:#000}

The text would be white.

Why am I getting an OPTIONS request instead of a GET request?

I was able to fix it with the help of following headers

Access-Control-Allow-Origin
Access-Control-Allow-Headers
Access-Control-Allow-Credentials
Access-Control-Allow-Methods

If you are on Nodejs, here is the code you can copy/paste.

app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin','*');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH');
  next();
});

How to browse localhost on Android device?

For the mac user:

I have worked on this problem for one afternoon until I realized the Xampp I used was not the real "Xampp" It was Xampp VM which runs itself based on a Linux virtual machine. That made it not running on localhost, instead, another IP. I installed the real Xampp and run my local server on localhost and then just access it with the IP of my mac.

Hope this will help someone.

Moment js date time comparison

for date-time comparison, you can use valueOf function of the moment which provides milliseconds of the date-time, which is best for comparison:

_x000D_
_x000D_
let date1 = moment('01-02-2020','DD-MM-YYYY').valueOf()_x000D_
let date2 = moment('11-11-2012','DD-MM-YYYY').valueOf()_x000D_
_x000D_
//     alert((date1 > date2 ? 'date1' : 'date2') + " is greater..."  )_x000D_
_x000D_
if (date1 > date2) {_x000D_
   alert("date1 is greater..." )_x000D_
} else {_x000D_
   alert("date2 is greater..." )_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Rails find_or_create_by more than one attribute?

In Rails 4 you could do:

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

And use where is different:

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

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

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

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

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

Please see this relevant commit on rails/rails.

multiple conditions for JavaScript .includes() method

You can use the .some method referenced here.

The some() method tests whether at least one element in the array passes the test implemented by the provided function.

_x000D_
_x000D_
// test cases
var str1 = 'hi, how do you do?';
var str2 = 'regular string';

// do the test strings contain these terms?
var conditions = ["hello", "hi", "howdy"];

// run the tests against every element in the array
var test1 = conditions.some(el => str1.includes(el));
var test2 = conditions.some(el => str2.includes(el));

// display results
console.log(str1, ' ===> ', test1);
console.log(str2, ' ===> ', test2);
_x000D_
_x000D_
_x000D_

How to quit a java app from within the program

Runtime.getCurrentRumtime().halt(0);

How does the modulus operator work?

Basically modulus Operator gives you remainder simple Example in maths what's left over/remainder of 11 divided by 3? answer is 2

for same thing C++ has modulus operator ('%')

Basic code for explanation

#include <iostream>
using namespace std;


int main()
{
    int num = 11;
    cout << "remainder is " << (num % 3) << endl;

    return 0;
}

Which will display

remainder is 2

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

Using Axios GET with Authorization Header in React-Native App

Could not get this to work until I put Authorization in single quotes:

axios.get(URL, { headers: { 'Authorization': AuthStr } })

How to add a single item to a Pandas Series

You can use the append function to add another element to it. Only, make a series of the new element, before you append it:

test = test.append(pd.Series(200, index=[101]))

How can I get the key value in a JSON object?

You can simply traverse through the object and return if a match is found.

Here is the code:

returnKeyforValue : function() {
    var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
        for (key in JsonObj) {
        if(JsonObj[key] === "Keyvalue") {
            return key;
        }
    }
}

Select arrow style change

Working with just one class:

select {
    width: 268px;
    padding: 5px;
    font-size: 16px;
    line-height: 1;
    border: 0;
    border-radius: 5px;
    height: 34px;
    background: url(http://cdn1.iconfinder.com/data/icons/cc_mono_icon_set/blacks/16x16/br_down.png) no-repeat right #ddd;
    -webkit-appearance: none;
    background-position-x: 244px;
}

http://jsfiddle.net/qhCsJ/4120/

Python - Locating the position of a regex match in a string?

I don't think this question has been completely answered yet because all of the answers only give single match examples. The OP's question demonstrates the nuances of having 2 matches as well as a substring match which should not be reported because it is not a word/token.

To match multiple occurrences, one might do something like this:

iter = re.finditer(r"\bis\b", String)
indices = [m.start(0) for m in iter]

This would return a list of the two indices for the original string.

How to add header data in XMLHttpRequest when using formdata?

Your error

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

appears because you must call setRequestHeader after calling open. Simply move your setRequestHeader line below your open line (but before send):

xmlhttp.open("POST", url);
xmlhttp.setRequestHeader("x-filename", photoId);
xmlhttp.send(formData);

Remove pandas rows with duplicate indices

Unfortunately, I don't think Pandas allows one to drop dups off the indices. I would suggest the following:

df3 = df3.reset_index() # makes date column part of your data
df3.columns = ['timestamp','A','B','rownum'] # set names
df3 = df3.drop_duplicates('timestamp',take_last=True).set_index('timestamp') #done!

Storing SHA1 hash values in MySQL

You may still want to use VARCHAR in cases where you don't always store a hash for the user (i.e. authenticating accounts/forgot login url). Once a user has authenticated/changed their login info they shouldn't be able to use the hash and should have no reason to. You could create a separate table to store temporary hash -> user associations that could be deleted but I don't think most people bother to do this.

How to send json data in POST request using C#

You can do it with HttpWebRequest:

var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://yourUrl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Method = "POST";
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
            {
                Username = "myusername",
                Password = "pass"
            });
    streamWriter.Write(json);
    streamWriter.Flush();
    streamWriter.Close();
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
    var result = streamReader.ReadToEnd();
}

Fundamental difference between Hashing and Encryption algorithms

Encryption and hash algorithms work in similar ways. In each case, there is a need to create confusion and diffusion amongst the bits. Boiled down, confusion is creating a complex relationship between the key and the ciphertext, and diffusion is spreading the information of each bit around.

Many hash functions actually use encryption algorithms (or primitives of encryption algorithms. For example, the SHA-3 candidate Skein uses Threefish as the underlying method to process each block. The difference is that instead of keeping each block of ciphertext, they are destructively, deterministically merged together to a fixed length

Rails 4 - Strong Parameters - Nested Objects

Permitting a nested object :

params.permit( {:school => [:id , :name]}, 
               {:student => [:id, 
                            :name, 
                            :address, 
                            :city]},
                {:records => [:marks, :subject]})

How may I reference the script tag that loaded the currently-executing script?

How to get the current script element:

1. Use document.currentScript

document.currentScript will return the <script> element whose script is currently being processed.

<script>
var me = document.currentScript;
</script>

Benefits

  • Simple and explicit. Reliable.
  • Don't need to modify the script tag
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically

Problems

  • Will not work in older browsers and IE.
  • Does not work with modules <script type="module">

2. Select script by id

Giving the script an id attribute will let you easily select it by id from within using document.getElementById().

<script id="myscript">
var me = document.getElementById('myscript');
</script>

Benefits

  • Simple and explicit. Reliable.
  • Almost universally supported
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically

Problems

  • Requires adding a custom attribute to the script tag
  • id attribute may cause weird behaviour for scripts in some browsers for some edge cases

3. Select the script using a data-* attribute

Giving the script a data-* attribute will let you easily select it from within.

<script data-name="myscript">
var me = document.querySelector('script[data-name="myscript"]');
</script>

This has few benefits over the previous option.

Benefits

  • Simple and explicit.
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically

Problems

  • Requires adding a custom attribute to the script tag
  • HTML5, and querySelector() not compliant in all browsers
  • Less widely supported than using the id attribute
  • Will get around <script> with id edge cases.
  • May get confused if another element has the same data attribute and value on the page.

4. Select the script by src

Instead of using the data attributes, you can use the selector to choose the script by source:

<script src="//example.com/embed.js"></script>

In embed.js:

var me = document.querySelector('script[src="//example.com/embed.js"]');

Benefits

  • Reliable
  • Works with asynchronous scripts (defer & async)
  • Works with scripts inserted dynamically
  • No custom attributes or id needed

Problems

  • Does not work for local scripts
  • Will cause problems in different environments, like Development and Production
  • Static and fragile. Changing the location of the script file will require modifying the script
  • Less widely supported than using the id attribute
  • Will cause problems if you load the same script twice

5. Loop over all scripts to find the one you want

We can also loop over every script element and check each individually to select the one we want:

<script>
var me = null;
var scripts = document.getElementsByTagName("script")
for (var i = 0; i < scripts.length; ++i) {
    if( isMe(scripts[i])){
      me = scripts[i];
    }
}
</script>

This lets us use both previous techniques in older browsers that don't support querySelector() well with attributes. For example:

function isMe(scriptElem){
    return scriptElem.getAttribute('src') === "//example.com/embed.js";
}

This inherits the benefits and problems of whatever approach is taken, but does not rely on querySelector() so will work in older browsers.

6. Get the last executed script

Since the scripts are executed sequentially, the last script element will very often be the currently running script:

<script>
var scripts = document.getElementsByTagName( 'script' );
var me = scripts[ scripts.length - 1 ];
</script>

Benefits

  • Simple.
  • Almost universally supported
  • No custom attributes or id needed

Problems

  • Does not work with asynchronous scripts (defer & async)
  • Does not work with scripts inserted dynamically

How to implement history.back() in angular.js

Ideally use a simple directive to keep controllers free from redundant $window

app.directive('back', ['$window', function($window) {
        return {
            restrict: 'A',
            link: function (scope, elem, attrs) {
                elem.bind('click', function () {
                    $window.history.back();
                });
            }
        };
    }]);

Use like this:

<button back>Back</button>

How to check if a string in Python is in ASCII?

A sting (str-type) in Python is a series of bytes. There is no way of telling just from looking at the string whether this series of bytes represent an ascii string, a string in a 8-bit charset like ISO-8859-1 or a string encoded with UTF-8 or UTF-16 or whatever.

However if you know the encoding used, then you can decode the str into a unicode string and then use a regular expression (or a loop) to check if it contains characters outside of the range you are concerned about.

count number of rows in a data frame in R based on group

Using the example data set that Ananda dummied up, here's an example using aggregate(), which is part of core R. aggregate() just needs something to count as function of the different values of MONTH-YEAR. In this case, I used VALUE as the thing to count:

aggregate(cbind(count = VALUE) ~ MONTH.YEAR, 
          data = mydf, 
          FUN = function(x){NROW(x)})

which gives you..

  MONTH.YEAR count
1  FEB. 2012     2
2  JAN. 2012     2
3  MAR. 2012     1

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

Set line spacing

lineSpacing is used in React Native (or native mobile apps).

For web you can use letterSpacing (or letter-spacing)

How to remove numbers from a string?

A secondary option would be to match and return non-digits with some expression similar to,

/\D+/g

which would likely work for that specific string in the question (1 ding ?).

Demo

Test

_x000D_
_x000D_
function non_digit_string(str) {_x000D_
 const regex = /\D+/g;_x000D_
 let m;_x000D_
_x000D_
 non_digit_arr = [];_x000D_
 while ((m = regex.exec(str)) !== null) {_x000D_
  // This is necessary to avoid infinite loops with zero-width matches_x000D_
  if (m.index === regex.lastIndex) {_x000D_
   regex.lastIndex++;_x000D_
  }_x000D_
_x000D_
_x000D_
  m.forEach((match, groupIndex) => {_x000D_
   if (match.trim() != '') {_x000D_
    non_digit_arr.push(match.trim());_x000D_
   }_x000D_
  });_x000D_
 }_x000D_
 return non_digit_arr;_x000D_
}_x000D_
_x000D_
const str = `1 ding ? 124_x000D_
12 ding ?_x000D_
123 ding ? 123`;_x000D_
console.log(non_digit_string(str));
_x000D_
_x000D_
_x000D_


If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

How to set a Timer in Java?

Use this

long startTime = System.currentTimeMillis();
long elapsedTime = 0L.

while (elapsedTime < 2*60*1000) {
    //perform db poll/check
    elapsedTime = (new Date()).getTime() - startTime;
}

//Throw your exception

Prevent form submission on Enter key press

<form id="form1" runat="server" onkeypress="return event.keyCode != 13;">

Add this Code In Your HTML Page...it will disable ...Enter Button..

How can I make the computer beep in C#?

Try this

Console.WriteLine("\a")

Accessing all items in the JToken

In addition to the accepted answer I would like to give an answer that shows how to iterate directly over the Newtonsoft collections. It uses less code and I'm guessing its more efficient as it doesn't involve converting the collections.

using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//Parse the data
JObject my_obj = JsonConvert.DeserializeObject<JObject>(your_json);

foreach (KeyValuePair<string, JToken> sub_obj in (JObject)my_obj["ADDRESS_MAP"])
{
    Console.WriteLine(sub_obj.Key);
}

I started doing this myself because JsonConvert automatically deserializes nested objects as JToken (which are JObject, JValue, or JArray underneath I think).

I think the parsing works according to the following principles:

  • Every object is abstracted as a JToken

  • Cast to JObject where you expect a Dictionary

  • Cast to JValue if the JToken represents a terminal node and is a value

  • Cast to JArray if its an array

  • JValue.Value gives you the .NET type you need

Pinging servers in Python

WINDOWS ONLY - Can't believe no-ones cracked open Win32_PingStatus Using a simple WMI query we return an object full of really detailed info for free

import wmi


# new WMI object
c = wmi.WMI()

# here is where the ping actually is triggered
x = c.Win32_PingStatus(Address='google.com')

# how big is this thing? - 1 element
print 'length x: ' ,len(x)


#lets look at the object 'WMI Object:\n'
print x


#print out the whole returned object
# only x[0] element has values in it
print '\nPrint Whole Object - can directly reference the field names:\n'
for i in x:
    print i



#just a single field in the object - Method 1
print 'Method 1 ( i is actually x[0] ) :'
for i in x:
    print 'Response:\t', i.ResponseTime, 'ms'
    print 'TTL:\t', i.TimeToLive


#or better yet directly access the field you want
print '\npinged ', x[0].ProtocolAddress, ' and got reply in ', x[0].ResponseTime, 'ms'

sample output

How to check a string for a special character?

Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.

Use this method to detect special characters not including whitespaces:

import re

def detect_special_characer(pass_string): 
  regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]') 
  if(regex.search(pass_string) == None): 
    res = False
  else: 
    res = True
  return(res)

Git: Installing Git in PATH with GitHub client for Windows

Having searched around several posts. On Windows 10 having downloaded and installed Github for Windows 2.10.2 I found the git.exe in

C:\Users\<user>\AppData\Local\Programs\Git\bin

and the git-cmd.exe in

C:\Users\<user>\AppData\Local\Programs\Git

Please note the change to Programs folder within Local from the above posts.

Set disable attribute based on a condition for Html.TextBoxFor

I like the extension method approach so you don't have to pass through all possible parameters.
However using Regular expressions can be quite tricky (and somewhat slower) so I used XDocument instead:

public static MvcHtmlString SetDisabled(this MvcHtmlString html, bool isDisabled)
{
    var xDocument = XDocument.Parse(html.ToHtmlString());
    if (!(xDocument.FirstNode is XElement element))
    {
        return html;
    }

    element.SetAttributeValue("disabled", isDisabled ? "disabled" : null);
    return MvcHtmlString.Create(element.ToString());
}

Use the extension method like this:
@Html.EditorFor(m => m.MyProperty).SetDisabled(Model.ExpireDate == null)

Tool to convert java to c# code

Microsoft has a tool called JLCA: Java Language Conversion Assistant. I can't tell if it is better though, as I have never compared the two.

Detect WebBrowser complete page loading

I did the following:

void BrowserDocumentCompleted(object sender,
        WebBrowserDocumentCompletedEventArgs e)
{
  if (e.Url.AbsolutePath != (sender as WebBrowser).Url.AbsolutePath)
    return; 

  //The page is finished loading 
}

The last page loaded tends to be the one navigated to, so this should work.

From here.

How to workaround 'FB is not defined'?

There is solution for you :)

You must run your script after window loaded

if you use jQuery, you can use simple way:

<div id="fb-root"></div>
<script>
    window.fbAsyncInit = function() {
        FB.init({
            appId      : 'your-app-id',
            xfbml      : true,
            status     : true,
            version    : 'v2.5'
        });
    };

    (function(d, s, id){
        var js, fjs = d.getElementsByTagName(s)[0];
        if (d.getElementById(id)) {return;}
        js = d.createElement(s); js.id = id;
        js.src = "//connect.facebook.net/en_US/sdk.js";
        fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>

<script>
$(window).load(function() {
    var comment_callback = function(response) {
        console.log("comment_callback");
        console.log(response);
    }
    FB.Event.subscribe('comment.create', comment_callback);
    FB.Event.subscribe('comment.remove', comment_callback);
});
</script>

Is there an equivalent of 'which' on the Windows command line?

While later versions of Windows have a where command, you can also do this with Windows XP by using the environment variable modifiers, as follows:

c:\> for %i in (cmd.exe) do @echo.   %~$PATH:i
   C:\WINDOWS\system32\cmd.exe

c:\> for %i in (python.exe) do @echo.   %~$PATH:i
   C:\Python25\python.exe

You don't need any extra tools and it's not limited to PATH since you can substitute any environment variable (in the path format, of course) that you wish to use.


And, if you want one that can handle all the extensions in PATHEXT (as Windows itself does), this one does the trick:

@echo off
setlocal enableextensions enabledelayedexpansion

:: Needs an argument.

if "x%1"=="x" (
    echo Usage: which ^<progName^>
    goto :end
)

:: First try the unadorned filenmame.

set fullspec=
call :find_it %1

:: Then try all adorned filenames in order.

set mypathext=!pathext!
:loop1
    :: Stop if found or out of extensions.

    if "x!mypathext!"=="x" goto :loop1end

    :: Get the next extension and try it.

    for /f "delims=;" %%j in ("!mypathext!") do set myext=%%j
    call :find_it %1!myext!

:: Remove the extension (not overly efficient but it works).

:loop2
    if not "x!myext!"=="x" (
        set myext=!myext:~1!
        set mypathext=!mypathext:~1!
        goto :loop2
    )
    if not "x!mypathext!"=="x" set mypathext=!mypathext:~1!

    goto :loop1
:loop1end

:end
endlocal
goto :eof

:: Function to find and print a file in the path.

:find_it
    for %%i in (%1) do set fullspec=%%~$PATH:i
    if not "x!fullspec!"=="x" @echo.   !fullspec!
    goto :eof

It actually returns all possibilities but you can tweak it quite easily for specific search rules.

How to add a custom right-click menu to a webpage?

You should remember if you want to use the Firefox only solution, if you want to add it to the whole document you should add contextmenu="mymenu" to the <html> tag not to the body tag.
You should pay attention to this.

What is meant by immutable?

Actually String is not immutable if you use the wikipedia definition suggested above.

String's state does change post construction. Take a look at the hashcode() method. String caches the hashcode value in a local field but does not calculate it until the first call of hashcode(). This lazy evaluation of hashcode places String in an interesting position as an immutable object whose state changes, but it cannot be observed to have changed without using reflection.

So maybe the definition of immutable should be an object that cannot be observed to have changed.

If the state changes in an immutable object after it has been created but no-one can see it (without reflection) is the object still immutable?

Insert new item in array on any position in PHP

This is what worked for me for the associative array:

/*
 * Inserts a new key/value after the key in the array.
 *
 * @param $key
 *   The key to insert after.
 * @param $array
 *   An array to insert in to.
 * @param $new_key
 *   The key to insert.
 * @param $new_value
 *   An value to insert.
 *
 * @return
 *   The new array if the key exists, FALSE otherwise.
 *
 * @see array_insert_before()
 */
function array_insert_after($key, array &$array, $new_key, $new_value) {
  if (array_key_exists($key, $array)) {
    $new = array();
    foreach ($array as $k => $value) {
      $new[$k] = $value;
      if ($k === $key) {
        $new[$new_key] = $new_value;
      }
    }
    return $new;
  }
  return FALSE;
}

The function source - this blog post. There's also handy function to insert BEFORE specific key.

How do you decrease navbar height in Bootstrap 3?

In Bootstrap 4

In my case I have just changed the .navbar min-height and the links font-size and it decreased the navbar.

For example:

.navbar{
    min-height:12px;
}
.navbar  a {
    font-size: 11.2px;
}

And this also worked for increasing the navbar height.

This also helps to change the navbar size when scrolling down the browser.

Converting a sentence string to a string array of words in Java

You can use BreakIterator.getWordInstance to find all words in a string.

public static List<String> getWords(String text) {
    List<String> words = new ArrayList<String>();
    BreakIterator breakIterator = BreakIterator.getWordInstance();
    breakIterator.setText(text);
    int lastIndex = breakIterator.first();
    while (BreakIterator.DONE != lastIndex) {
        int firstIndex = lastIndex;
        lastIndex = breakIterator.next();
        if (lastIndex != BreakIterator.DONE && Character.isLetterOrDigit(text.charAt(firstIndex))) {
            words.add(text.substring(firstIndex, lastIndex));
        }
    }

    return words;
}

Test:

public static void main(String[] args) {
    System.out.println(getWords("A PT CR M0RT BOUSG SABN NTE TR/GB/(G) = RAND(MIN(XXX, YY + ABC))"));
}

Ouput:

[A, PT, CR, M0RT, BOUSG, SABN, NTE, TR, GB, G, RAND, MIN, XXX, YY, ABC]

django: TypeError: 'tuple' object is not callable

There is comma missing in your tuple.

insert the comma between the tuples as shown:

pack_size = (('1', '1'),('3', '3'),(b, b),(h, h),(d, d), (e, e),(r, r))

Do the same for all

Oracle "Partition By" Keyword

The PARTITION BY clause sets the range of records that will be used for each "GROUP" within the OVER clause.

In your example SQL, DEPT_COUNT will return the number of employees within that department for every employee record. (It is as if you're de-nomalising the emp table; you still return every record in the emp table.)

emp_no  dept_no  DEPT_COUNT
1       10       3
2       10       3
3       10       3 <- three because there are three "dept_no = 10" records
4       20       2
5       20       2 <- two because there are two "dept_no = 20" records

If there was another column (e.g., state) then you could count how many departments in that State.

It is like getting the results of a GROUP BY (SUM, AVG, etc.) without the aggregating the result set (i.e. removing matching records).

It is useful when you use the LAST OVER or MIN OVER functions to get, for example, the lowest and highest salary in the department and then use that in a calculation against this records salary without a sub select, which is much faster.

Read the linked AskTom article for further details.

Difference between static STATIC_URL and STATIC_ROOT on Django

All the answers above are helpful but none solved my issue. In my production file, my STATIC_URL was https://<URL>/static and I used the same STATIC_URL in my dev settings.py file.

This causes a silent failure in django/conf/urls/static.py.

The test elif not settings.DEBUG or '://' in prefix: picks up the '//' in the URL and does not add the static URL pattern, causing no static files to be found.

It would be thoughtful if Django spit out an error message stating you can't use a http(s):// with DEBUG = True

I had to change STATIC_URL to be '/static/'

Swing vs JavaFx for desktop applications

No one has mentioned it, but JavaFX does not compile or run on certain architectures deemed "servers" by Oracle (e.g. Solaris), because of the missing "jfxrt.jar" support. Stick with SWT, until further notice.

Box shadow for bottom side only

Specify negative value to spread value. This works for me:

box-shadow: 0 2px 3px -1px rgba(0, 0, 0, 0.1);

New lines inside paragraph in README.md

Interpreting newlines as <br /> used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.

Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change

a
b
c

into

a__
b__
c

(where _ is a blank space).

Or, you can add explicit <br /> tags.

a <br />
b <br />
c

parent & child with position fixed, parent overflow:hidden bug

I had a similar, quite complex problem with a fluid layout, where the right column had a fixed width and the left one had a flexible width. My fixed container should have the same width as the flexible column. Here is my solution:

HTML

<div id="wrapper">
    <div id="col1">
    <div id="fixed-outer">
        <div id="fixed-inner">inner</div>
    </div>
    COL1<br />Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
    </div>
    <div id="col2">COL2</div>
</div>

CSS

    #wrapper {
    padding-left: 20px;
}

#col1 {
    background-color: grey;
    float: left;
    margin-right: -200px; /* #col2 width */
    width: 100%;
}

#col2 {
    background-color: #ddd;
    float: left;
    height: 400px;
    width: 200px;
}

#fixed-outer {
    background: yellow;
    border-right: 2px solid red;
    height: 30px;
    margin-left: -420px; /* 2x #col2 width + #wrapper padding-left */
    overflow: hidden;
    padding-right: 200px; /* #col2 width */
    position: fixed;
    width: 100%;
}

#fixed-inner {
    background: orange;
    border-left: 2px solid blue;
    border-top: 2px solid blue;
    height: 30px;
    margin-left: 420px; /* 2x #col2 width + #wrapper padding-left */
    position: absolute;
    width: 100%;
}

Live Demo: http://jsfiddle.net/hWCub/

how to open a page in new tab on button click in asp.net?

You have to use Javascript since code behind is server side only. I am pretty sure that this works.

<asp:Button ID="btnNewEntry" runat="Server" CssClass="button" Text="New Entry" OnClick="btnNewEntry_Click" OnClientClick="aspnetForm.target ='_blank';"/>

protected void btnNewEntry_Click(object sender, EventArgs e)
{
  Response.Redirect("New.aspx");
}

How to empty a redis database?

Be careful here.

FlushDB deletes all keys in the current database while FlushALL deletes all keys in all databases on the current host.

How to check if a string array contains one string in JavaScript?

You can use the indexOfmethod and "extend" the Array class with the method contains like this:

Array.prototype.contains = function(element){
    return this.indexOf(element) > -1;
};

with the following results:

["A", "B", "C"].contains("A") equals true

["A", "B", "C"].contains("D") equals false

MySQL Workbench: "Can't connect to MySQL server on 127.0.0.1' (10061)" error

I have tried all the method. I will suggest you to reinstall it.

Docker: adding a file from a parent directory

With docker-compose, you could set context folder:

#docker-compose.yml
version: '3.3'    
services:
      yourservice:
        build:
          context: ./
          dockerfile: ./docker/yourservice/Dockerfile

Convert array to JSON string in swift

Swift 3.0 - 4.0 version

do {

    //Convert to Data
    let jsonData = try JSONSerialization.data(withJSONObject: dictionaryOrArray, options: JSONSerialization.WritingOptions.prettyPrinted)

    //Convert back to string. Usually only do this for debugging
    if let JSONString = String(data: jsonData, encoding: String.Encoding.utf8) {
       print(JSONString)
    }

    //In production, you usually want to try and cast as the root data structure. Here we are casting as a dictionary. If the root object is an array cast as [Any].
    var json = try JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? [String: Any]


} catch {
    print(error.description)
}

The JSONSerialization.WritingOptions.prettyPrinted option gives it to the eventual consumer in an easier to read format if they were to print it out in the debugger.

Reference: Apple Documentation

The JSONSerialization.ReadingOptions.mutableContainers option lets you mutate the returned array's and/or dictionaries.

Reference for all ReadingOptions: Apple Documentation

NOTE: Swift 4 has the ability to encode and decode your objects using a new protocol. Here is Apples Documentation, and a quick tutorial for a starting example.

How do I get the entity that represents the current user in Symfony2?

In symfony >= 3.2, documentation states that:

An alternative way to get the current user in a controller is to type-hint the controller argument with UserInterface (and default it to null if being logged-in is optional):

use Symfony\Component\Security\Core\User\UserInterface\UserInterface;

public function indexAction(UserInterface $user = null)
{
    // $user is null when not logged-in or anon.
}

This is only recommended for experienced developers who don't extend from the Symfony base controller and don't use the ControllerTrait either. Otherwise, it's recommended to keep using the getUser() shortcut.

Blog post about it

Set size on background image with CSS?

In support of the answer that @tetra gave, I want to point out that if the image is an SVG, then resizing the actual image is not necessary.

Since an SVG file is just XML you can specify whatever size you want it to appear within the XML.

However, if you are using the same SVG image in different places and need it to be different sizes, then using background-size is very helpful. SVG files are inherently smaller than raster images anyway and resizing on the fly with CSS can be very helpful without any performance cost that I am aware of, and certainly little to no loss of quality.

Here is a quick example:

<div class="hasBackgroundImage">content</div>

.hasBackgroundImage
{
    background: transparent url('/image/background.svg') no-repeat 10px 5px;
    background-size: 1.4em;
}

(Note: this works for me in OS X 10.7 with Firefox 8, Safari 5.1, and Chrome 16.0.912.63)

replace all occurrences in a string

Brighams answer uses literal regexp.

Solution with a Regex object.

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

TRY IT HERE : JSFiddle Working Example

MySQL LIKE IN()?

Just note to anyone trying the REGEXP to use "LIKE IN" functionality.

IN allows you to do:

field IN (
'val1',
'val2',
'val3'
)

In REGEXP this won't work

REGEXP '
val1$|
val2$|
val3$
'

It has to be in one line like this:

REGEXP 'val1$|val2$|val3$'

Cannot attach the file *.mdf as database

To fix this using SQL SERVER Management Studio

Your problem: You get an error such as 'Cannot attach the file 'YourDB.mdf' as database 'YourConnStringNamedContext';

Reason: happens because you deleted the backing files .mdf, ldf without actually deleting the database within the running instance of SqlLocalDb; re-running the code in VS won't help because you cannot re-create a DB with the same name (and that's why renaming works, but leaves the old phantom db name lying around).

The Fix: I am using VS2012, adopt similarly for a different version.

Navigate to below path and enter

c:\program files\microsoft sql server\110\Tools\Binn>sqllocaldb info

Above cmd shows the instance names, including 'v11.0'

If the instance is already running, enter at the prompt

sqllocaldb info v11.0

Note the following info Owner: YourPCName\Username , State: Running , Instance pipe name: np:\.\pipe\LOCALDB#12345678\tsql\query , where 123456789 is some random alphanumeric

If State is not running or stopped, start the instance with

sqllocaldb start v11.0

and extract same info as above.

In the SS Management Studio 'Connect' dialog box enter

server name: np:\.\pipe\LOCALDB#12345678\tsql\query

auth: Windows auth

user name: (same as Owner, it is grayed out for Win. auth.)

Once connected, find the phantom DB which you deleted (e.g. YourDB.mdf should have created a db named YourDB), and really delete it.

Done! Once it's gone, VS EF should have no problem re-creating it.

Creating and writing lines to a file

You'll need to deal with File System Object. See this OpenTextFile method sample.

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

y my case i solved this by named it in the "Identifier" property of Table View Cell:

enter image description here

Don't forgot: to declare in your Class: UITableViewDataSource

 let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as UITableViewCell

Drawing Circle with OpenGL

Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius

void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
    int i;
    int triangleAmount = 20; //# of triangles used to draw circle

    //GLfloat radius = 0.8f; //radius
    GLfloat twicePi = 2.0f * PI;

    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= triangleAmount; i++) {
        glVertex2f(
            x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
            y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
        );
    }
    glEnd();
}

How can I export data to an Excel file

You can use ExcelDataReader to read existing Excel file:

using (var stream = File.Open("C:\\temp\\input.xlsx", FileMode.Open, FileAccess.Read))
{
    using (var reader = ExcelReaderFactory.CreateReader(stream))
    {
        while (reader.Read())
        {
            for (var i = 0; i < reader.FieldCount; i++)
            {
                var value = reader.GetValue(i)?.ToString();
            }
        }
    }
}

After you collected all data needed you can try my SwiftExcel library to export it to the new Excel file:

using (var ew = new ExcelWriter("C:\\temp\\output.xlsx"))
{
    for (var i = 1; i < 10; i++)
    {
        ew.Write("your_data", i, 1);
    }
}

Nuget commands to install both libraries:

Install-Package ExcelDataReader

Install-Package SwiftExcel

'import' and 'export' may only appear at the top level

Using webpack 4.14.0 and babel-cli 6.26 I had to install this Babel plugin to fix the SyntaxError: 'import' and 'export' may only appear at the top level error: babel-plugin-syntax-dynamic-import

It was linked through from the Webpack Code Splitting Docs.

What is the exact meaning of Git Bash?

git bash is a shell where:

See "Fix msysGit Portable $HOME location":

On a Windows 64:

C:\Windows\SysWOW64\cmd.exe /c ""C:\Prog\Git\1.7.1\bin\sh.exe" --login -i"

This differs from git-cmd.bat, which provides git commands in a plain DOS command prompt.

A tool like GitHub for Windows (G4W) provides different shell for git (including a PowerShell one)


Update April 2015:

Note: the git bash in msysgit/Git for windows 1.9.5 is an old one:

GNU bash, version 3.1.20(4)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.

But with the phasing out of msysgit (Q4 2015) and the new Git For Windows (Q2 2015), you now have Git for Windows 2.3.5.
It has a much more recent bash, based on the 64bits msys2 project, an independent rewrite of MSYS, based on modern Cygwin (POSIX compatibility layer) and MinGW-w64 with the aim of better interoperability with native Windows software. msys2 comes with its own installer too.

The git bash is now (with the new Git For Windows):

GNU bash, version 4.3.33(3)-release (x86_64-pc-msys)
Copyright (C) 2013 Free Software Foundation, Inc.

Original answer (June 2013) More precisely, from msygit wiki:

Historically, Git on Windows was only officially supported using Cygwin.
To help make a native Windows version, this project was started, based on the mingw fork.

To make the milky 'soup' of project names more clear, we say like this:

  • msysGit - is the name of this project, a build environment for Git for Windows, which releases the official binaries
  • MinGW - is a minimalist development environment for native Microsoft Windows applications.
    It is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as a fork() call
  • MSYS - is a Bourne Shell command line interpreter system, is used by MinGW (and others), was forked in the past from Cygwin
  • Cygwin - a Linux like environment, which was used in the past to build Git for Windows, nowadays has no relation to msysGit

So, your two lines description about "git bash" are:

"Git bash" is a msys shell included in "Git for Windows", and is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.


Reminder:

msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.

msysGit is not Git for Windows; that is an installer which installs Git -- and only Git.

See more in "Difference between msysgit and Cygwin + git?".

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

If you don't have any data assigned already to you database do the following:

  1. Go to app/Providers/AppServiceProvide.php and add

use Illuminate\Support\ServiceProvider;

and inside of the method boot();

Schema::defaultStringLength(191);

  1. Now delete the records in your database, user table for ex.

  2. run the following

php artisan config:cache

php artisan migrate

convert string to number node.js

Not a full answer Ok so this is just to supplement the information about parseInt, which is still very valid. Express doesn't allow the req or res objects to be modified at all (immutable). So if you want to modify/use this data effectively, you must copy it to another variable (var year = req.params.year).

Export HTML page to PDF on user click using JavaScript

This is because you define your "doc" variable outside of your click event. The first time you click the button the doc variable contains a new jsPDF object. But when you click for a second time, this variable can't be used in the same way anymore. As it is already defined and used the previous time.

change it to:

$(function () {

    var specialElementHandlers = {
        '#editor': function (element,renderer) {
            return true;
        }
    };
 $('#cmd').click(function () {
        var doc = new jsPDF();
        doc.fromHTML(
            $('#target').html(), 15, 15, 
            { 'width': 170, 'elementHandlers': specialElementHandlers }, 
            function(){ doc.save('sample-file.pdf'); }
        );

    });  
});

and it will work.

Difference between web reference and service reference?

The service reference is the newer interface for adding references to all manner of WCF services (they may not be web services) whereas Web reference is specifically concerned with ASMX web references.

You can access web references via the advanced options in add service reference (if I recall correctly).

I'd use service reference because as I understand it, it's the newer mechanism of the two.

Using getline() in C++

If you're using getline() after cin >> something, you need to flush the newline character out of the buffer in between. You can do it by using cin.ignore().

It would be something like this:

string messageVar;
cout << "Type your message: ";
cin.ignore(); 
getline(cin, messageVar);

This happens because the >> operator leaves a newline \n character in the input buffer. This may become a problem when you do unformatted input, like getline(), which reads input until a newline character is found. This happening, it will stop reading immediately, because of that \n that was left hanging there in your previous operation.

How to set up tmux so that it starts up with specified windows opened?

Use tmuxinator - it allows you to have multiple sessions configured, and you can choose which one to launch at any given time. You can launch commands in particular windows or panes and give titles to windows. Here is an example use with developing Django applications.

Sample config file:

# ~/.tmuxinator/project_name.yml
# you can make as many tabs as you wish...

project_name: Tmuxinator
project_root: ~/code/rails_project
socket_name: foo # Not needed. Remove to use default socket
rvm: 1.9.2@rails_project
pre: sudo /etc/rc.d/mysqld start
tabs:
  - editor:
      layout: main-vertical
      panes:
        - vim
        - #empty, will just run plain bash
        - top
  - shell: git pull
  - database: rails db
  - server: rails s
  - logs: tail -f logs/development.log
  - console: rails c
  - capistrano:
  - server: ssh me@myhost

See the README at the above link for a full explanation.

Android getText from EditText field

Sample code for How to get text from EditText.

Android Java Syntax

EditText text = (EditText)findViewById(R.id.vnosEmaila);
String value = text.getText().toString();

Kotlin Syntax

val text = findViewById<View>(R.id.vnosEmaila) as EditText
val value = text.text.toString()

How to convert an Array to a Set in Java

Quickly : you can do :

// Fixed-size list
List list = Arrays.asList(array);

// Growable list
list = new LinkedList(Arrays.asList(array));

// Duplicate elements are discarded
Set set = new HashSet(Arrays.asList(array));

and to reverse

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

Failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

CONNECTION_REFUSED is standard when the port is closed, but it could be rejected because SSL is failing authentication (one of a billion reasons). Did you configure SSL with Ratchet? (Apache is bypassed) Did you try without SSL in JavaScript?

I don't think Ratchet has built-in support for SSL. But even if it does you'll want to try the ws:// protocol first; it's a lot simpler, easier to debug, and closer to telnet. Chrome or the socket service may also be generating the REFUSED error if the service doesn't support SSL (because you explicitly requested SSL).

However the refused message is likely a server side problem, (usually port closed).

Subtract 1 day with PHP

 date('Y-m-d',(strtotime ( '-1 day' , strtotime ( $date) ) ));

How to change JDK version for an Eclipse project

Right click project -> Properties -> Java Build Path -> select JRE System Library click Edit and select JDK or JRE after then click Java Compiler and select Compiler compliance level to 1.8

enter image description here

enter image description here

enter image description here

How to prevent column break within an element?

I faced same issue while using card-columns

i fixed it using

 display: inline-flex ;
 column-break-inside: avoid;
 width:100%;

Flutter - The method was called on null

Because of your initialization wrong.

Don't do like this,

MethodName _methodName;

Do like this,

MethodName _methodName = MethodName();

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

Just click red button to stop all services on eclipse than re- run application as Spring Boot Application - This worked for me.

Save range to variable

To save a range and then call it later, you were just missing the "Set"

Set Remember_Range = Selection    or    Range("A3")
Remember_Range.Activate

But for copying and pasting, this quicker. Cuts out the middle man and its one line

Sheets("Copy").Range("A3").Value = Sheets("Paste").Range("A3").Value

How to use OrderBy with findAll in Spring Data

Please have a look at the Spring Data JPA - Reference Documentation, section 5.3. Query Methods, especially at section 5.3.2. Query Creation, in "Table 3. Supported keywords inside method names" (links as of 2019-05-03).

I think it has exactly what you need and same query as you stated should work...

Get Base64 encode file-data from Input Form

I've started to think that using the 'iframe' for Ajax style upload might be a much better choice for my situation until HTML5 comes full circle and I don't have to support legacy browsers in my app!

Reinitialize Slick js after successful ajax call

You should use the unslick method:

function getSliderSettings(){
  return {
    infinite: true,
    slidesToShow: 3,
    slidesToScroll: 1
  }
}

$.ajax({
  type: 'get',
  url: '/public/index',
  dataType: 'script',
  data: data_send,
  success: function() {
    $('.skills_section').slick('unslick'); /* ONLY remove the classes and handlers added on initialize */
    $('.my-slide').remove(); /* Remove current slides elements, in case that you want to show new slides. */
    $('.skills_section').slick(getSliderSettings()); /* Initialize the slick again */
  }
});

Validating input using java.util.Scanner

Overview of Scanner.hasNextXXX methods

java.util.Scanner has many hasNextXXX methods that can be used to validate input. Here's a brief overview of all of them:

Scanner is capable of more, enabled by the fact that it's regex-based. One important feature is useDelimiter(String pattern), which lets you define what pattern separates your tokens. There are also find and skip methods that ignores delimiters.

The following discussion will keep the regex as simple as possible, so the focus remains on Scanner.


Example 1: Validating positive ints

Here's a simple example of using hasNextInt() to validate positive int from the input.

Scanner sc = new Scanner(System.in);
int number;
do {
    System.out.println("Please enter a positive number!");
    while (!sc.hasNextInt()) {
        System.out.println("That's not a number!");
        sc.next(); // this is important!
    }
    number = sc.nextInt();
} while (number <= 0);
System.out.println("Thank you! Got " + number);

Here's an example session:

Please enter a positive number!
five
That's not a number!
-3
Please enter a positive number!
5
Thank you! Got 5

Note how much easier Scanner.hasNextInt() is to use compared to the more verbose try/catch Integer.parseInt/NumberFormatException combo. By contract, a Scanner guarantees that if it hasNextInt(), then nextInt() will peacefully give you that int, and will not throw any NumberFormatException/InputMismatchException/NoSuchElementException.

Related questions


Example 2: Multiple hasNextXXX on the same token

Note that the snippet above contains a sc.next() statement to advance the Scanner until it hasNextInt(). It's important to realize that none of the hasNextXXX methods advance the Scanner past any input! You will find that if you omit this line from the snippet, then it'd go into an infinite loop on an invalid input!

This has two consequences:

  • If you need to skip the "garbage" input that fails your hasNextXXX test, then you need to advance the Scanner one way or another (e.g. next(), nextLine(), skip, etc).
  • If one hasNextXXX test fails, you can still test if it perhaps hasNextYYY!

Here's an example of performing multiple hasNextXXX tests.

Scanner sc = new Scanner(System.in);
while (!sc.hasNext("exit")) {
    System.out.println(
        sc.hasNextInt() ? "(int) " + sc.nextInt() :
        sc.hasNextLong() ? "(long) " + sc.nextLong() :  
        sc.hasNextDouble() ? "(double) " + sc.nextDouble() :
        sc.hasNextBoolean() ? "(boolean) " + sc.nextBoolean() :
        "(String) " + sc.next()
    );
}

Here's an example session:

5
(int) 5
false
(boolean) false
blah
(String) blah
1.1
(double) 1.1
100000000000
(long) 100000000000
exit

Note that the order of the tests matters. If a Scanner hasNextInt(), then it also hasNextLong(), but it's not necessarily true the other way around. More often than not you'd want to do the more specific test before the more general test.


Example 3 : Validating vowels

Scanner has many advanced features supported by regular expressions. Here's an example of using it to validate vowels.

Scanner sc = new Scanner(System.in);
System.out.println("Please enter a vowel, lowercase!");
while (!sc.hasNext("[aeiou]")) {
    System.out.println("That's not a vowel!");
    sc.next();
}
String vowel = sc.next();
System.out.println("Thank you! Got " + vowel);

Here's an example session:

Please enter a vowel, lowercase!
5
That's not a vowel!
z
That's not a vowel!
e
Thank you! Got e

In regex, as a Java string literal, the pattern "[aeiou]" is what is called a "character class"; it matches any of the letters a, e, i, o, u. Note that it's trivial to make the above test case-insensitive: just provide such regex pattern to the Scanner.

API links

Related questions

References


Example 4: Using two Scanner at once

Sometimes you need to scan line-by-line, with multiple tokens on a line. The easiest way to accomplish this is to use two Scanner, where the second Scanner takes the nextLine() from the first Scanner as input. Here's an example:

Scanner sc = new Scanner(System.in);
System.out.println("Give me a bunch of numbers in a line (or 'exit')");
while (!sc.hasNext("exit")) {
    Scanner lineSc = new Scanner(sc.nextLine());
    int sum = 0;
    while (lineSc.hasNextInt()) {
        sum += lineSc.nextInt();
    }
    System.out.println("Sum is " + sum);
}

Here's an example session:

Give me a bunch of numbers in a line (or 'exit')
3 4 5
Sum is 12
10 100 a million dollar
Sum is 110
wait what?
Sum is 0
exit

In addition to Scanner(String) constructor, there's also Scanner(java.io.File) among others.


Summary

  • Scanner provides a rich set of features, such as hasNextXXX methods for validation.
  • Proper usage of hasNextXXX/nextXXX in combination means that a Scanner will NEVER throw an InputMismatchException/NoSuchElementException.
  • Always remember that hasNextXXX does not advance the Scanner past any input.
  • Don't be shy to create multiple Scanner if necessary. Two simple Scanner is often better than one overly complex Scanner.
  • Finally, even if you don't have any plans to use the advanced regex features, do keep in mind which methods are regex-based and which aren't. Any Scanner method that takes a String pattern argument is regex-based.
    • Tip: an easy way to turn any String into a literal pattern is to Pattern.quote it.

CSS:Defining Styles for input elements inside a div

Like this.

.divContainer input[type="text"] {
  width:150px;
}
.divContainer input[type="radio"] {
  width:20px;
}

String concatenation in Jinja

My bad, in trying to simplify it, I went too far, actually stuffs is a record of all kinds of info, I just want the id in it.

stuffs = [[123, first, last], [456, first, last]]

I want my_sting to be

my_sting = '123, 456'

My original code should have looked like this:

{% set my_string = '' %}
{% for stuff in stuffs %}
{% set my_string = my_string + stuff.id + ', '%}
{% endfor%}

Thinking about it, stuffs is probably a dictionary, but you get the gist.

Yes I found the join filter, and was going to approach it like this:

 {% set my_string = [] %}
 {% for stuff in stuffs %}
 {% do my_string.append(stuff.id) %}
 {% endfor%}
 {%  my_string|join(', ') %}

But the append doesn't work without importing the extensions to do it, and reading that documentation gave me a headache. It doesn't explicitly say where to import it from or even where you would put the import statement, so I figured finding a way to concat would be the lesser of the two evils.

Connection to SQL Server Works Sometimes

Unfortunately, I had problem with Local SQL Server installed within Visual Studio and here many solutions didn't work out for me. All I have to do is to reset my Visual Studio, by going to:

Control Panel > Program & Features > Visual Studio Setup Launcher

and click on More button and choose Repair

After that I was able to access my Local SQL Server and work with local SQL Databases.

Python integer incrementing with ++

Yes. The ++ operator is not available in Python. Guido doesn't like these operators.

Git: Merge a Remote branch locally

You can reference those remote tracking branches ~(listed with git branch -r) with the name of their remote.

You need to fetch the remote branch:

git fetch origin aRemoteBranch

If you want to merge one of those remote branches on your local branch:

git checkout master
git merge origin/aRemoteBranch

Note 1: For a large repo with a long history, you will want to add the --depth=1 option when you use git fetch.

Note 2: These commands also work with other remote repos so you can setup an origin and an upstream if you are working on a fork.

Note 3: user3265569 suggests the following alias in the comments:

From aLocalBranch, run git combine remoteBranch
Alias:

combine = !git fetch origin ${1} && git merge origin/${1}

Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:

git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch

The idea here, is to merge "one of your local branch" (here anotherLocalBranch) to a remote branch (origin/aBranch).
For that, you create first "myBranch" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch part.
And then you can merge anotherLocalBranch to it (to myBranch).

Commands out of sync; you can't run this command now

I use CodeIgniter. One server OK ... this one probably older ... Anyway using

$this->db->reconnect();

Fixed it.

How can I execute PHP code from the command line?

If you're using Laravel, you can use php artisan tinker to get an amazing interactive shell to interact with your Laravel app. However, Tinker works with "Psysh" under the hood which is a popular PHP REPL and you can use it even if you're not using Laravel (bare PHP):

// Bare PHP:
>>> preg_match("/hell/", "hello");
=> 1

// Laravel Stuff:
>>> Str::slug("How to get the job done?!!?!", "_");
=> "how_to_get_the_job_done"

One great feature I really like about Psysh is that it provides a quick way for directly looking up the PHP docs from the command line. To get it to work, you only have to take the following simple steps:

apt install php-sqlite3

And then get the required PHP documentation database and move it to the proper location:

wget http://psysh.org/manual/en/php_manual.sqlite
mkdir -p /usr/local/share/psysh/ && mv php_manual.sqlite /usr/local/share/psysh/

Now for instance:

Enter image description here

Downcasting in Java

We can all see that the code you provided won't work at run time. That's because we know that the expression new A() can never be an object of type B.

But that's not how the compiler sees it. By the time the compiler is checking whether the cast is allowed, it just sees this:

variable_of_type_B = (B)expression_of_type_A;

And as others have demonstrated, that sort of cast is perfectly legal. The expression on the right could very well evaluate to an object of type B. The compiler sees that A and B have a subtype relation, so with the "expression" view of the code, the cast might work.

The compiler does not consider the special case when it knows exactly what object type expression_of_type_A will really have. It just sees the static type as A and considers the dynamic type could be A or any descendant of A, including B.

bind/unbind service example (android)

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

Client

  • It makes request to a specific server

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

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

Server

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

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

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

.

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

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

Now how to call method which lies in service

myservice.serviceMethod();

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

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

How to get a responsive button in bootstrap 3

<a href="#"><button type="button" class="btn btn-info btn-block regular-link"> <span class="text">Create New Board</span></button></a>

We can use btn-block for automatic responsive.

Pandas : compute mean or std (standard deviation) over entire dataframe

You could convert the dataframe to be a single column with stack (this changes the shape from 5x3 to 15x1) and then take the standard deviation:

df.stack().std()         # pandas default degrees of freedom is one

Alternatively, you can use values to convert from a pandas dataframe to a numpy array before taking the standard deviation:

df.values.std(ddof=1)    # numpy default degrees of freedom is zero

Unlike pandas, numpy will give the standard deviation of the entire array by default, so there is no need to reshape before taking the standard deviation.

A couple of additional notes:

  • The numpy approach here is a bit faster than the pandas one, which is generally true when you have the option to accomplish the same thing with either numpy or pandas. The speed difference will depend on the size of your data, but numpy was roughly 10x faster when I tested a few different sized dataframes on my laptop (numpy version 1.15.4 and pandas version 0.23.4).

  • The numpy and pandas approaches here will not give exactly the same answers, but will be extremely close (identical at several digits of precision). The discrepancy is due to slight differences in implementation behind the scenes that affect how the floating point values get rounded.

Delete empty rows

If you are trying to delete empty spaces , try using ='' instead of is null. Hence , if your row contains empty spaces , is null will not capture those records. Empty space is not null and null is not empty space.

Dec  Hex     Binary    Char-acter Description
0    00  00000000      NUL        null

32  20  00100000      Space       space

So I recommend:

delete  from foo_table  where bar = ''

#or 

delete  from foo_table  where bar = '' or bar is null 

#or even better , 

delete from foo_table where rtrim(ltrim(isnull(bar,'')))='';

What is a CSRF token? What is its importance and how does it work?

The site generates a unique token when it makes the form page. This token is required to post/get data back to the server.

Since the token is generated by your site and provided only when the page with the form is generated, some other site can't mimic your forms -- they won't have the token and therefore can't post to your site.

Fastest way to extract frames using ffmpeg?

Came across this question, so here's a quick comparison. Compare these two different ways to extract one frame per minute from a video 38m07s long:

time ffmpeg -i input.mp4 -filter:v fps=fps=1/60 ffmpeg_%0d.bmp

1m36.029s

This takes long because ffmpeg parses the entire video file to get the desired frames.

time for i in {0..39} ; do ffmpeg -accurate_seek -ss `echo $i*60.0 | bc` -i input.mp4   -frames:v 1 period_down_$i.bmp ; done

0m4.689s

This is about 20 times faster. We use fast seeking to go to the desired time index and extract a frame, then call ffmpeg several times for every time index. Note that -accurate_seek is the default , and make sure you add -ss before the input video -i option.

Note that it's better to use -filter:v -fps=fps=... instead of -r as the latter may be inaccurate. Although the ticket is marked as fixed, I still did experience some issues, so better play it safe.

Trigger insert old values- values that was updated

Here's an example update trigger:

create table Employees (id int identity, Name varchar(50), Password varchar(50))
create table Log (id int identity, EmployeeId int, LogDate datetime, 
    OldName varchar(50))
go
create trigger Employees_Trigger_Update on Employees
after update
as
insert into Log (EmployeeId, LogDate, OldName) 
select id, getdate(), name
from deleted
go
insert into Employees (Name, Password) values ('Zaphoid', '6')
insert into Employees (Name, Password) values ('Beeblebox', '7')
update Employees set Name = 'Ford' where id = 1
select * from Log

This will print:

id   EmployeeId   LogDate                   OldName
1    1            2010-07-05 20:11:54.127   Zaphoid

Clear text from textarea with selenium

I ran into a field where .clear() did not work. Using a combination of the first two answers worked for this field.

from selenium.webdriver.common.keys import Keys

#...your code (I was using python 3)

driver.find_element_by_id('foo').send_keys(Keys.CONTROL + "a");
driver.find_element_by_id('foo').send_keys(Keys.DELETE);

Remove duplicated rows

You can also use dplyr's distinct() function! It tends to be more efficient than alternative options, especially if you have loads of observations.

distinct_data <- dplyr::distinct(yourdata)

Detect all changes to a <input type="text"> (immediately) using JQuery

Add this code somewhere, this will do the trick.

var originalVal = $.fn.val;
$.fn.val = function(){
    var result =originalVal.apply(this,arguments);
    if(arguments.length>0)
        $(this).change(); // OR with custom event $(this).trigger('value-changed');
    return result;
};

Found this solution at val() doesn't trigger change() in jQuery

Remove columns from DataTable in C#

Aside from limiting the columns selected to reduce bandwidth and memory:

DataTable t;
t.Columns.Remove("columnName");
t.Columns.RemoveAt(columnIndex);

Numpy first occurrence of value greater than existing value

I'd like to propose

np.min(np.append(np.where(aa>5)[0],np.inf))

This will return the smallest index where the condition is met, while returning infinity if the condition is never met (and where returns an empty array).

android splash screen sizes for ldpi,mdpi, hdpi, xhdpi displays ? - eg : 1024X768 pixels for ldpi

Just use this website: http://ticons.fokkezb.nl :)

It makes it easier for you, and generates the correct sizes directly

Rails 4: List of available datatypes

It is important to know not only the types but the mapping of these types to the database types, too:

enter image description here

enter image description here


Source added - Agile Web Development with Rails 4

How to make a owl carousel with arrows instead of next previous

If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.

$('.your-class').owlCarousel({
        loop: true,
        items: 1, // Select Item Number
        autoplay:true,
        dots: false,
        nav: true,
        navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],

    });

How to list AD group membership for AD users using input list?

The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc

$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
  $output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
  $users[$i] + " " + $output 
  $z =  $users[$i] + " " + $output 
  add-content $location $z
}

Sample Output:

Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners
Guest Domain Guests Guests
krbtgt Domain Users Denied RODC Password Replication Group
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production

What are the differences between using the terminal on a mac vs linux?

@Michael Durrant's answer ably covers the shell itself, but the shell environment also includes the various commands you use in the shell and these are going to be similar -- but not identical -- between OS X and linux. In general, both will have the same core commands and features (especially those defined in the Posix standard), but a lot of extensions will be different.

For example, linux systems generally have a useradd command to create new users, but OS X doesn't. On OS X, you generally use the GUI to create users; if you need to create them from the command line, you use dscl (which linux doesn't have) to edit the user database (see here). (Update: starting in macOS High Sierra v10.13, you can use sysadminctl -addUser instead.)

Also, some commands they have in common will have different features and options. For example, linuxes generally include GNU sed, which uses the -r option to invoke extended regular expressions; on OS X, you'd use the -E option to get the same effect. Similarly, in linux you might use ls --color=auto to get colorized output; on macOS, the closest equivalent is ls -G.

EDIT: Another difference is that many linux commands allow options to be specified after their arguments (e.g. ls file1 file2 -l), while most OS X commands require options to come strictly first (ls -l file1 file2).

Finally, since the OS itself is different, some commands wind up behaving differently between the OSes. For example, on linux you'd probably use ifconfig to change your network configuration. On OS X, ifconfig will work (probably with slightly different syntax), but your changes are likely to be overwritten randomly by the system configuration daemon; instead you should edit the network preferences with networksetup, and then let the config daemon apply them to the live network state.

AngularJS : Clear $watch

scope.$watch returns a function that you can call and that will unregister the watch.

Something like:

var unbindWatch = $scope.$watch("myvariable", function() {
    //...
});

setTimeout(function() {
    unbindWatch();
}, 1000);

De-obfuscate Javascript code to make it readable again

From the first link on google;

function call_func(_0x41dcx2) {
 var _0x41dcx3 = eval('(' + _0x41dcx2 + ')');
 var _0x41dcx4 = document['createElement']('div');
 var _0x41dcx5 = _0x41dcx3['id'];
 var _0x41dcx6 = _0x41dcx3['Student_name'];
 var _0x41dcx7 = _0x41dcx3['student_dob'];
 var _0x41dcx8 = '<b>ID:</b>';
 _0x41dcx8 += '<a href="/learningyii/index.php?r=student/view&amp; id=' + _0x41dcx5 + '">' + _0x41dcx5 + '</a>';
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student Name:</b>';
 _0x41dcx8 += _0x41dcx6;
 _0x41dcx8 += '<br/>';
 _0x41dcx8 += '<b>Student DOB:</b>';
 _0x41dcx8 += _0x41dcx7;
 _0x41dcx8 += '<br/>';
 _0x41dcx4['innerHTML'] = _0x41dcx8;
 _0x41dcx4['setAttribute']('class', 'view');
 $('#StudentGridViewId')['find']('.items')['prepend'](_0x41dcx4);
};

It won't get you all the way back to source, and that's not really possible, but it'll get you out of a hole.

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

How to check if a string contains text from an array of substrings in JavaScript?

Not that I'm suggesting that you go and extend/modify String's prototype, but this is what I've done:

String.prototype.includes()

_x000D_
_x000D_
String.prototype.includes = function (includes) {_x000D_
    console.warn("String.prototype.includes() has been modified.");_x000D_
    return function (searchString, position) {_x000D_
        if (searchString instanceof Array) {_x000D_
            for (var i = 0; i < searchString.length; i++) {_x000D_
                if (includes.call(this, searchString[i], position)) {_x000D_
                    return true;_x000D_
                }_x000D_
            }_x000D_
            return false;_x000D_
        } else {_x000D_
            return includes.call(this, searchString, position);_x000D_
        }_x000D_
    }_x000D_
}(String.prototype.includes);_x000D_
_x000D_
console.log('"Hello, World!".includes("foo");',          "Hello, World!".includes("foo")           ); // false_x000D_
console.log('"Hello, World!".includes(",");',            "Hello, World!".includes(",")             ); // true_x000D_
console.log('"Hello, World!".includes(["foo", ","])',    "Hello, World!".includes(["foo", ","])    ); // true_x000D_
console.log('"Hello, World!".includes(["foo", ","], 6)', "Hello, World!".includes(["foo", ","], 6) ); // false
_x000D_
_x000D_
_x000D_

Amazon S3 exception: "The specified key does not exist"

In my case the error was appearing because I had uploaded the whole folder, containing the website files, into the container.

I solved it by moving all the files outside the folder, right into the container.

To get specific part of a string in c#

If you want to get the strings separated by the , you can use

string b = a.Split(',')[0];

How do I escape a string inside JavaScript code inside an onClick handler?

Depending on the server-side language, you could use one of these:

.NET 4.0

string result = System.Web.HttpUtility.JavaScriptStringEncode("jsString")

Java

import org.apache.commons.lang.StringEscapeUtils;
...

String result = StringEscapeUtils.escapeJavaScript(jsString);

Python

import json
result = json.dumps(jsString)

PHP

$result = strtr($jsString, array('\\' => '\\\\', "'" => "\\'", '"' => '\\"', 
                                 "\r" => '\\r', "\n" => '\\n' ));

Ruby on Rails

<%= escape_javascript(jsString) %>

Push items into mongo array via mongoose

First I tried this code

const peopleSchema = new mongoose.Schema({
  name: String,
  friends: [
    {
      firstName: String,
      lastName: String,
    },
  ],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
  name: "Yash Salvi",
  notes: [
    {
      firstName: "Johnny",
      lastName: "Johnson",
    },
  ],
});
first.save();
const friendNew = {
  firstName: "Alice",
  lastName: "Parker",
};
People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
  function (error, success) {
    if (error) {
      console.log(error);
    } else {
      console.log(success);
    }
  }
);

But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element ! So the simple solution is written below

const peopleSchema = new mongoose.Schema({
  name: String,
  friends: [
    {
      firstName: String,
      lastName: String,
    },
  ],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
  name: "Yash Salvi",
  notes: [
    {
      firstName: "Johnny",
      lastName: "Johnson",
    },
  ],
});
first.save();
const friendNew = {
  firstName: "Alice",
  lastName: "Parker",
};
People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
  { upsert: true }
);

Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements ! The upsert = true option creates the object if it doesn't exist. default is set to false.

if it doesn't work use below snippet

People.findOneAndUpdate(
  { name: "Yash Salvi" },
  { $push: { friends: friendNew } },
).exec();

Can't start hostednetwork

Let alone enabling the network adapter under Device Manager may not help. The following helped me resolved the issue.

I tried Disabling and Enabling the Wifi Adapter (i.e. the actual Wifi device adapter not the virtual adapters) in Control Panel -> Network and Internet -> Network Connections altogether worked for me. The same can be done from the Device Manager too. This surely resets the adapter settings and for the Wifi Adapter and the Virtual Miniport adapters.

However, please make sure that the mode is set to allow as in the below example before you run the start command.

netsh wlan set hostednetwork mode=allow ssid=ssidOfUrChoice key=keyOfUrChoice

and after that run the command netsh wlan start hostednetwork.

Also once the usage is over with the Miniport adapter connection, it is a good practice to stop it using the following command.

netsh wlan stop hostednetwork

Hope it helps.

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

If your project does not use stdafx.h, you can put the following lines as the first lines in your .cpp file and the compiler warning should go away -- at least it did for me in Visual Studio C++ 2008.

#ifdef _CRT_SECURE_NO_WARNINGS
#undef _CRT_SECURE_NO_WARNINGS
#endif
#define _CRT_SECURE_NO_WARNINGS 1

It's ok to have comment and blank lines before them.

How to initialize an array in Java?

When you create an array of size 10 it allocated 10 slots but from 0 to 9. This for loop might help you see that a little better.

public class Array {
    int[] data = new int[10]; 
    /** Creates a new instance of an int Array */
    public Array() {
        for(int i = 0; i < data.length; i++) {
            data[i] = i*10;
        }
    }
}

How to display images from a folder using php - PHP

You had a mistake on the statement below. Use . not ,

echo '<img src="', $dir, '/', $file, '" alt="', $file, $

to

echo '<img src="'. $dir. '/'. $file. '" alt="'. $file. $

and

echo 'Directory \'', $dir, '\' not found!';

to

echo 'Directory \''. $dir. '\' not found!';

Getting a count of objects in a queryset in django

To get the number of votes for a specific item, you would use:

vote_count = Item.objects.filter(votes__contest=contestA).count()

If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:

contest = Contest.objects.get(pk=contest_id)
votes   = contest.votes_set.select_related()

vote_counts = {}

for vote in votes:
  if not vote_counts.has_key(vote.item.id):
    vote_counts[vote.item.id] = {
      'item': vote.item,
      'count': 0
    }

  vote_counts[vote.item.id]['count'] += 1

This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.

Which is faster: multiple single INSERTs or one multiple-row INSERT?

multiple inserts are faster but it has thredshould. another thrik is disabling constrains checks temprorary make inserts much much faster. It dosn't matter your table has it or not. For example test disabling foreign keys and enjoy the speed:

SET FOREIGN_KEY_CHECKS=0;

offcourse you should turn it back on after inserts by:

SET FOREIGN_KEY_CHECKS=1;

this is common way to inserting huge data. the data integridity may break so you shoud care of that before disabling foreign key checks.

How to start new line with space for next line in Html.fromHtml for text view in android

use <br/> tag

Example:

<string name="copyright"><b>@</b> 2014 <br/>
Corporation.<br/>
<i>All rights reserved.</i></string>

How to convert list of key-value tuples into dictionary?

Have you tried this?

>>> l=[('A',1), ('B',2), ('C',3)]
>>> d=dict(l)
>>> d
{'A': 1, 'C': 3, 'B': 2}

Get the current user, within an ApiController action, without passing the userID as a parameter

Karan Bhandari's answer is good, but the AccountController added in a project is very likely a Mvc.Controller. To convert his answer for use in an ApiController change HttpContext.Current.GetOwinContext() to Request.GetOwinContext() and make sure you have added the following 2 using statements:

using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

How to get the background color code of an element in hex?

In fact, if there is no definition of background-color under some element, Chrome will output its background-color as rgba(0, 0, 0, 0), while Firefox outputs is transparent.

add new element in laravel collection object

It looks like you have everything correct according to Laravel docs, but you have a typo

$item->push($product);

Should be

$items->push($product);

I also want to think the actual method you're looking for is put

$items->put('products', $product);

What is Shelving in TFS?

Shelving is a way of saving all of the changes on your box without checking in. The changes are persisted on the server. At any later time you or any of your team-mates can "unshelve" them back onto any one of your machines.

It's also great for review purposes. On my team for a check in we shelve up our changes and send out an email with the change description and name of the changeset. People on the team can then view the changeset and give feedback.

FYI: The best way to review a shelveset is with the following command

tfpt review /shelveset:shelvesetName;userName

tfpt is a part of the Team Foundation Power Tools

Parse String to Date with Different Format in Java

Convert a string date to java.sql.Date

String fromDate = "19/05/2009";
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
java.util.Date dtt = df.parse(fromDate);
java.sql.Date ds = new java.sql.Date(dtt.getTime());
System.out.println(ds);//Mon Jul 05 00:00:00 IST 2010

ESLint Parsing error: Unexpected token

Originally, the solution was to provide the following config as object destructuring used to be an experimental feature and not supported by default:

{
  "parserOptions": {
    "ecmaFeatures": {
      "experimentalObjectRestSpread": true
    }
  }
}

Since version 5, this option has been deprecated.

Now it is enough just to declare a version of ES, which is new enough:

{
  "parserOptions": {
    "ecmaVersion": 2018
  }
}

Converting a POSTMAN request to Curl

enter image description here

You can see the button "Code" in the attached screenshot, press it and you can get your code in many different languages including PHP cURL

enter image description here

Using multiple parameters in URL in express

For what you want I would've used

    app.get('/fruit/:fruitName&:fruitColor', function(request, response) {
       const name = request.params.fruitName 
       const color = request.params.fruitColor 
    });

or better yet

    app.get('/fruit/:fruit', function(request, response) {
       const fruit = request.params.fruit
       console.log(fruit)
    });

where fruit is a object. So in the client app you just call

https://mydomain.dm/fruit/{"name":"My fruit name", "color":"The color of the fruit"}

and as a response you should see:

    //  client side response
    // { name: My fruit name, color:The color of the fruit}

Hiding a button in Javascript

//Your code to make the box goes here... call it box
box.id="foo";
//Your code to remove the box goes here
document.getElementById("foo").style.display="none";

of course if you are doing a lot of stuff like this, use jQuery

JWT refresh token flow

Based in this implementation with Node.js of JWT with refresh token:

1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

Using LINQ to concatenate strings

Here it is using pure LINQ as a single expression:

static string StringJoin(string sep, IEnumerable<string> strings) {
  return strings
    .Skip(1)
    .Aggregate(
       new StringBuilder().Append(strings.FirstOrDefault() ?? ""), 
       (sb, x) => sb.Append(sep).Append(x));
}

And its pretty damn fast!

How to run python script on terminal (ubuntu)?

First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be

!/usr/bin/env python

Regular expression "^[a-zA-Z]" or "[^a-zA-Z]"

^ outside of the character class ("[a-zA-Z]") notes that it is the "begins with" operator.
^ inside of the character negates the specified class.

So, "^[a-zA-Z]" translates to "begins with character from a-z or A-Z", and "[^a-zA-Z]" translates to "is not either a-z or A-Z"

Here's a quick reference: http://www.regular-expressions.info/reference.html

Typescript es6 import module "File is not a module error"

How can I accomplish that?

Your example declares a TypeScript < 1.5 internal module, which is now called a namespace. The old module App {} syntax is now equivalent to namespace App {}. As a result, the following works:

// test.ts
export namespace App {
    export class SomeClass {
        getName(): string {
            return 'name';
        }
    }
}

// main.ts
import { App } from './test';
var a = new App.SomeClass();

That being said...

Try to avoid exporting namespaces and instead export modules (which were previously called external modules). If needs be you can use a namespace on import with the namespace import pattern like this:

// test.ts
export class SomeClass {
    getName(): string {
        return 'name';
    }
}

// main.ts
import * as App from './test'; // namespace import pattern
var a = new App.SomeClass();

Fixing broken UTF-8 encoding

Another thing to check, which happened to be my solution (found here), is how data is being returned from your server. In my application, I'm using PDO to connect from PHP to MySQL. I needed to add a flag to the connection which said get the data back in UTF-8 format

The answer was

$dbHandle = new PDO("mysql:host=$dbHost;dbname=$dbName;charset=utf8", $dbUser, $dbPass, 
    array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'utf8'"));

Converting an integer to a hexadecimal string in Ruby

Just in case you have a preference for how negative numbers are formatted:

p "%x" % -1   #=> "..f"
p -1.to_s(16) #=> "-1"

Get PostGIS version

Did you try using SELECT PostGIS_version();

Sublime Text 2 Code Formatting

Sublime CodeFormatter has formatting support for PHP, JavaScript/JSON/JSONP, HTML, CSS, Python. Although I haven't used CodeFormatter for very long, I have been impressed with it's JS, HTML, and CSS "beautifying" capabilities. I haven't tried using it with PHP (I don't do any PHP development) or Python (which I have no experience with) but both languages have many options in the .sublime-settings file.

One note however, the settings aren't very easy to find. On Windows you will need to go to your %AppData%\Roaming\Sublime Text #\Packages\CodeFormatter\CodeFormatter.sublime-settings. As I don't have a Mac I'm not sure where the settings file is on OS X.

As for a shortcut key, I added this key binding to my "Key Bindings - User" file:

{
    "keys": ["ctrl+k", "ctrl+d"],
    "command": "code_formatter"
}

I use Ctrl + K, Ctrl + D because that's what Visual Studio uses for formatting. You can change it, of course, just remember that what you choose might conflict with some other feature's keyboard shortcut.

Update:

It seems as if the developers of Sublime Text CodeFormatter have made it easier to access the .sublime-settings file. If you install CodeFormatter with the Package Control plugin, you can access the settings via the Preferences -> Package Settings -> CodeFormatter -> Settings - Default and override those settings using the Preferences -> Package Settings -> CodeFormatter -> Settings - User menu item.

Could not load file or assembly 'Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies

It is possible to solve the problem by updating the 'Newtonsoft' version.

In Visual Studio 2015 it is possible to right click on the "Solution" and select "Manage Nuget packages for solution", search for "Newtonsoft" select a more current version and click update.

Background color of text in SVG

You can add style to your text:

  style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); 
    text-shadow: rgb(255, 255, 255) -2px -2px 0px, rgb(255, 255, 255) -2px 2px 0px, 
     rgb(255, 255, 255) 2px -2px 0px, rgb(255, 255, 255) 2px 2px 0px;"

White, in this example. Does not work in IE :)