Programs & Examples On #Url style

UTF-8 output from PowerShell

Not an expert on encoding, but after reading these...

... it seems fairly clear that the $OutputEncoding variable only affects data piped to native applications.

If sending to a file from withing PowerShell, the encoding can be controlled by the -encoding parameter on the out-file cmdlet e.g.

write-output "hello" | out-file "enctest.txt" -encoding utf8

Nothing else you can do on the PowerShell front then, but the following post may well help you:.

Validate that text field is numeric usiung jQuery

I know there isn't any need to add a plugin for this.

But this can be useful if you are doing so many things with numbers. So checkout this plugin at least for a knowledge point of view.

The rest of karim79's answer is super cool.

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
        <script type="text/javascript" src="jquery.numeric.js"></script>
    </head>

    <body>
        <form>
            Numbers only:
            <input class="numeric" type="text" />
            Integers only:
            <input class="integer" type="text" />
            No negative values:
            <input class="positive" type="text" />
            No negative values (integer only):
            <input class="positive-integer" type="text" />
            <a href="#" id="remove">Remove numeric</a>
        </form>

        <script type="text/javascript">
            $(".numeric").numeric();

            $(".integer").numeric(false, function() {
                alert("Integers only");
                this.value = "";
                this.focus();
            });

            $(".positive").numeric({ negative: false },
                function() {
                    alert("No negative values");
                    this.value = "";
                    this.focus();
                });

            $(".positive-integer").numeric({ decimal: false, negative: false },
                function() {
                    alert("Positive integers only");
                    this.value = "";
                    this.focus();
                });

            $("#remove").click(
                function(e)
                {
                    e.preventDefault();
                    $(".numeric,.integer,.positive").removeNumeric();
                }
            );
        </script>

    </body>
</html>

Convert a space delimited string to list

Use string's split() method.

states.split()

How to make `setInterval` behave more in sync, or how to use `setTimeout` instead?

Given that neither time is going to be very accurate, one way to use setTimeout to be a little more accurate is to calculate how long the delay was since the last iteration, and then adjust the next iteration as appropriate. For example:

var myDelay = 1000;
var thisDelay = 1000;
var start = Date.now();

function startTimer() {    
    setTimeout(function() {
        // your code here...
        // calculate the actual number of ms since last time
        var actual = Date.now() - start;
        // subtract any extra ms from the delay for the next cycle
        thisDelay = myDelay - (actual - myDelay);
        start = Date.now();
        // start the timer again
        startTimer();
    }, thisDelay);
}

So the first time it'll wait (at least) 1000 ms, when your code gets executed, it might be a little late, say 1046 ms, so we subtract 46 ms from our delay for the next cycle and the next delay will be only 954 ms. This won't stop the timer from firing late (that's to be expected), but helps you to stop the delays from pilling up. (Note: you might want to check for thisDelay < 0 which means the delay was more than double your target delay and you missed a cycle - up to you how you want to handle that case).

Of course, this probably won't help you keep several timers in sync, in which case you might want to figure out how to control them all with the same timer.

So looking at your code, all your delays are a multiple of 500, so you could do something like this:

var myDelay = 500;
var thisDelay = 500;
var start = Date.now();
var beatCount = 0;

function startTimer() {    
    setTimeout(function() {
        beatCount++;
        // your code here...
        //code for the bass playing goes here  

        if (count%2 === 0) {
            //code for the chords playing goes here (every 1000 ms)
        }

        if (count%16) {
            //code for the drums playing goes here (every 8000 ms)
        }

        // calculate the actual number of ms since last time
        var actual = Date.now() - start;
        // subtract any extra ms from the delay for the next cycle
        thisDelay = myDelay - (actual - myDelay);
        start = Date.now();
        // start the timer again
        startTimer();
    }, thisDelay);
}

De-obfuscate Javascript code to make it readable again

Try this: http://jsbeautifier.org/

I tested with your code and worked as good as possible. =D

How to get Exception Error Code in C#

You should look at the members of the thrown exception, particularly .Message and .InnerException.

I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet. Catching and just looking at the Exception base class may not be particularly useful.

Eclipse error: R cannot be resolved to a variable

In addition to install the build tools and restart the update manager I also had to restart Eclipse to make this work.

How to position a CSS triangle using ::after?

Add a class:

.com_box:after {
     content: '';
    position: absolute;
    left: 18px;
    top: 50px;
    width: 0;
    height: 0;
    border-left: 20px solid transparent;
    border-right: 20px solid transparent;
    border-top: 20px solid #000;
    clear: both;

}

Updated your jsfiddle: http://jsfiddle.net/wrm4y8k6/8/

How can I run Tensorboard on a remote server?

For anyone who must use the ssh keys (for a corporate server).

Just add -i /.ssh/id_rsa at the end.

$ ssh -N -f -L localhost:8211:localhost:6007 myname@servername -i /.ssh/id_rsa

How do you open an SDF file (SQL Server Compact Edition)?

Try the sql server management studio (version 2008 or earlier) from Microsoft. Download it from here. Not sure about the license, but it seems to be free if you download the EXPRESS EDITION.

You might also be able to use later editions of SSMS. For 2016, you will need to install an extension.

If you have the option you can copy the sdf file to a different machine which you are allowed to pollute with additional software.

Update: comment from Nick Westgate in nice formatting

The steps are not all that intuitive:

  1. Open SQL Server Management Studio, or if it's running select File -> Connect Object Explorer...
  2. In the Connect to Server dialog change Server type to SQL Server Compact Edition
  3. From the Database file dropdown select < Browse for more...>
  4. Open your SDF file.

The mysqli extension is missing. Please check your PHP configuration

sudo apt-get install php7.2-mysql

extension=mysqli.so (add this php.ini file)

sudo service apahce2 restart

Please use above commands to resolve mysqli-extension missing error

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel using Eloquent or the query builder.

You can use the following approach.

$data = [
    ['user_id'=>'Coder 1', 'subject_id'=> 4096],
    ['user_id'=>'Coder 2', 'subject_id'=> 2048],
    //...
];

Model::insert($data); // Eloquent approach
DB::table('table')->insert($data); // Query Builder approach

In your case you already have the data within the $query variable.

More elegant way of declaring multiple variables at the same time

Like JavaScript you can also use multiple statements on one line in python a = 1; b = "Hello World"; c += 3

Making macOS Installer Packages which are Developer ID ready

Here is a build script which creates a signed installer package out of a build root.

#!/bin/bash
# TRIMCheck build script
# Copyright Doug Richardson 2015
# Usage: build.sh
#
# The result is a disk image that contains the TRIMCheck installer.
#

DSTROOT=/tmp/trimcheck.dst
SRCROOT=/tmp/trimcheck.src

INSTALLER_PATH=/tmp/trimcheck
INSTALLER_PKG="TRIMCheck.pkg"
INSTALLER="$INSTALLER_PATH/$INSTALLER_PKG"

#
# Clean out anything that doesn't belong.
#
echo Going to clean out build directories
rm -rf build $DSTROOT $SRCROOT $INSTALLER_PATH
echo Build directories cleaned out


#
# Build
#
echo ------------------
echo Installing Sources
echo ------------------
xcodebuild -project TRIMCheck.xcodeproj installsrc SRCROOT=$SRCROOT || exit 1

echo ----------------
echo Building Project
echo ----------------
pushd $SRCROOT
xcodebuild -project TRIMCheck.xcodeproj -target trimcheck -configuration Release install || exit 1
popd

echo ------------------
echo Building Installer
echo ------------------
mkdir -p "$INSTALLER_PATH" || exit 1

echo "Runing pkgbuild. Note you must be connected to Internet for this to work as it"
echo "has to contact a time server in order to generate a trusted timestamp. See"
echo "man pkgbuild for more info under SIGNED PACKAGES."
pkgbuild --identifier "com.delicioussafari.TRIMCheck" \
    --sign "Developer ID Installer: Douglas Richardson (4L84QT8KA9)" \
    --root "$DSTROOT" \
    "$INSTALLER" || exit 1


echo Successfully built TRIMCheck
open "$INSTALLER_PATH"

exit 0

HttpClient - A task was cancelled?

I ran into this issue because my Main() method wasn't waiting for the task to complete before returning, so the Task<HttpResponseMessage> myTask was being cancelled when my console program exited.

The solution was to call myTask.GetAwaiter().GetResult() in Main() (from this answer).

VirtualBox Cannot register the hard disk already exists

I really appreciate the suggestions here. The Impaler's and Oleg's comments helped me to piece my solution together.

Use the VBoxManage CLI. There's a modifymedium command with a --setlocation option.

I suggest opening the VBox GUI (on VM VirtualBox Manager 6.0)
- select "Virtual Media Manager" (I used the File menu)
- select the "Information" button for the disk giving you this error
- copy the UUID
Note: I removed the controller from the "Storage" setting before the next step.
- open your command prompt and navigate to the location of the .vdi file
It's a good idea to type VBoxMange to see a list of options, but this is the command to run:

VBoxManage modifymedium [insert medium type here] [UUID] --setlocation [full path to .vdi file]

Finally, reattach the controller to any VM--preferably the one you'd like to fix.

Gridview get Checkbox.Checked value

    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox chkbox = (CheckBox)row.FindControl("CheckBox1");
        if (chkbox.Checked == true)
        {
            // Your Code
        }
    }

Using Python's os.path, how do I go up one directory?

Go up a level from the work directory

import os
os.path.dirname(os.getcwd())

or from the current directory

import os
os.path.dirname('current path')

Replace part of a string with another string

If you want to do it quickly you can use a two scan approach. Pseudo code:

  1. first parse. find how many matching chars.
  2. expand the length of the string.
  3. second parse. Start from the end of the string when we get a match we replace, else we just copy the chars from the first string.

I am not sure if this can be optimized to an in-place algo.

And a C++11 code example but I only search for one char.

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

void ReplaceString(string& subject, char search, const string& replace)
{   
    size_t initSize = subject.size();
    int count = 0;
    for (auto c : subject) { 
        if (c == search) ++count;
    }

    size_t idx = subject.size()-1 + count * replace.size()-1;
    subject.resize(idx + 1, '\0');

    string reverseReplace{ replace };
    reverse(reverseReplace.begin(), reverseReplace.end());  

    char *end_ptr = &subject[initSize - 1];
    while (end_ptr >= &subject[0])
    {
        if (*end_ptr == search) {
            for (auto c : reverseReplace) {
                subject[idx - 1] = c;
                --idx;              
            }           
        }
        else {
            subject[idx - 1] = *end_ptr;
            --idx;
        }
        --end_ptr;
    }
}

int main()
{
    string s{ "Mr John Smith" };
    ReplaceString(s, ' ', "%20");
    cout << s << "\n";

}

Manually adding a Userscript to Google Chrome

Update 2016: seems to be working again.

Update August 2014: No longer works as of recent Chrome versions.


Yeah, the new state of affairs sucks. Fortunately it's not so hard as the other answers imply.

  1. Browse in Chrome to chrome://extensions
  2. Drag the .user.js file into that page.

Voila. You can also drag files from the downloads footer bar to the extensions tab.

Chrome will automatically create a manifest.json file in the extensions directory that Brock documented.

<3 Freedom.

ISO C90 forbids mixed declarations and code in C

To diagnose what really triggers the error, I would first try to remove = 0

  • If the error is tripped, then most likely the declaration goes after the code.

  • If no error, then it may be related to a C-standard enforcement/compile flags OR ...something else.

In any case, declare the variable in the beginning of the current scope. You may then initialize it separately. Indeed, if this variable deserves its own scope - delimit its definition in {}.

If the OP could clarify the context, then a more directed response would follow.

How to call a C# function from JavaScript?

If you're meaning to make a server call from the client, you should use Ajax - look at something like Jquery and use $.Ajax() or $.getJson() to call the server function, depending on what kind of return you're after or action you want to execute.

Unbound classpath container in Eclipse

To fix this:

  • Right click your project –> Build Path –>Configure Build Path
  • Select JRE Library and click Edit and from Edit library window choose alternate JRE whatever been configured with your eclipse then click Finish

How to flip background image using CSS?

According to w3schools: http://www.w3schools.com/cssref/css3_pr_transform.asp

The transform property is supported in Internet Explorer 10, Firefox, and Opera. Internet Explorer 9 supports an alternative, the -ms-transform property (2D transforms only). Safari and Chrome support an alternative, the -webkit-transform property (3D and 2D transforms). Opera supports 2D transforms only.

This is a 2D transform, so it should work, with the vendor prefixes, on Chrome, Firefox, Opera, Safari, and IE9+.

Other answers used :before to stop it from flipping the inner content. I used this on my footer (to vertically-mirror the image from my header):

HTML:

<footer>
<p><a href="page">Footer Link</a></p>
<p>&copy; 2014 Company</p>
</footer>

CSS:

footer {
background:url(/img/headerbg.png) repeat-x 0 0;

/* flip background vertically */
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

/* undo the vertical flip for all child elements */
footer * {
-webkit-transform:scaleY(-1);
-moz-transform:scaleY(-1);
-ms-transform:scaleY(-1);
-o-transform:scaleY(-1);
transform:scaleY(-1);
}

So you end up flipping the element and then re-flipping all its children. Works with nested elements, too.

ios simulator: how to close an app

You can use this command to quit an app in iOS Simulator

xcrun simctl terminate booted com.apple.mobilesafari

You will need to know the bundle id of the app you have installed in the simulator. You can refer to this link

Converting map to struct

The simplest way would be to use https://github.com/mitchellh/mapstructure

import "github.com/mitchellh/mapstructure"

mapstructure.Decode(myData, &result)

If you want to do it yourself, you could do something like this:

http://play.golang.org/p/tN8mxT_V9h

func SetField(obj interface{}, name string, value interface{}) error {
    structValue := reflect.ValueOf(obj).Elem()
    structFieldValue := structValue.FieldByName(name)

    if !structFieldValue.IsValid() {
        return fmt.Errorf("No such field: %s in obj", name)
    }

    if !structFieldValue.CanSet() {
        return fmt.Errorf("Cannot set %s field value", name)
    }

    structFieldType := structFieldValue.Type()
    val := reflect.ValueOf(value)
    if structFieldType != val.Type() {
        return errors.New("Provided value type didn't match obj field type")
    }

    structFieldValue.Set(val)
    return nil
}

type MyStruct struct {
    Name string
    Age  int64
}

func (s *MyStruct) FillStruct(m map[string]interface{}) error {
    for k, v := range m {
        err := SetField(s, k, v)
        if err != nil {
            return err
        }
    }
    return nil
}

func main() {
    myData := make(map[string]interface{})
    myData["Name"] = "Tony"
    myData["Age"] = int64(23)

    result := &MyStruct{}
    err := result.FillStruct(myData)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Println(result)
}

Pandas df.to_csv("file.csv" encode="utf-8") still gives trash characters for minus sign

Your "bad" output is UTF-8 displayed as CP1252.

On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:

df.to_csv('file.csv',encoding='utf-8-sig')

That encoder will add the BOM.

Execute a PHP script from another PHP script

The OP refined his question to how a php script is called from a script. The php statement 'require' is good for dependancy as the script will stop if required script is not found.

#!/usr/bin/php
<?
require '/relative/path/to/someotherscript.php';

/* The above script runs as though executed from within this one. */

printf ("Hello world!\n");

?>

Get an object attribute

You can do the following:

class User(object):
    fullName = "John Doe"

    def __init__(self, name):
        self.SName = name

    def print_names(self):
        print "Names: full name: '%s', name: '%s'" % (self.fullName, self.SName)

user = User('Test Name')

user.fullName # "John Doe"
user.SName # 'Test Name'
user.print_names() # will print you Names: full name: 'John Doe', name: 'Test Name'

E.g any object attributes could be retrieved using istance.

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

Just as an FYI, here is my working code:

src_dir = "C:\\temp\\CSV\\"
target_dir = "C:\\temp\\output2\\"
keyword = "KEYWORD"

for f in os.listdir(src_dir):
    file_name = os.path.join(src_dir, f)
    out_file = os.path.join(target_dir, f)
    with open(file_name, "r+") as fi, open(out_file, "w") as fo:
        for line in fi:
            if keyword not in line:
                fo.write(line)

Thanks again to everyone for all the great feedback!

C++ static virtual members?

While Alsk has already given a pretty detailed answer, I'd like to add an alternative, since I think his enhanced implementation is overcomplicated.

We start with an abstract base class, that provides the interface for all the object types:

class Object
{
public:
    virtual char* GetClassName() = 0;
};

Now we need an actual implementation. But to avoid having to write both the static and the virtual methods, we will have our actual object classes inherit the virtual methods. This does obviously only work, if the base class knows how to access the static member function. So we need to use a template and pass the actual objects class name to it:

template<class ObjectType>
class ObjectImpl : public Object
{
public:
    virtual char* GetClassName()
    {
        return ObjectType::GetClassNameStatic();
    }
};

Finally we need to implement our real object(s). Here we only need to implement the static member function, the virtual member functions will be inherited from the ObjectImpl template class, instantiated with the name of the derived class, so it will access it's static members.

class MyObject : public ObjectImpl<MyObject>
{
public:
    static char* GetClassNameStatic()
    {
        return "MyObject";
    }
};

class YourObject : public ObjectImpl<YourObject>
{
public:
    static char* GetClassNameStatic()
    {
        return "YourObject";
    }
};

Let's add some code to test:

char* GetObjectClassName(Object* object)
{
    return object->GetClassName();
}

int main()
{
    MyObject myObject;
    YourObject yourObject;

    printf("%s\n", MyObject::GetClassNameStatic());
    printf("%s\n", myObject.GetClassName());
    printf("%s\n", GetObjectClassName(&myObject));
    printf("%s\n", YourObject::GetClassNameStatic());
    printf("%s\n", yourObject.GetClassName());
    printf("%s\n", GetObjectClassName(&yourObject));

    return 0;
}

Addendum (Jan 12th 2019):

Instead of using the GetClassNameStatic() function, you can also define the the class name as a static member, even "inline", which IIRC works since C++11 (don't get scared by all the modifiers :)):

class MyObject : public ObjectImpl<MyObject>
{
public:
    // Access this from the template class as `ObjectType::s_ClassName` 
    static inline const char* const s_ClassName = "MyObject";

    // ...
};

dynamically set iframe src

try this code. then 'formId' div can set the image.

$('#formId').append('<iframe style="width: 100%;height: 500px" src="/document_path/name.jpg"' +
 'title="description"> </iframe> ');

Android Activity as a dialog

If you want to remove activity header & provide a custom view for the dialog add the following to the activity block of you manifest

android:theme="@style/Base.Theme.AppCompat.Dialog"

and design your activity_layout with your desired view

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

How do I add target="_blank" to a link within a specified div?

Using jQuery:

 $('#link_other a').each(function(){
  $(this).attr('target', '_BLANK');
 });

Convert cells(1,1) into "A1" and vice versa

The Address property of a cell can get this for you:

MsgBox Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)

returns A1.

The other way around can be done with the Row and Column property of Range:

MsgBox Range("A1").Row & ", " & Range("A1").Column

returns 1,1.

ERROR in The Angular Compiler requires TypeScript >=3.1.1 and <3.2.0 but 3.2.1 was found instead

For following Error:

ERROR in The Angular Compiler requires TypeScript >=3.4.0 and <3.6.0 but 3.6.3 was found instead.

Run following NPM command:

$ npm install [email protected]

Source Link

Eclipse error "ADB server didn't ACK, failed to start daemon"

These symptoms occur if you are using the Genymotion emulator (on Windows or Linux) at the same time as Android Studio:

adb server is out of date.  killing...
ADB server didn't ACK
* failed to start daemon *

Genymotion includes its own copy of adb, which interferes with the one bundled in the Android SDK.

The easiest way to fix seems to be to update your Genymotion Settings so it uses the same ADB as your Android SDK:

genymotion ADB settings

Just check the "Use custom Android SDK tools" option and enter your desired location.

How can I convert uppercase letters to lowercase in Notepad++

First select the text
To convert lowercase to uppercase, press Ctrl+Shift+U
To convert uppercase to lowercase, press Ctrl+U

Cannot set some HTTP headers when using System.Net.WebRequest

Note: this solution will work with WebClientSocket as well as with HttpWebRequest or any other class that uses WebHeaderCollection to work with headers.

If you look at the source code of WebHeaderCollection.cs you will see that Hinfo is used to keep information of all known headers:

private static readonly HeaderInfoTable HInfo = new HeaderInfoTable();

Looking at HeaderInfoTable class, you can notice all the data is stored into hash table

private static Hashtable HeaderHashTable;

Further, in static contructor of HeaderInfoTable, you can see all known headers are added in HeaderInfo array and then copied into hashtable.

Final look at HeaderInfo class shows the names of the fields.

internal class HeaderInfo {

    internal readonly bool IsRequestRestricted;
    internal readonly bool IsResponseRestricted;
    internal readonly HeaderParser Parser;

    //
    // Note that the HeaderName field is not always valid, and should not
    // be used after initialization. In particular, the HeaderInfo returned
    // for an unknown header will not have the correct header name.
    //

    internal readonly string HeaderName;
    internal readonly bool AllowMultiValues;
    ...
    }

So, with all the above, here is a code that uses reflection to find static Hashtable in HeaderInfoTable class and then changes every request-restricted HeaderInfo inside hash table to be unrestricted

        // use reflection to remove IsRequestRestricted from headerInfo hash table
        Assembly a = typeof(HttpWebRequest).Assembly;
        foreach (FieldInfo f in a.GetType("System.Net.HeaderInfoTable").GetFields(BindingFlags.NonPublic | BindingFlags.Static))
        {
            if (f.Name == "HeaderHashTable")
            {
                Hashtable hashTable = f.GetValue(null) as Hashtable;
                foreach (string sKey in hashTable.Keys)
                {

                    object headerInfo = hashTable[sKey];
                    //Console.WriteLine(String.Format("{0}: {1}", sKey, hashTable[sKey]));
                    foreach (FieldInfo g in a.GetType("System.Net.HeaderInfo").GetFields(BindingFlags.NonPublic | BindingFlags.Instance))
                    {

                        if (g.Name == "IsRequestRestricted")
                        {
                            bool b = (bool)g.GetValue(headerInfo);
                            if (b)
                            {
                                g.SetValue(headerInfo, false);
                                Console.WriteLine(sKey + "." + g.Name + " changed to false");
                            }

                        }
                    }

                }
            }
        } 

How to get jSON response into variable from a jquery script

Look out for this pitfal: http://www.vertstudios.com/blog/avoiding-ajax-newline-pitfall/

Searched several houres before I found there were some linebreaks in the included files.

Numpy matrix to array

This will convert the matrix into array

A = np.ravel(M).T

How to sort a data frame by date

If you just want to rearrange dates from oldest to newest in r etc. you can always do:

dataframe <- dataframe[nrow(dataframe):1,]

It's saved me exporting in and out from excel just for sort on Yahoo Finance data.

How do I lowercase a string in C?

If we're going to be as sloppy as to use tolower(), do this:

char blah[] = "blah blah Blah BLAH blAH\0"; int i=0; while(blah[i]|=' ', blah[++i]) {}

But, well, it kinda explodes if you feed it some symbols/numerals, and in general it's evil. Good interview question, though.

How to check if Receiver is registered in Android?

You can use Dagger to create a reference of that receiver.

First provide it:

@Provides
@YourScope
fun providesReceiver(): NotificationReceiver{
    return NotificationReceiver()
}

Then inject it where you need (using constructor or field injection)

and simply pass it to registerReceiver.

Also put it in try/catch block too.

How to Programmatically Add Views to Views

Calling addView is the correct answer, but you need to do a little more than that to get it to work.

If you create a View via a constructor (e.g., Button myButton = new Button();), you'll need to call setLayoutParams on the newly constructed view, passing in an instance of the parent view's LayoutParams inner class, before you add your newly constructed child to the parent view.

For example, you might have the following code in your onCreate() function assuming your LinearLayout has id R.id.main:

LinearLayout myLayout = findViewById(R.id.main);

Button myButton = new Button(this);
myButton.setLayoutParams(new LinearLayout.LayoutParams(
                                     LinearLayout.LayoutParams.MATCH_PARENT,
                                     LinearLayout.LayoutParams.MATCH_PARENT));

myLayout.addView(myButton);

Making sure to set the LayoutParams is important. Every view needs at least a layout_width and a layout_height parameter. Also getting the right inner class is important. I struggled with getting Views added to a TableRow to display properly until I figured out that I wasn't passing an instance of TableRow.LayoutParams to the child view's setLayoutParams.

How to execute raw queries with Laravel 5.1?

I found the solution in this topic and I code this:

$cards = DB::select("SELECT
        cards.id_card,
        cards.hash_card,
        cards.`table`,
        users.name,
        0 as total,
        cards.card_status,
        cards.created_at as last_update
    FROM cards
    LEFT JOIN users
    ON users.id_user = cards.id_user
    WHERE hash_card NOT IN ( SELECT orders.hash_card FROM orders )
    UNION
    SELECT
        cards.id_card,
        orders.hash_card,
        cards.`table`,
        users.name,
        sum(orders.quantity*orders.product_price) as total, 
        cards.card_status, 
        max(orders.created_at) last_update 
    FROM menu.orders
    LEFT JOIN cards
    ON cards.hash_card = orders.hash_card
    LEFT JOIN users
    ON users.id_user = cards.id_user
    GROUP BY hash_card
    ORDER BY id_card ASC");

Getting a timestamp for today at midnight?

If you are using Carbon you can do the following. You could also format this date to set an Expire HTTP Header.

Carbon::parse('tomorrow midnight')->format(Carbon::RFC7231_FORMAT)

Git error when trying to push -- pre-receive hook declined

This is actually happens when YACC is enabled at server side in BitBucket. YACC is enable for JIRA issue names to be mentioned in the commit message. So whenever you commit anything atleast keep your JIRA number into the commit message and then additionally you can add your own message.

How to get ID of clicked element with jQuery

Your id will be passed through as #1, #2 etc. However, # is not valid as an ID (CSS selectors prefix IDs with #).

Find character position and update file name

If you're working with actual files (as opposed to some sort of string data), how about the following?

$files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }

(or use _.+$ if you want to cut everything from the first underscore.)

What is Gradle in Android Studio?

At the risk of being discursive I think behind this is the question of why the Android Studio / Gradle experience is so bad.

Typical Clojure experience :

  • download project with dependencies listed in project.clj.
  • Leiningen gets the dependencies thanks to Clojars and Maven.
  • Project compiles.

Typical Android Studio / Gradle experience :

  • "Import my Eclipse project".
  • OK project imported.
  • Gradle is doing it's thang ... wait ... wait ... wait ... Gradle has finished.
  • Compile ... can't compile because I don't know what an X is / can't find Y library.

I'm not sure this is Gradle's fault exactly. But the "import from Eclipse project" seems pretty flaky. For all of Gradle's alleged sophistication and the virtues of a build-system, Android Studio just doesn't seem to import the build dependencies or build-process from Eclipse very well.

It doesn't tell you when it's failed to import a complete dependency graph. The Android Studio gives no useful help or tips as to how to solve the problem. It doesn't tell you where you can manually look in the Eclipse folders. It doesn't tell you which library seems to be missing. Or help you search Maven etc. for them.

In 2016 things like Leiningen / Clojars, or node's npm, or Python's pip, or the Debian apkg (and I'm sure many similar package managers for other languages and systems) all work beautifully ... missing dependencies are thing of the past.

Except with Android. Android Studio is now the only place where I still seem to experience missing-dependency hell.

I'm inclined to say this is Google's fault. They broke the Android ecosystem (and thousands of existing Android projects / online tutorials) when they cavalierly decided to shift from Eclipse to Android Studio / Gradle without producing a robust conversion process. People whose projects work in Eclipse aren't adapting them to AS (presumably because it's a pain for them). And people trying to use those projects in AS are hitting the same issues.

And anyway, if Gradle is this super-powerful build system, why am I still managing a whole lot of other dependencies in the sdk manager? Why can't a project that needs, say, the ndk specify this in its Gradle file so that it gets automatically installed and built-against when needed? Why is NDK special? Similarly for target platforms? Why am I installing them explicitly in the IDE rather than just checking my project against them and having this all sorted for me behind the scenes?

Generate a random date between two other dates

# needed to create data for 1000 fictitious employees for testing code 
# code relating to randomly assigning forenames, surnames, and genders
# has been removed as not germaine to the question asked above but FYI
# genders were randomly assigned, forenames/surnames were web scrapped,
# there is no accounting for leap years, and the data stored in mySQL
   
import random 
from datetime import datetime
from datetime import timedelta

for employee in range(1000):
    # assign a random date of birth (employees are aged between sixteen and sixty five)
    dlt = random.randint(365*16, 365*65)
    dob = datetime.today() - timedelta(days=dlt)
    # assign a random date of hire sometime between sixteenth birthday and yesterday
    doh = datetime.today() - timedelta(days=random.randint(1, dlt-365*16))
    print("born {} hired {}".format(dob.strftime("%d-%m-%y"), doh.strftime("%d-%m-%y")))

using "if" and "else" Stored Procedures MySQL

The problem is you either haven't closed your if or you need an elseif:

create procedure checando(
    in nombrecillo varchar(30),
    in contrilla varchar(30), 
    out resultado int)
begin 

    if exists (select * from compas where nombre = nombrecillo and contrasenia = contrilla) then
        set resultado = 0;
    elseif exists (select * from compas where nombre = nombrecillo) then
        set resultado = -1;
    else 
        set resultado = -2;
    end if;
end;

Bootstrap 3: Text overlay on image

You need to set the thumbnail class to position relative then the post-content to absolute.

Check this fiddle

.post-content {
    top:0;
    left:0;
    position: absolute;
}

.thumbnail{
    position:relative;

}

Giving it top and left 0 will make it appear in the top left corner.

How can I get device ID for Admob

To get the Hash Device ID

inside the oncreate

String android_id = Settings.Secure.getString(this.getContentResolver(), Settings.Secure.ANDROID_ID);
        String deviceId = md5(android_id).toUpperCase();
Log.i("device id=",deviceId);

then add this class for md5 ()

public String md5(String s) {
        try {
            // Create MD5 Hash
            MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
            digest.update(s.getBytes());
            byte messageDigest[] = digest.digest();

            // Create Hex String
            StringBuffer hexString = new StringBuffer();
            for (int i=0; i<messageDigest.length; i++)
                hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }

How can I create Min stl priority_queue?

In C++11 you could also create an alias for convenience:

template<class T> using min_heap = priority_queue<T, std::vector<T>, std::greater<T>>;

And use it like this:

min_heap<int> my_heap;

Is there a cross-domain iframe height auto-resizer that works?

I got the solution for setting the height of the iframe dynamically based on it's content. This works for the cross domain content. There are some steps to follow to achieve this.

  1. Suppose you have added iframe in "abc.com/page" web page

    <div> <iframe id="IframeId" src="http://xyz.pqr/contactpage" style="width:100%;" onload="setIframeHeight(this)"></iframe> </div>

  2. Next you have to bind windows "message" event under web page "abc.com/page"

window.addEventListener('message', function (event) {
//Here We have to check content of the message event  for safety purpose
//event data contains message sent from page added in iframe as shown in step 3
if (event.data.hasOwnProperty("FrameHeight")) {
        //Set height of the Iframe
        $("#IframeId").css("height", event.data.FrameHeight);        
    }
});

On iframe load you have to send message to iframe window content with "FrameHeight" message:

function setIframeHeight(ifrm) {
   var height = ifrm.contentWindow.postMessage("FrameHeight", "*");   
}
  1. On main page that added under iframe here "xyz.pqr/contactpage" you have to bind windows "message" event where all messages are going to receive from parent window of "abc.com/page"
window.addEventListener('message', function (event) {

    // Need to check for safety as we are going to process only our messages
    // So Check whether event with data(which contains any object) contains our message here its "FrameHeight"
   if (event.data == "FrameHeight") {

        //event.source contains parent page window object 
        //which we are going to use to send message back to main page here "abc.com/page"

        //parentSourceWindow = event.source;

        //Calculate the maximum height of the page
        var body = document.body, html = document.documentElement;
        var height = Math.max(body.scrollHeight, body.offsetHeight,
            html.clientHeight, html.scrollHeight, html.offsetHeight);

       // Send height back to parent page "abc.com/page"
        event.source.postMessage({ "FrameHeight": height }, "*");       
    }
});

return SQL table as JSON in python

I knocked together a short script that dumps all data from all tables, as dicts of column name : value. Unlike other solutions, it doesn't require any info about what the tables or columns are, it just finds everything and dumps it. Hope someone finds it useful!

from contextlib import closing
from datetime import datetime
import json
import MySQLdb
DB_NAME = 'x'
DB_USER = 'y'
DB_PASS = 'z'

def get_tables(cursor):
    cursor.execute('SHOW tables')
    return [r[0] for r in cursor.fetchall()] 

def get_rows_as_dicts(cursor, table):
    cursor.execute('select * from {}'.format(table))
    columns = [d[0] for d in cursor.description]
    return [dict(zip(columns, row)) for row in cursor.fetchall()]

def dump_date(thing):
    if isinstance(thing, datetime):
        return thing.isoformat()
    return str(thing)


with closing(MySQLdb.connect(user=DB_USER, passwd=DB_PASS, db=DB_NAME)) as conn, closing(conn.cursor()) as cursor:
    dump = {}
    for table in get_tables(cursor):
        dump[table] = get_rows_as_dicts(cursor, table)
    print(json.dumps(dump, default=dump_date, indent=2))

How to call VS Code Editor from terminal / command line

In linux terminal you can just type:

$ code run

Problems installing the devtools package

As per damienfrancois's suggestion, I installed libcurl4-gnutls-dev and the problem was solved.

EDIT (@dardisco)

In your shell:

apt-get -y build-dep libcurl4-gnutls-dev
apt-get -y install libcurl4-gnutls-dev

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

Try this

SELECT Position_ID , Position_Name
FROM 
position
WHERE Position_ID IN (6 ,7 ,8)
ORDER BY Position_Name

How to express a NOT IN query with ActiveRecord/Rails?

You can use sql in your conditions:

Topic.find(:all, :conditions => [ "forum_id NOT IN (?)", @forums.map(&:id)])

MAX(DATE) - SQL ORACLE

Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:

SELECT
  max(MEMBSHIP_ID)
  keep (
      dense_rank first
      order by paym_date desc NULLS LAST
  ) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1

How to use executables from a package installed locally in node_modules?

Update: I no longer recommend this method, both for the mentioned security reasons and not the least the newer npm bin command. Original answer below:

As you have found out, any locally installed binaries are in ./node_modules/.bin. In order to always run binaries in this directory rather than globally available binaries, if present, I suggest you put ./node_modules/.bin first in your path:

export PATH="./node_modules/.bin:$PATH"

If you put this in your ~/.profile, coffee will always be ./node_modules/.bin/coffee if available, otherwise /usr/local/bin/coffee (or whatever prefix you are installing node modules under).

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

I got a shortcut for Idle (Python GUI).

  • Click on Window icon at the bottom left or use Window Key (only Python 2), you will see Idle (Python GUI) icon
  • Right click on the icon then more
  • Open File Location
  • A new window will appears, and you will see the shortcut of Idle (Python GUI)
  • Right click, hold down and pull out to desktop to create a shortcut of Python GUI on desktop.

MySQL, update multiple tables with one query

That's usually what stored procedures are for: to implement several SQL statements in a sequence. Using rollbacks, you can ensure that they are treated as one unit of work, ie either they are all executed or none of them are, to keep data consistent.

LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

I had this happen in Visual Studio 2015 too for an interesting reason. Just adding it here in case it happens to someone else.

I already had number of files in project and I was adding another one that would have main function in it, however when I initially added the file I made a typo in the extension (.coo instead of .cpp). I corrected that but when I was done I got this error. It turned out that Visual Studio was being smart and when file was added it decided that it is not a source file due to the initial extension.

Right-clicking on file in solution explorer and selecting Properties -> General -> ItemType and setting it to "C/C++ compiler" fixed the issue.

JavaFX Application Icon

I used this in my application

Image icon = new Image(getClass().getResourceAsStream("icon.png"));
window.getIcons().add(icon);

Here window is the stage.

How can I send an email by Java application using GMail, Yahoo, or Hotmail?

Even though this question is closed, I'd like to post a counter solution, but now using Simple Java Mail (Open Source JavaMail smtp wrapper):

final Email email = new Email();

String host = "smtp.gmail.com";
Integer port = 587;
String from = "username";
String pass = "password";
String[] to = {"[email protected]"};

email.setFromAddress("", from);
email.setSubject("sending in a group");
for( int i=0; i < to.length; i++ ) {
    email.addRecipient("", to[i], RecipientType.TO);
}
email.setText("Welcome to JavaMail");

new Mailer(host, port, from, pass).sendMail(email);
// you could also still use your mail session instead
new Mailer(session).sendMail(email);

Reading a file character by character in C

I think the most significant problem is that you're incrementing code as you read stuff in, and then returning the final value of code, i.e. you'll be returning a pointer to the end of the string. You probably want to make a copy of code before the loop, and return that instead.

Also, C strings need to be null-terminated. You need to make sure that you place a '\0' directly after the final character that you read in.

Note: You could just use fgets() to get the entire line in one hit.

How to jump to top of browser page

I know this is old, but for those having problems in Edge:

Plain JS: window.scrollTop=0;

Unfortunately, scroll() and scrollTo() throw errors in Edge.

Send email using the GMail SMTP server from a PHP page

The code as listed in the question needs two changes

$host = "ssl://smtp.gmail.com";
$port = "465";

Port 465 is required for an SSL connection.

Convert pandas dataframe to NumPy array

You can use the to_records method, but have to play around a bit with the dtypes if they are not what you want from the get go. In my case, having copied your DF from a string, the index type is string (represented by an object dtype in pandas):

In [102]: df
Out[102]: 
label    A    B    C
ID                  
1      NaN  0.2  NaN
2      NaN  NaN  0.5
3      NaN  0.2  0.5
4      0.1  0.2  NaN
5      0.1  0.2  0.5
6      0.1  NaN  0.5
7      0.1  NaN  NaN

In [103]: df.index.dtype
Out[103]: dtype('object')
In [104]: df.to_records()
Out[104]: 
rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
       (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
       (7, 0.1, nan, nan)], 
      dtype=[('index', '|O8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
In [106]: df.to_records().dtype
Out[106]: dtype([('index', '|O8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

Converting the recarray dtype does not work for me, but one can do this in Pandas already:

In [109]: df.index = df.index.astype('i8')
In [111]: df.to_records().view([('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])
Out[111]:
rec.array([(1, nan, 0.2, nan), (2, nan, nan, 0.5), (3, nan, 0.2, 0.5),
       (4, 0.1, 0.2, nan), (5, 0.1, 0.2, 0.5), (6, 0.1, nan, 0.5),
       (7, 0.1, nan, nan)], 
      dtype=[('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

Note that Pandas does not set the name of the index properly (to ID) in the exported record array (a bug?), so we profit from the type conversion to also correct for that.

At the moment Pandas has only 8-byte integers, i8, and floats, f8 (see this issue).

How to set JAVA_HOME environment variable on Mac OS X 10.9?

I've updated the great utility jenv to make it easy to setup on macOS.

Follow the instructions on https://github.com/hiddenswitch/jenv

What is console.log in jQuery?

It has nothing to do with jQuery, it's just a handy js method built into modern browsers.

Think of it as a handy alternative to debugging via window.alert()

.gitignore and "The following untracked working tree files would be overwritten by checkout"

Unfortunately neither git rm --cached or git clean -d -fx "" did it for me.

My solution ended up being pushing my branch to remote, cloning a new repo, then doing my merge in the new repo. Other people accessing the repo had to do the same.

Moral of the story: use a .gitignore file from inception.

Tomcat Server not starting with in 45 seconds

Disabling my antivirus does the trick for me ...

How to use a dot "." to access members of dictionary?

I tried this:

class dotdict(dict):
    def __getattr__(self, name):
        return self[name]

you can try __getattribute__ too.

make every dict a type of dotdict would be good enough, if you want to init this from a multi-layer dict, try implement __init__ too.

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

require 'alien'

if alien.platform == "windows" then
  kernel32 = alien.load("kernel32.dll")
  sleep = kernel32.Sleep
  sleep:types{ret="void",abi="stdcall","uint"}
else
  -- untested !!!
  libc = alien.default
  local usleep = libc.usleep
  usleep:types('int', 'uint')
  sleep = function(ms)
    while ms > 1000 do
      usleep(1000)
      ms = ms - 1000
    end
    usleep(1000 * ms)
  end
end 

print('hello')
sleep(500)  -- sleep 500 ms
print('world')

How to check a channel is closed or not without reading it?

it's easier to check first if the channel has elements, that would ensure the channel is alive.

func isChanClosed(ch chan interface{}) bool {
    if len(ch) == 0 {
        select {
        case _, ok := <-ch:
            return !ok
        }
    }
    return false 
}

EF 5 Enable-Migrations : No context type was found in the assembly

Follow the below steps to resolve the issue

Install-Package EntityFramework-IncludePrerelease

or Install entity framework from Nuget Package Manager

Restart visual studio

After that I was getting "No context type was found in assembly"

To resolve it - This "No context" that mean you need to create class in "Model" folder in your app with suffix like DbContext ... like this AppDbContext. There you need to include some library using System.Data.Entity;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;


namespace Oceans.Models
{
    public class MyDbContext:DbContext
    {
        public MyDbContext()
        {
        }
    }
}

After that run the below command on Package Manager:

Enable-Migrations -ProjectName <YourProjectName> -ContextTypeName <YourContextName>

My Project Name is - MyFirstApp and AppDbContext is inside the Model Folder so path is like

Enable-Migrations -StartUpProjectName MyFirstApp -ContextTypeName MyFirstApp.Models.AppDbContext

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

Sorry but they are only in Unicode. :(

Big ones:

  • U+25B2 (Black up-pointing triangle ?)
  • U+25BC (Black down-pointing triangle ?)
  • U+25C0 (Black left-pointing triangle ?)
  • U+25B6 (Black right-pointing triangle ?)

Big white ones:

  • U+25B3 (White up-pointing triangle ?)
  • U+25BD (White down-pointing triangle ?)
  • U+25C1 (White left-pointing triangle ?)
  • U+25B7 (White right-pointing triangle ?)

There is also some smalller triangles:

  • U+25B4 (Black up-pointing small triangle ?)
  • U+25C2 (Black left-pointing small triangle ?)
  • U+25BE (Black down-pointing small triangle ?)
  • U+25B8 (Black right-pointing small triangle ?)

Also some white ones:

  • U+25C3 (White left-pointing small triangle ?)
  • U+25BF (White down-pointing small triangle ?)
  • U+25B9 (White right-pointing small triangle ?)
  • U+25B5 (White up-pointing small triangle ?)

There are also some "pointy" triangles. You can read more here in Wikipedia:
http://en.wikipedia.org/wiki/Geometric_Shapes

But unfortunately, they are all Unicode instead of ASCII. If you still want to use ASCII, then you can use an image file for it of just use ^ and v. (Just like the Google Maps in the mobile version this was referring to the ancient mobile Google Maps)


As others also suggested, you can also create triangles with HTML, either with CSS borders or SVG shapes or even JavaScript canvases.

CSS

div{
    width: 0px;
    height: 0px;
    border-top: 10px solid black;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-bottom: none;
}

SVG

<svg width="16" height="10">
    <polygon points="0,0 16,0 8,10"/>
</svg>

JavaScript

var ctx = document.querySelector("canvas").getContext("2d");

// do not use with() outside of this demo!
with(ctx){
    beginPath();
    moveTo(0,0);
    lineTo(16,0);
    lineTo(8,10);
    fill();
    endPath();
}

Demo

Gradle version 2.2 is required. Current version is 2.10

Based on https://developer.android.com/studio/releases/gradle-plugin.html ...

The following table lists which version of Gradle is required for each version of the Android plugin for Gradle. For the best performance, you should use the latest possible version of both Gradle and the Android plugin.

So, the Plugin version with Required Gradle version should be match.

enter image description here

Undefined symbols for architecture arm64

I solved this problem by setting that:

ARCHS = armv7 armv7s

VALID_ARCHS = armv6 armv7 armv7s arm64

Create a branch in Git from another branch

For creating a branch from another one can use this syntax as well:

git push origin refs/heads/<sourceBranch>:refs/heads/<targetBranch>

It is a little shorter than "git checkout -b " + "git push origin "

How to add title to subplots in Matplotlib?

ax.title.set_text('My Plot Title') seems to work too.

fig = plt.figure()
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(222)
ax3 = fig.add_subplot(223)
ax4 = fig.add_subplot(224)
ax1.title.set_text('First Plot')
ax2.title.set_text('Second Plot')
ax3.title.set_text('Third Plot')
ax4.title.set_text('Fourth Plot')
plt.show()

matplotlib add titles on subplots

Can't bind to 'formControl' since it isn't a known property of 'input' - Angular2 Material Autocomplete issue

Forget trying to decipher the example .ts - as others have said it is often incomplete.

Instead just click on the 'pop-out' icon circled here and you'll get a fully working StackBlitz example.

enter image description here

You can quickly confirm the required modules:

enter image description here

Comment out any instances of ReactiveFormsModule, and sure enough you'll get the error:

Template parse errors:
Can't bind to 'formControl' since it isn't a known property of 'input'. 

Select multiple columns by labels in pandas

Just pick the columns you want directly....

df[['A','E','I','C']]

Resolve Javascript Promise outside function scope

Thanks to everyone who posted in this thread. I created a module that includes the Defer() object described earlier as well as a few other objects built upon it. They all leverage Promises and the neat Promise call-back syntax to implement communication/event handling within a program.

  • Defer: Promise that can be resolved failed remotely (outside of its body)
  • Delay: Promise that is resolved automatically after a given time
  • TimeOut: Promise that fails automatically after a given time.
  • Cycle: Re-triggerable promise to manage events with the Promise syntax
  • Queue: Execution queue based on Promise chaining.

rp = require("openpromise")

https://github.com/CABrouwers/openpromise https://www.npmjs.com/package/openpromise

CASE in WHERE, SQL Server

.. ELSE a.Country ...

I suppose

How do you get/set media volume (not ringtone volume) in Android?

You can set your activity to use a specific volume. In your activity, use one of the following:

this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
this.setVolumeControlStream(AudioManager.STREAM_RING);  
this.setVolumeControlStream(AudioManager.STREAM_ALARM);  
this.setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);  
this.setVolumeControlStream(AudioManager.STREAM_SYSTEM);  
this.setVolumeControlStream(AudioManager.STREAM_VOICECALL); 

How to set an image's width and height without stretching it?

#logo {
    width: 400px;
    height: 200px;

    /*Scale down will take the necessary specified space that is 400px x 200px without stretching the image*/
    object-fit:scale-down;
}

How to split a string content into an array of strings in PowerShell?

Remove the spaces from the original string and split on semicolon

$address = "[email protected]; [email protected]; [email protected]"
$addresses = $address.replace(' ','').split(';')

Or all in one line:

$addresses = "[email protected]; [email protected]; [email protected]".replace(' ','').split(';')

$addresses becomes:

@('[email protected]','[email protected]','[email protected]')

Convert generator object to list for debugging

Simply call list on the generator.

lst = list(gen)
lst

Be aware that this affects the generator which will not return any further items.

You also cannot directly call list in IPython, as it conflicts with a command for listing lines of code.

Tested on this file:

def gen():
    yield 1
    yield 2
    yield 3
    yield 4
    yield 5
import ipdb
ipdb.set_trace()

g1 = gen()

text = "aha" + "bebe"

mylst = range(10, 20)

which when run:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> lst = list(g1)
ipdb> lst
[1, 2, 3, 4, 5]
ipdb> q
Exiting Debugger.

General method for escaping function/variable/debugger name conflicts

There are debugger commands p and pp that will print and prettyprint any expression following them.

So you could use it as follows:

$ python code.py 
> /home/javl/sandbox/so/debug/code.py(10)<module>()
      9 
---> 10 g1 = gen()
     11 

ipdb> n
> /home/javl/sandbox/so/debug/code.py(12)<module>()
     11 
---> 12 text = "aha" + "bebe"
     13 

ipdb> p list(g1)
[1, 2, 3, 4, 5]
ipdb> c

There is also an exec command, called by prefixing your expression with !, which forces debugger to take your expression as Python one.

ipdb> !list(g1)
[]

For more details see help p, help pp and help exec when in debugger.

ipdb> help exec
(!) statement
Execute the (one-line) statement in the context of
the current stack frame.
The exclamation point can be omitted unless the first word
of the statement resembles a debugger command.
To assign to a global variable you must always prefix the
command with a 'global' command, e.g.:
(Pdb) global list_options; list_options = ['-l']

Android and Facebook share intent

Here is what I did (for text). In the code, I copy whatever text is needed to clipboard. The first time an individual tries to use the share intent button, I pop up a notification that explains if they wish to share to facebook, they need to click 'Facebook' and then long press to paste (this is to make them aware that Facebook has BROKEN the android intent system). Then the relevant information is in the field. I might also include a link to this post so users can complain too...

private void setClipboardText(String text) { // TODO
    int sdk = android.os.Build.VERSION.SDK_INT;
    if(sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(text);
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
        android.content.ClipData clip = android.content.ClipData.newPlainText("text label",text);
        clipboard.setPrimaryClip(clip);
    }
}

Below is a method for dealing w/prior versions

public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case R.id.menu_item_share:
        Intent shareIntent = new Intent(Intent.ACTION_SEND);
        shareIntent.setType("text/plain");
        shareIntent.putExtra(Intent.EXTRA_TEXT, "text here");

        ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE); //TODO
         ClipData clip = ClipData.newPlainText("label", "text here");
         clipboard.setPrimaryClip(clip);

        setShareIntent(shareIntent); 

        break;
    }
        return super.onOptionsItemSelected(item);
}

Routing with Multiple Parameters using ASP.NET MVC

You can pass arbitrary parameters through the query string, but you can also set up custom routes to handle it in a RESTful way:

http://ws.audioscrobbler.com/2.0/?method=artist.getimages&artist=cher&
                                  api_key=b25b959554ed76058ac220b7b2e0a026

That could be:

routes.MapRoute(
    "ArtistsImages",
    "{ws}/artists/{artist}/{action}/{*apikey}",
    new { ws = "2.0", controller="artists" artist = "", action="", apikey="" }
    );

So if someone used the following route:

ws.audioscrobbler.com/2.0/artists/cher/images/b25b959554ed76058ac220b7b2e0a026/

It would take them to the same place your example querystring did.

The above is just an example, and doesn't apply the business rules and constraints you'd have to set up to make sure people didn't 'hack' the URL.

in iPhone App How to detect the screen resolution of the device

Use this code it will help for getting any type of device's screen resolution

 [[UIScreen mainScreen] bounds].size.height
 [[UIScreen mainScreen] bounds].size.width

How can I hide/show a div when a button is clicked?

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Show and hide div with JavaScript</title>
<script>

    var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
    var show_button = 'Show', hide_button = 'Hide';
    function showhide() {
        var div = document.getElementById( "hide_show" );
        var showhide = document.getElementById( "showhide" );
        if ( div.style.display !== "none" ) {
            div.style.display = "none";
            button = show_button;
            showhide.innerHTML = button_beg + button + button_end;
        } else {
            div.style.display = "block";
            button = hide_button;
            showhide.innerHTML = button_beg + button + button_end;
        }
    }
    function setup_button( status ) {
        if ( status == 'show' ) {
            button = hide_button;
        } else {
            button = show_button;
        }
        var showhide = document.getElementById( "showhide" );
        showhide.innerHTML = button_beg + button + button_end;
    }
    window.onload = function () {
        setup_button( 'hide' );
        showhide(); // if setup_button is set to 'show' comment this line
    }
</script>
</head>
<body>
    <div id="showhide"></div>
    <div id="hide_show">
        <p>This div will be show and hide on button click</p>
    </div>
</body>
</html>

How to execute a file within the python interpreter?

Python 2 + Python 3

exec(open("./path/to/script.py").read(), globals())

This will execute a script and put all it's global variables in the interpreter's global scope (the normal behavior in most scripting environments).

Python 3 exec Documentation

how to bypass Access-Control-Allow-Origin?

Have you tried actually adding the Access-Control-Allow-Origin header to the response sent from your server? Like, Access-Control-Allow-Origin: *?

Mockito How to mock only the call of a method of the superclass

No, Mockito does not support this.

This might not be the answer you're looking for, but what you're seeing is a symptom of not applying the design principle:

Favor composition over inheritance

If you extract a strategy instead of extending a super class the problem is gone.

If however you are not allowed to change the code, but you must test it anyway, and in this awkward way, there is still hope. With some AOP tools (for example AspectJ) you can weave code into the super class method and avoid its execution entirely (yuck). This doesn't work if you're using proxies, you have to use bytecode modification (either load time weaving or compile time weaving). There are be mocking frameworks that support this type of trick as well, like PowerMock and PowerMockito.

I suggest you go for the refactoring, but if that is not an option you're in for some serious hacking fun.

Access to the path is denied

I was having the same problem while trying to create a file on the server (actually a file that is a copy from a template).

Here's the complete error message:

{ERROR} 08/07/2012 22:15:58 - System.UnauthorizedAccessException: Access to the path 'C:\inetpub\wwwroot\SAvE\Templates\Cover.pdf' is denied.

I added a new folder called Templates inside the IIS app folder. One very important thing in my case is that I needed to give the Write (Gravar) permission for the IUSR user on that folder. You may also need to give Network Service and ASP.NET v$.# the same Write permission.

enter image description here

After doing this everything works as expected.

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

A simple two lines of code works for me.

dataGridView.DataSource = dataTable;
dataGridView.AutoResizeColumns();

How to get screen width without (minus) scrollbar?

Try this :

$('body, html').css('overflow', 'hidden');
var screenWidth1 = $(window).width();
$('body, html').css('overflow', 'visible');
var screenWidth2 = $(window).width();
alert(screenWidth1); // Gives the screenwith without scrollbar
alert(screenWidth2); // Gives the screenwith including scrollbar

You can get the screen width by with and without scroll bar by using this code. Here, I have changed the overflow value of body and get the width with and without scrollbar.

What is the best way to seed a database in Rails?

Rails has a built in way to seed data as explained here.

Another way would be to use a gem for more advanced or easy seeding such as: seedbank.

The main advantage of this gem and the reason I use it is that it has advanced capabilities such as data loading dependencies and per environment seed data.

Adding an up to date answer as this answer was first on google.

Singular matrix issue with Numpy

The matrix you pasted

[[   1,    8,   50],
 [   8,   64,  400],
 [  50,  400, 2500]]

Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)

http://en.wikipedia.org/wiki/Invertible_matrix

Error: No Firebase App '[DEFAULT]' has been created - call Firebase App.initializeApp()

If you are starting out a react-native app and seeing this issue, then you have to follow all the instructions listed in firebase (when you setup iOS/android app) or the instructions @ React-native google auth android DEVELOPER_ERROR Code 10 question

enter image description here

What is a C++ delegate?

An option for delegates in C++ that is not otherwise mentioned here is to do it C style using a function ptr and a context argument. This is probably the same pattern that many asking this question are trying to avoid. But, the pattern is portable, efficient, and is usable in embedded and kernel code.

class SomeClass
{
    in someMember;
    int SomeFunc( int);

    static void EventFunc( void* this__, int a, int b, int c)
    {
        SomeClass* this_ = static_cast< SomeClass*>( this__);

        this_->SomeFunc( a );
        this_->someMember = b + c;
    }
};

void ScheduleEvent( void (*delegateFunc)( void*, int, int, int), void* delegateContext);

    ...
    SomeClass* someObject = new SomeObject();
    ...
    ScheduleEvent( SomeClass::EventFunc, someObject);
    ...

Check if the number is integer

[UPDATE] ==============================================================

Respect to the [OLD] answer here below, I have discovered that it worked because I have put all the numbers in a single atomic vector; one of them was a character, so every one become characters.

If we use a list (hence, coercion does not happen) all the test pass correctly but one: 1/(1 - 0.98), which remains a numeric. This because the tol parameter is by default 100 * .Machine$double.eps and that number is far from 50 little less than the double of that. So, basically, for this kind of numbers, we have to decide our tolerance!

So if you want all test became TRUE, you can assertive::is_whole_number(x, tol = 200 * .Machine$double.eps)

Anyway, I confirm that IMO assertive remains the best solution.

Here below a reprex for this [UPDATE].

expect_trues_c <- c(
  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # this is under machine precision!
)

str(expect_trues_c)
#>  Named chr [1:15] "2" "9" "50" "66" "66" "1" "222000" "10000" "1e+05" ...
#>  - attr(*, "names")= chr [1:15] "cl" "pp" "t" "ar0" ...
assertive::is_whole_number(expect_trues_c)
#> Warning: Coercing expect_trues_c to class 'numeric'.
#>                      2                      9                     50 
#>                   TRUE                   TRUE                   TRUE 
#>                     66                     66                      1 
#>                   TRUE                   TRUE                   TRUE 
#>                 222000                  10000                 100000 
#>                   TRUE                   TRUE                   TRUE 
#>                  1e+36                      2                  1e+22 
#>                   TRUE                   TRUE                   TRUE 
#> 9.9999999999999998e+23                      1                      1 
#>                   TRUE                   TRUE                   TRUE



expect_trues_l <- list(
  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # this is under machine precision!
)

str(expect_trues_l)
#> List of 15
#>  $ cl : num 2
#>  $ pp : num 9
#>  $ t  : num 50
#>  $ ar0: int 66
#>  $ ar1: num 66
#>  $ ar2: num 1
#>  $ v  : num 222000
#>  $ w1 : num 10000
#>  $ w2 : num 1e+05
#>  $ v2 : chr "1000000000000000000000000000000000001"
#>  $ an : num 2
#>  $ ju1: num 1e+22
#>  $ ju2: num 1e+24
#>  $ al : num 1
#>  $ v5 : num 1
assertive::is_whole_number(expect_trues_l)
#> Warning: Coercing expect_trues_l to class 'numeric'.
#> There was 1 failure:
#>   Position              Value      Cause
#> 1        3 49.999999999999957 fractional
assertive::is_whole_number(expect_trues_l, tol = 200 * .Machine$double.eps)
#> Warning: Coercing expect_trues_l to class 'numeric'.
#>     2.0000000000000004                      9     49.999999999999957 
#>                   TRUE                   TRUE                   TRUE 
#>                     66                     66     1.0000000000000009 
#>                   TRUE                   TRUE                   TRUE 
#>                 222000                  10000                 100000 
#>                   TRUE                   TRUE                   TRUE 
#>                  1e+36     1.9999999999999998                  1e+22 
#>                   TRUE                   TRUE                   TRUE 
#> 9.9999999999999998e+23                      1                      1 
#>                   TRUE                   TRUE                   TRUE



expect_falses <- list(
  bb = 5 - 1e-8,
  pt1 = 1.0000001,
  pt2 = 1.00000001,
  v3 = 3243.34,
  v4 = "sdfds"
)

str(expect_falses)
#> List of 5
#>  $ bb : num 5
#>  $ pt1: num 1
#>  $ pt2: num 1
#>  $ v3 : num 3243
#>  $ v4 : chr "sdfds"
assertive::is_whole_number(expect_falses)
#> Warning: Coercing expect_falses to class 'numeric'.
#> Warning in as.this_class(x): NAs introduced by coercion
#> There were 5 failures:
#>   Position              Value      Cause
#> 1        1 4.9999999900000001 fractional
#> 2        2 1.0000001000000001 fractional
#> 3        3 1.0000000099999999 fractional
#> 4        4 3243.3400000000001 fractional
#> 5        5               <NA>    missing
assertive::is_whole_number(expect_falses, tol = 200 * .Machine$double.eps)
#> Warning: Coercing expect_falses to class 'numeric'.

#> Warning: NAs introduced by coercion
#> There were 5 failures:
#>   Position              Value      Cause
#> 1        1 4.9999999900000001 fractional
#> 2        2 1.0000001000000001 fractional
#> 3        3 1.0000000099999999 fractional
#> 4        4 3243.3400000000001 fractional
#> 5        5               <NA>    missing

Created on 2019-07-23 by the reprex package (v0.3.0)

[OLD] =================================================================

IMO the best solution comes from the assertive package (which, for the moment, solve all positive and negative examples in this thread):

are_all_whole_numbers <- function(x) {
  all(assertive::is_whole_number(x), na.rm = TRUE)
}

are_all_whole_numbers(c(
  cl = sqrt(2)^2,
  pp = 9.0,
  t = 1 / (1 - 0.98),
  ar0 = 66L,
  ar1 = 66,
  ar2 = 1 + 2^-50,
  v = 222e3,
  w1 = 1e4,
  w2 = 1e5,
  v2 = "1000000000000000000000000000000000001",
  an = 2 / 49 * 49,
  ju1 = 1e22,
  ju2 = 1e24,
  al = floor(1),
  v5 = 1.0000000000000001 # difference is under machine precision!
))
#> Warning: Coercing x to class 'numeric'.
#> [1] TRUE

are_all_not_whole_numbers <- function(x) {
  all(!assertive::is_whole_number(x), na.rm = TRUE)
}

are_all_not_whole_numbers(c(
  bb = 5 - 1e-8,
  pt1 = 1.0000001,
  pt2 = 1.00000001,
  v3 = 3243.34,
  v4 = "sdfds"
))
#> Warning: Coercing x to class 'numeric'.
#> Warning in as.this_class(x): NAs introduced by coercion
#> [1] TRUE

Created on 2019-07-23 by the reprex package (v0.3.0)

set height of imageview as matchparent programmatically

For Kotlin Users

val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params

Here I used FrameLayout.LayoutParams since my views( ImageView) parent is FrameLayout

Simple PHP Pagination script

 <?php
// Custom PHP MySQL Pagination Tutorial and Script
// You have to put your mysql connection data and alter the SQL queries(both queries)

mysql_connect("DATABASE_Host_Here","DATABASE_Username_Here","DATABASE_Password_Here") or die (mysql_error());
mysql_select_db("DATABASE_Name_Here") or die (mysql_error());
//////////////  QUERY THE MEMBER DATA INITIALLY LIKE YOU NORMALLY WOULD
$sql = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC");
//////////////////////////////////// Pagination Logic ////////////////////////////////////////////////////////////////////////
$nr = mysql_num_rows($sql); // Get total of Num rows from the database query
if (isset($_GET['pn'])) { // Get pn from URL vars if it is present
    $pn = preg_replace('#[^0-9]#i', '', $_GET['pn']); // filter everything but numbers for security(new)
    //$pn = ereg_replace("[^0-9]", "", $_GET['pn']); // filter everything but numbers for security(deprecated)
} else { // If the pn URL variable is not present force it to be value of page number 1
    $pn = 1;
}
//This is where we set how many database items to show on each page
$itemsPerPage = 10;
// Get the value of the last page in the pagination result set
$lastPage = ceil($nr / $itemsPerPage);
// Be sure URL variable $pn(page number) is no lower than page 1 and no higher than $lastpage
if ($pn < 1) { // If it is less than 1
    $pn = 1; // force if to be 1
} else if ($pn > $lastPage) { // if it is greater than $lastpage
    $pn = $lastPage; // force it to be $lastpage's value
}
// This creates the numbers to click in between the next and back buttons
// This section is explained well in the video that accompanies this script
$centerPages = "";
$sub1 = $pn - 1;
$sub2 = $pn - 2;
$add1 = $pn + 1;
$add2 = $pn + 2;
if ($pn == 1) {
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
} else if ($pn == $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
} else if ($pn > 2 && $pn < ($lastPage - 1)) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub2 . '">' . $sub2 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add2 . '">' . $add2 . '</a> &nbsp;';
} else if ($pn > 1 && $pn < $lastPage) {
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $sub1 . '">' . $sub1 . '</a> &nbsp;';
    $centerPages .= '&nbsp; <span class="pagNumActive">' . $pn . '</span> &nbsp;';
    $centerPages .= '&nbsp; <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $add1 . '">' . $add1 . '</a> &nbsp;';
}
// This line sets the "LIMIT" range... the 2 values we place to choose a range of rows from database in our query
$limit = 'LIMIT ' .($pn - 1) * $itemsPerPage .',' .$itemsPerPage;
// Now we are going to run the same query as above but this time add $limit onto the end of the SQL syntax
// $sql2 is what we will use to fuel our while loop statement below
$sql2 = mysql_query("SELECT id, firstname, country FROM myTable ORDER BY id ASC $limit");
//////////////////////////////// END Pagination Logic ////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////// Pagination Display Setup /////////////////////////////////////////////////////////////////////
$paginationDisplay = ""; // Initialize the pagination output variable
// This code runs only if the last page variable is ot equal to 1, if it is only 1 page we require no paginated links to display
if ($lastPage != "1"){
    // This shows the user what page they are on, and the total number of pages
    $paginationDisplay .= 'Page <strong>' . $pn . '</strong> of ' . $lastPage. '&nbsp;  &nbsp;  &nbsp; ';
    // If we are not on page 1 we can place the Back button
    if ($pn != 1) {
        $previous = $pn - 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $previous . '"> Back</a> ';
    }
    // Lay in the clickable numbers display here between the Back and Next links
    $paginationDisplay .= '<span class="paginationNumbers">' . $centerPages . '</span>';
    // If we are not on the very last page we can place the Next button
    if ($pn != $lastPage) {
        $nextPage = $pn + 1;
        $paginationDisplay .=  '&nbsp;  <a href="' . $_SERVER['PHP_SELF'] . '?pn=' . $nextPage . '"> Next</a> ';
    }
}
///////////////////////////////////// END Pagination Display Setup ///////////////////////////////////////////////////////////////////////////
// Build the Output Section Here
$outputList = '';
while($row = mysql_fetch_array($sql2)){

    $id = $row["id"];
    $firstname = $row["firstname"];
    $country = $row["country"];

    $outputList .= '<h1>' . $firstname . '</h1><h2>' . $country . ' </h2><hr />';

} // close while loop
?>
<html>
<head>
<title>Simple Pagination</title>
</head>
<body>
   <div style="margin-left:64px; margin-right:64px;">
     <h2>Total Items: <?php echo $nr; ?></h2>
   </div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
      <div style="margin-left:64px; margin-right:64px;"><?php print "$outputList"; ?></div>
      <div style="margin-left:58px; margin-right:58px; padding:6px; background-color:#FFF; border:#999 1px solid;"><?php echo $paginationDisplay; ?></div>
</body>
</html> 

'No database provider has been configured for this DbContext' on SignInManager.PasswordSignInAsync

This is the solution i found.

https://github.com/aspnet/EntityFramework.Docs/blob/master/entity-framework/core/miscellaneous/configuring-dbcontext.md

Configure DBContext via AddDbContext

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<BloggingContext>(options => options.UseSqlite("Data Source=blog.db"));
}

Add new constructor to your DBContext class

public class BloggingContext : DbContext
{
    public BloggingContext(DbContextOptions<BloggingContext> options)
      :base(options)
    { }

    public DbSet<Blog> Blogs { get; set; }
}

Inject context to your controllers

public class MyController
{
    private readonly BloggingContext _context;

    public MyController(BloggingContext context)
    {
      _context = context;
    }

    ...
}

How to clone all remote branches in Git?

A git clone is supposed to copy the entire repository. Try cloning it, and then run git branch -a. It should list all the branches. If then you want to switch to branch "foo" instead of "master", use git checkout foo.

How can I disable the bootstrap hover color for links?

I am not a Bootstrap expert, but it sounds to me that you should define a new class called nohover (or something equivalent) then in your link code add the class as the last attribute value:

<a class="green nohover" href="#">green text</a>
<a class="yellow nohover" href="#">yellow text</a>

Then in your Bootstrap LESS/CSS file, define nohover (using the JSFiddle example above):

a:hover { color: red  }
/* Green */
a.green  { color: green; }
/* Yellow */
a.yellow  { color: yellow; }
a.nohover:hover { color: none;  }

Forked the JSFiddle here: http://jsfiddle.net/9rpkq/

jQuery: Check if special characters exists in string

You could also use the whitelist method -

var str = $('#Search').val();
var regex = /[^\w\s]/gi;

if(regex.test(str) == true) {
    alert('Your search string contains illegal characters.');
}

The regex in this example is digits, word characters, underscores (\w) and whitespace (\s). The caret (^) indicates that we are to look for everything that is not in our regex, so look for things that are not word characters, underscores, digits and whitespace.

How to set up subdomains on IIS 7

This one drove me crazy... basically you need two things:

1) Make sure your DNS is setup to point to your subdomain. This means to make sure you have an A Record in the DNS for your subdomain and point to the same IP.

2) You must add an additional website in IIS 7 named subdomain.example.com

  • Sites > Add Website
  • Site Name: subdomain.example.com
  • Physical Path: select the subdomain directory
  • Binding: same ip as example.com
  • Host name: subdomain.example.com

What does the question mark in Java generics' type parameter mean?

List<? extends HasWord> accepts any concrete classes that extends HasWord. If you have the following classes...

public class A extends HasWord { .. }
public class B extends HasWord { .. }
public class C { .. }
public class D extends SomeOtherWord { .. }

... the wordList can ONLY contain a list of either As or Bs or mixture of both because both classes extend the same parent or null (which fails instanceof checks for HasWorld).

Why do I get AttributeError: 'NoneType' object has no attribute 'something'?

g.d.d.c. is right, but adding a very frequent example:

You might call this function in a recursive form. In that case, you might end up at null pointer or NoneType. In that case, you can get this error. So before accessing an attribute of that parameter check if it's not NoneType.

How to choose an AWS profile when using boto3 to connect to CloudFront

I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.

So there are three different ways to do this:

Option A) Create a new session with the profile

    dev = boto3.session.Session(profile_name='dev')

Option B) Change the profile of the default session in code

    boto3.setup_default_session(profile_name='dev')

Option C) Change the profile of the default session with an environment variable

    $ AWS_PROFILE=dev ipython
    >>> import boto3
    >>> s3dev = boto3.resource('s3')

Error converting data types when importing from Excel to SQL Server 2008

SSIS doesn't implicitly convert data types, so you need to do it explicitly. The Excel connection manager can only handle a few data types and it tries to make a best guess based on the first few rows of the file. This is fully documented in the SSIS documentation.

You have several options:

  • Change your destination data type to float
  • Load to a 'staging' table with data type float using the Import Wizard and then INSERT into the real destination table using CAST or CONVERT to convert the data
  • Create an SSIS package and use the Data Conversion transformation to convert the data

You might also want to note the comments in the Import Wizard documentation about data type mappings.

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

How do I modify fields inside the new PostgreSQL JSON datatype?

You can try updating as below:

Syntax: UPDATE table_name SET column_name = column_name::jsonb || '{"key":new_value}' WHERE column_name condition;

For your example:

UPDATE test SET data = data::jsonb || '{"a":new_value}' WHERE data->>'b' = '2';

Monad in plain English? (For the OOP programmer with no FP background)

See my answer to "What is a monad?"

It begins with a motivating example, works through the example, derives an example of a monad, and formally defines "monad".

It assumes no knowledge of functional programming and it uses pseudocode with function(argument) := expression syntax with the simplest possible expressions.

This C++ program is an implementation of the pseudocode monad. (For reference: M is the type constructor, feed is the "bind" operation, and wrap is the "return" operation.)

#include <iostream>
#include <string>

template <class A> class M
{
public:
    A val;
    std::string messages;
};

template <class A, class B>
M<B> feed(M<B> (*f)(A), M<A> x)
{
    M<B> m = f(x.val);
    m.messages = x.messages + m.messages;
    return m;
}

template <class A>
M<A> wrap(A x)
{
    M<A> m;
    m.val = x;
    m.messages = "";
    return m;
}

class T {};
class U {};
class V {};

M<U> g(V x)
{
    M<U> m;
    m.messages = "called g.\n";
    return m;
}

M<T> f(U x)
{
    M<T> m;
    m.messages = "called f.\n";
    return m;
}

int main()
{
    V x;
    M<T> m = feed(f, feed(g, wrap(x)));
    std::cout << m.messages;
}

Escape double quotes in Java

For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.

svn over HTTP proxy

If you can get SSH to it you can an SSH Port-forwarded SVN server.

Use SSHs -L ( or -R , I forget, it always confuses me ) to make an ssh tunnel so that

127.0.0.1:3690 is really connecting to remote:3690 over the ssh tunnel, and then you can use it via

svn co svn://127.0.0.1/....

How do I find an array item with TypeScript? (a modern, easier way)

Part One - Polyfill

For browsers that haven't implemented it, a polyfill for array.find. Courtesy of MDN.

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}

Part Two - Interface

You need to extend the open Array interface to include the find method.

interface Array<T> {
    find(predicate: (search: T) => boolean) : T;
}

When this arrives in TypeScript, you'll get a warning from the compiler that will remind you to delete this.

Part Three - Use it

The variable x will have the expected type... { id: number }

var x = [{ "id": 1 }, { "id": -2 }, { "id": 3 }].find(myObj => myObj.id < 0);

Working with time DURATION, not time of day

The best way I found to resolve this issue was by using a combination of the above. All my cells were entered as a Custom Format to only show "HH:MM" - if I entered in "4:06" (being 4 minutes and 6 seconds) the field would show the numbers I entered correctly - but the data itself would represent HH:MM in the background.

Fortunately time is based on factors of 60 (60 seconds = 60 minutes). So 7H:15M / 60 = 7M:15S - I hope you can see where this is going. Accordingly, if I take my 4:06 and divide by 60 when working with the data (eg. to total up my total time or average time across 100 cells I would use the normal SUM or AVERAGE formulas and then divide by 60 in the formula.

Example =(SUM(A1:A5))/60. If my data was across the 5 time tracking fields was the 4:06, 3:15, 9:12, 2:54, 7:38 (representing MM:SS for us, but the data in the background is actually HH:MM) then when I work out the sum of those 5 fields are, what I want should be 27M:05S but what shows instead is 1D:03H:05M:00S. As mentioned above, 1D:3H:5M divided by 60 = 27M:5S ... which is the sum I am looking for.

Further examples of this are: =(SUM(G:G))/60 and =(AVERAGE(B2:B90)/60) and =MIN(C:C) (this is a direct check so no /60 needed here!).

Note that your "formula" or "calculation" fields (average, total time, etc) MUST have the custom format of MM:SS once you have divided by 60 as Excel's default thinking is in HH:MM (hence this issue). Your data fields where you are entering in your times should need to be changed from "General" or "Number" format to the custom format of HH:MM.

This process is still a little bit cumbersome to use - but it does mean that your data entry is still entered in very easy and is "correctly" displayed on screen as 4:06 (which most people would view as minutes:seconds when under a "Minutes" header). Generally there will only be a couple of fields needing to be used for formulas such as "best time", "average time", "total time" etc when tracking times and they will not usually be changed once the formula is entered so this will be a "one off" process - I use this for my call tracking sheet at work to track "average call", "total call time for day".

Running ASP.Net on a Linux based server

You can use Mono to run ASP.NET applications on Apache/Linux, however it has a limited subset of what you can do under Windows. As for "they" saying Windows is more vulnerable to attack - it's not true. IIS has had less security problems over the last couple of years that Apache, but in either case it's all down to the administration of the boxes - both OSes can be easily secured. These days the attack points are not the OS or web server software, but the applications themselves.

Angular 2 Hover event

yes there is on-mouseover in angular2 instead of ng-Mouseover like in angular 1.x so you have to write this :-

<div on-mouseover='over()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

over(){
    console.log("Mouseover called");
  }

As @Gunter Suggested in comment there is alternate of on-mouseover we can use this too. Some people prefer the on- prefix alternative, known as the canonical form.

Update

HTML Code -

<div (mouseover)='over()' (mouseout)='out()' style="height:100px; width:100px; background:#e2e2e2">hello mouseover</div>

Controller/.TS Code -

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  over(){
    console.log("Mouseover called");
  }

  out(){
    console.log("Mouseout called");
  }
}

Working Example

Some other Mouse events can be used in Angular -

(mouseenter)="myMethod()"
(mousedown)="myMethod()"
(mouseup)="myMethod()"

Select multiple rows with the same value(s)

You need to understand that when you include GROUP BY in your query you are telling SQL to combine rows. you will get one row per unique Locus value. The Having then filters those groups. Usually you specify an aggergate function in the select list like:

--show how many of each Locus there is
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus

--only show the groups that have more than one row in them
SELECT COUNT(*),Locus FROM Genes GROUP BY Locus HAVING COUNT(*)>1

--to just display all the rows for your condition, don't use GROUP BY or HAVING
SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10'

JavaScript get child element

Try this one:

function show_sub(cat) {
    var parent = cat,
    sub = parent.getElementsByClassName('sub');
    if (sub[0].style.display == 'inline'){
        sub[0].style.display = 'none';
    }
    else {
        sub[0].style.display = 'inline';
    }
}

document.getElementById('cat').onclick = function(){
    show_sub(this);
};?

and use this for IE6 & 7

if (typeof document.getElementsByClassName!='function') {
    document.getElementsByClassName = function() {
        var elms = document.getElementsByTagName('*');
        var ei = new Array();
        for (i=0;i<elms.length;i++) {
            if (elms[i].getAttribute('class')) {
               ecl = elms[i].getAttribute('class').split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            } else if (elms[i].className) {
                ecl = elms[i].className.split(' ');
                for (j=0;j<ecl.length;j++) {
                    if (ecl[j].toLowerCase() == arguments[0].toLowerCase()) {
                        ei.push(elms[i]);
                    }
                }
            }
        }
        return ei;
    }
}

Chmod recursively

You need read access, in addition to execute access, to list a directory. If you only have execute access, then you can find out the names of entries in the directory, but no other information (not even types, so you don't know which of the entries are subdirectories). This works for me:

find . -type d -exec chmod +rx {} \;

How to create a custom navigation drawer in android

I need to add a header to categorize the list item in Drawer

Customize the listView or use expandableListView

I need a radio button to select some of my options

You can do that without modifying the current implementation of NavigationDrawer, You just need to create a custom adapter for your listView. You can add a parent layout as Drawer then you can do any complex layouts within that as normal.

How do you convert a byte array to a hexadecimal string, and vice versa?

Either:

public static string ByteArrayToString(byte[] ba)
{
  StringBuilder hex = new StringBuilder(ba.Length * 2);
  foreach (byte b in ba)
    hex.AppendFormat("{0:x2}", b);
  return hex.ToString();
}

or:

public static string ByteArrayToString(byte[] ba)
{
  return BitConverter.ToString(ba).Replace("-","");
}

There are even more variants of doing it, for example here.

The reverse conversion would go like this:

public static byte[] StringToByteArray(String hex)
{
  int NumberChars = hex.Length;
  byte[] bytes = new byte[NumberChars / 2];
  for (int i = 0; i < NumberChars; i += 2)
    bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
  return bytes;
}

Using Substring is the best option in combination with Convert.ToByte. See this answer for more information. If you need better performance, you must avoid Convert.ToByte before you can drop SubString.

Explanation on Integer.MAX_VALUE and Integer.MIN_VALUE to find min and max value in an array

By initializing the min/max values to their extreme opposite, you avoid any edge cases of values in the input: Either one of min/max is in fact one of those values (in the case where the input consists of only one of those values), or the correct min/max will be found.

It should be noted that primitive types must have a value. If you used Objects (ie Integer), you could initialize value to null and handle that special case for the first comparison, but that creates extra (needless) code. However, by using these values, the loop code doesn't need to worry about the edge case of the first comparison.

Another alternative is to set both initial values to the first value of the input array (never a problem - see below) and iterate from the 2nd element onward, since this is the only correct state of min/max after one iteration. You could iterate from the 1st element too - it would make no difference, other than doing one extra (needless) iteration over the first element.

The only sane way of dealing with inout of size zero is simple: throw an IllegalArgumentException, because min/max is undefined in this case.

Add a CSS border on hover without moving the element

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc.

java.lang.IllegalStateException: Fragment not attached to Activity

I adopted the following approach for handling this issue. Created a new class which act as a wrapper for activity methods like this

public class ContextWrapper {
    public static String getString(Activity activity, int resourceId, String defaultValue) {
        if (activity != null) {
            return activity.getString(resourceId);
        } else {
            return defaultValue;
        }
    }

    //similar methods like getDrawable(), getResources() etc

}

Now wherever I need to access resources from fragments or activities, instead of directly calling the method, I use this class. In case the activity context is not null it returns the value of the asset and in case the context is null, it passes a default value (which is also specified by the caller of the function).

Important This is not a solution, this is an effective way where you can handle this crash gracefully. You would want to add some logs in cases where you are getting activity instance as null and try to fix that, if possible.

How to check queue length in Python

len(queue) should give you the result, 3 in this case.

Specifically, len(object) function will call object.__len__ method [reference link]. And the object in this case is deque, which implements __len__ method (you can see it by dir(deque)).


queue= deque([])   #is this length 0 queue?

Yes it will be 0 for empty deque.

How to enable Logger.debug() in Log4j

I like to use a rolling file appender to write the logging info to a file. My log4j properties file typically looks something like this. I prefer this way since I like to make package specific logging in case I need varying degrees of logging for different packages. Only one package is mentioned in the example.

log4j.appender.RCS=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RCS.File.DateFormat='.'yyyy-ww
#define output location
log4j.appender.RCS.File=C:temp/logs/MyService.log
#define the file layout
log4j.appender.RCS.layout=org.apache.log4j.PatternLayout
log4j.appender.RCS.layout.ConversionPattern=%d{yyyy-MM-dd hh:mm a} %5 %c{1}: Line#%L - %m%n
log4j.rootLogger=warn
#Define package specific logging
log4j.logger.MyService=debug, RCS

How to split a string with any whitespace chars as delimiters

Study this code.. good luck

    import java.util.*;
class Demo{
    public static void main(String args[]){
        Scanner input = new Scanner(System.in);
        System.out.print("Input String : ");
        String s1 = input.nextLine();   
        String[] tokens = s1.split("[\\s\\xA0]+");      
        System.out.println(tokens.length);      
        for(String s : tokens){
            System.out.println(s);

        } 
    }
}

Java, looping through result set

List<String> sids = new ArrayList<String>();
List<String> lids = new ArrayList<String>();

String query = "SELECT rlink_id, COUNT(*)"
             + "FROM dbo.Locate  "
             + "GROUP BY rlink_id ";

Statement stmt = yourconnection.createStatement();
try {
    ResultSet rs4 = stmt.executeQuery(query);

    while (rs4.next()) {
        sids.add(rs4.getString(1));
        lids.add(rs4.getString(2));
    }
} finally {
    stmt.close();
}

String show[] = sids.toArray(sids.size());
String actuate[] = lids.toArray(lids.size());

Postgresql, update if row with some unique value exists, else insert

If INSERTS are rare, I would avoid doing a NOT EXISTS (...) since it emits a SELECT on all updates. Instead, take a look at wildpeaks answer: https://dba.stackexchange.com/questions/5815/how-can-i-insert-if-key-not-exist-with-postgresql

CREATE OR REPLACE FUNCTION upsert_tableName(arg1 type, arg2 type) RETURNS VOID AS $$ 
    DECLARE 
    BEGIN 
        UPDATE tableName SET col1 = value WHERE colX = arg1 and colY = arg2; 
        IF NOT FOUND THEN 
        INSERT INTO tableName values (value, arg1, arg2); 
        END IF; 
    END; 
    $$ LANGUAGE 'plpgsql'; 

This way Postgres will initially try to do a UPDATE. If no rows was affected, it will fall back to emitting an INSERT.

Can't import javax.servlet.annotation.WebServlet

Copy servlet-api.jar from your tomcat server lib folder.

enter image description here

Paste it to WEB-INF > lib folder

enter image description here

Error was solved!!!

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

Display Last Saved Date on worksheet

May be this time stamp fit you better Code

Function LastInputTimeStamp() As Date
  LastInputTimeStamp = Now()
End Function

and each time you input data in defined cell (in my example below it is cell C36) you'll get a new constant time stamp. As an example in Excel file may use this

=IF(C36>0,LastInputTimeStamp(),"")

Merging two images with PHP

The GD Image Manipulation Library in PHP is probably the best for working with images in PHP. Try one of the imagecopy functions (imagecopy, imagecopymerge, ...). Each of them combine 2 images in different ways. See the php documentation on imagecopy for more information.

Python integer incrementing with ++

Here there is an explanation: http://bytes.com/topic/python/answers/444733-why-there-no-post-pre-increment-operator-python

However the absence of this operator is in the python philosophy increases consistency and avoids implicitness.

In addition, this kind of increments are not widely used in python code because python have a strong implementation of the iterator pattern plus the function enumerate.

Reading/Writing a MS Word file in PHP

Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.

You could use the Microsoft Office XML formats for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need.

The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to OpenXML. As databyss pointed out here the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on MSDN regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest.

Perhaps you can have a look at PHPExcel which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.

ImportError: No module named request

The SpeechRecognition library requires Python 3.3 or up:

Requirements

[...]

The first software requirement is Python 3.3 or better. This is required to use the library.

and from the Trove classifiers:

Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4

The urllib.request module is part of the Python 3 standard library; in Python 2 you'd use urllib2 here.

How do I change TextView Value inside Java Code?

First, add a textView in the XML file

<TextView  
    android:id="@+id/rate_id"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/what_U_want_to_display_in_first_time"
    />

then add a button in xml file with id btn_change_textView and write this two line of code in onCreate() method of activity

Button btn= (Button) findViewById(R.id. btn_change_textView);
TextView textView=(TextView)findViewById(R.id.rate_id);

then use clickListener() on button object like this

btn.setOnClickListener(new View.OnClickListener {
    public void onClick(View v) {
      
        textView.setText("write here what u want to display after button click in string");
    }
});

java.lang.UnsupportedClassVersionError

This class was compiled with a JDK more recent than the one used for execution.

The easiest is to install a more recent JRE on the computer where you execute the program. If you think you installed a recent one, check the JAVA_HOME and PATH environment variables.

Version 49 is java 1.5. That means the class was compiled with (or for) a JDK which is yet old. You probably tried to execute the class with JDK 1.4. You really should use one more recent (1.6 or 1.7, see java version history).

Why is the time complexity of both DFS and BFS O( V + E )

DFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or BACK
  • Method incidentEdges is called once for each vertex
  • DFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

BFS(analysis):

  • Setting/getting a vertex/edge label takes O(1) time
  • Each vertex is labeled twice
    • once as UNEXPLORED
    • once as VISITED
  • Each edge is labeled twice
    • once as UNEXPLORED
    • once as DISCOVERY or CROSS
  • Each vertex is inserted once into a sequence Li
  • Method incidentEdges is called once for each vertex
  • BFS runs in O(n + m) time provided the graph is represented by the adjacency list structure
  • Recall that Sv deg(v) = 2m

In angular $http service, How can I catch the "status" of error?

Your arguments are incorrect, error doesn't return an object containing status and message, it passed them as separate parameters in the order described below.

Taken from the angular docs:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

So you'd need to change your code to:

$http.get(dataUrl)
    .success(function (data){
        $scope.data.products = data;
    })
    .error(function (error, status){
        $scope.data.error = { message: error, status: status};
        console.log($scope.data.error.status); 
  }); 

Obviously, you don't have to create an object representing the error, you could just create separate scope properties but the same principle applies.

Remove columns from dataframe where ALL values are NA

df[sapply(df, function(x) all(is.na(x)))] <- NULL

Android selector & text color

If using TextViews in tabs this selector definition worked for me (tried Klaus Balduino's but it did not):

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

  <!--  Active tab -->
  <item
    android:state_selected="true"
    android:state_focused="false"
    android:state_pressed="false"
    android:color="#000000" />

  <!--  Inactive tab -->
  <item
    android:state_selected="false"
    android:state_focused="false"
    android:state_pressed="false"
    android:color="#FFFFFF" />

</selector>

Adding ID's to google map markers

Why not use an cache that stores each marker object and references an ID?

var markerCache= {};
var idGen= 0;

function codeAddress(addr, contentStr){
    // create marker
    // store
    markerCache[idGen++]= marker;
}

Edit: of course this relies on a numeric index system that doesn't offer a length property like an array. You could of course prototype the Object object and create a length, etc for just such a thing. OTOH, generating a unique ID value (MD5, etc) of each address might be the way to go.

Determine project root from a running node.js application

Old question, I know, however no question mention to use progress.argv. The argv array includes a full pathname and filename (with or without .js extension) that was used as parameter to be executed by node. Because this also can contain flags, you must filter this.

This is not an example you can directly use (because of using my own framework) but I think it gives you some idea how to do it. I also use a cache method to avoid that calling this function stress the system too much, especially when no extension is specified (and a file exist check is required), for example:

node myfile

or

node myfile.js

That's the reason I cache it, see also code below.


function getRootFilePath()
{
        if( !isDefined( oData.SU_ROOT_FILE_PATH ) )
        {
            var sExt = false;

            each( process.argv, function( i, v )
            {
                 // Skip invalid and provided command line options
                if( !!v && isValidString( v ) && v[0] !== '-' )
                {
                    sExt = getFileExt( v );

                    if( ( sExt === 'js' ) || ( sExt === '' && fileExists( v+'.js' )) )
                    {

                        var a = uniformPath( v ).split("/"); 

                         // Chop off last string, filename
                        a[a.length-1]='';

                         // Cache it so we don't have to do it again.
                        oData.SU_ROOT_FILE_PATH=a.join("/"); 

                         // Found, skip loop
                        return true;
                    }
                }
            }, true ); // <-- true is: each in reverse order
        }

        return oData.SU_ROOT_FILE_PATH || '';
    }
}; 

Android : Capturing HTTP Requests with non-rooted android device

Set a https://mitmproxy.org/ as proxy on a same LAN

  • Open Source
  • Built in python 3
  • Installable via pip

What is the difference between a database and a data warehouse?

DataBase :- OLTP(online transaction process)

  • It is current data, up-to-date detailed data, flat relational isolated data.
  • Entity relationship is used to design the database
  • DB size 100MB-GB simple transaction or quires

Datawarehouse

  • OLAP(Online Analytical process)
  • It is about Historical data Star schema,snow flexed schema and galaxy
  • schema is used to design the data warehouse
  • DB size 100GB-TB Improved query performance foundation for DATA MINING DATA VISUALIZATION
  • Enables users to gain a deeper understanding and knowledge about various aspects of their corporate data through fast, consistent, interactive access to a wide variety of possible views of the data

Hide Signs that Meteor.js was Used

The amount of hacks you would need to go through to completely hide the fact your site is built by Meteor.js is absolutely ridiculous. You would have to strip essentially all core functionality and just serve straight up html, completely defeating the purpose of using the framework anyway.

That being said, I suggest looking at buildwith.com

You enter a url, and it reveals a ton of information about a site. If you only need to "fool" engines like this, there may be simple solutions.

.do extension in web pages?

Using apache's rewrite_module can change your script extensions. Give this thread a good read.

Create a string with n characters

Just replace your StringBuffer with a StringBuilder. Hard to beat that.

If your length is a big number, you might implement some more efficient (but more clumsy) self-appendding, duplicating the length in each iteration:

 public static String dummyString(char c, int len) {
  if( len < 1 ) return "";
  StringBuilder sb = new StringBuilder(len).append(c);
  int remnant = len - sb.length();
  while(remnant  > 0) {
   if( remnant  >= sb.length() ) sb.append(sb);
   else sb.append(sb.subSequence(0, remnant));
   remnant  = len - sb.length();
  }
  return sb.toString();
 }

Also, you might try the Arrays.fill() aproach (FrustratedWithFormsDesigner's answer).

Clicking a checkbox with ng-click does not update the model

I just replaced ng-model with ng-checked and it worked for me.

This issue was when I updated my angular version from 1.2.28 to 1.4.9

Also check if your ng-change is causing any issue here. I had to remove my ng-change as-well to make it working.

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

In my case of picking date from JXDatePicker (java calender) and getting it stored in database as SQL Date type, below works fine ..

java.sql.Date date = new java.sql.Date(pickedDate.getDate().getTime());

where pickedDate is object of JXDatePicker

Difference between <span> and <div> with text-align:center;?

the difference is not between <span> and <div> specifically, but between inline and block elements. <span> defaults to being display:inline; whereas <div> defaults to being display:block;. But these can be overridden in CSS.

The difference in the way text-align:center works between the two is down to the width.

A block element defaults to being the width of its container. It can have its width set using CSS, but either way it is a fixed width.

An inline element takes its width from the size of its content text.

text-align:center tells the text to position itself centrally in the element. But in an inline element, this is clearly not going to have any effect because the element is the same width as the text; aligning it one way or the other is meaningless.

In a block element, because the element's width is independent of the content, the content can be positioned within the element using the text-align style.

Finally, a solution for you:

There is an additional value for the display property which provides a half-way house between block and inline. Conveniently enough, it's called inline-block. If you specify a <span> to be display:inline-block; in the CSS, it will continue to work as an inline element but will take on some of the properties of a block as well, such as the ability to specify a width. Once you specify a width for it, you will be able to center the text within that width using text-align:center;

Hope that helps.

Multiprocessing vs Threading Python

MULTIPROCESSING

  • Multiprocessing adds CPUs to increase computing power.
  • Multiple processes are executed concurrently.
  • Creation of a process is time-consuming and resource intensive.
  • Multiprocessing can be symmetric or asymmetric.
  • The multiprocessing library in Python uses separate memory space, multiple CPU cores, bypasses GIL limitations in CPython, child processes are killable (ex. function calls in program) and is much easier to use.
  • Some caveats of the module are a larger memory footprint and IPC’s a little more complicated with more overhead.

MULTITHREADING

  • Multithreading creates multiple threads of a single process to increase computing power.
  • Multiple threads of a single process are executed concurrently.
  • Creation of a thread is economical in both sense time and resource.
  • The multithreading library is lightweight, shares memory, responsible for responsive UI and is used well for I/O bound applications.
  • The module isn’t killable and is subject to the GIL.
  • Multiple threads live in the same process in the same space, each thread will do a specific task, have its own code, own stack memory, instruction pointer, and share heap memory.
  • If a thread has a memory leak it can damage the other threads and parent process.

Example of Multi-threading and Multiprocessing using Python

Python 3 has the facility of Launching parallel tasks. This makes our work easier.

It has for thread pooling and Process pooling.

The following gives an insight:

ThreadPoolExecutor Example

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

ProcessPoolExecutor

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ProcessPoolExecutor() as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

Insert string at specified position

function insSubstr($str, $sub, $posStart, $posEnd){
  return mb_substr($str, 0, $posStart) . $sub . mb_substr($str, $posEnd + 1);
}

How do I use the built in password reset/change views with my own templates

You just need to wrap the existing functions and pass in the template you want. For example:

from django.contrib.auth.views import password_reset

def my_password_reset(request, template_name='path/to/my/template'):
    return password_reset(request, template_name)

To see this just have a look at the function declartion of the built in views:

http://code.djangoproject.com/browser/django/trunk/django/contrib/auth/views.py#L74

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

Well that is Because of

you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception. and the one way is to encrypt that data Directly into the String.

look this. Try and u will be able to resolve this

public static String decrypt(String encryptedData) throws Exception {

    Key key = generateKey();
    Cipher c = Cipher.getInstance(ALGO);
    c.init(Cipher.DECRYPT_MODE, key);
    String decordedValue = new BASE64Decoder().decodeBuffer(encryptedData).toString().trim();
    System.out.println("This is Data to be Decrypted" + decordedValue);
    return decordedValue;
}

hope that will help.

How to load npm modules in AWS Lambda?

npm module has to be bundeled inside your nodejs package and upload to AWS Lambda Layers as zip, then you would need to refer to your module/js as below and use available methods from it. const mymodule = require('/opt/nodejs/MyLogger');

Python POST binary data

This has nothing to do with a malformed upload. The HTTP error clearly specifies 401 unauthorized, and tells you the CSRF token is invalid. Try sending a valid CSRF token with the upload.

More about csrf tokens here:

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

How can I remove non-ASCII characters but leave periods and spaces using Python?

An easy way to change to a different codec, is by using encode() or decode(). In your case, you want to convert to ASCII and ignore all symbols that are not supported. For example, the Swedish letter å is not an ASCII character:

    >>>s = u'Good bye in Swedish is Hej d\xe5'
    >>>s = s.encode('ascii',errors='ignore')
    >>>print s
    Good bye in Swedish is Hej d

Edit:

Python3: str -> bytes -> str

>>>"Hej då".encode("ascii", errors="ignore").decode()
'hej d'

Python2: unicode -> str -> unicode

>>> u"hej då".encode("ascii", errors="ignore").decode()
u'hej d'

Python2: str -> unicode -> str (decode and encode in reverse order)

>>> "hej d\xe5".decode("ascii", errors="ignore").encode()
'hej d'

get the titles of all open windows

Here’s some code you can use to get a list of all the open windows. Actually, you get a dictionary where each item is a KeyValuePair where the key is the handle (hWnd) of the window and the value is its title. It also finds pop-up windows, such as those created by MessageBox.Show.

using System.Runtime.InteropServices;
using HWND = System.IntPtr;

/// <summary>Contains functionality to get all the open windows.</summary>
public static class OpenWindowGetter
{
  /// <summary>Returns a dictionary that contains the handle and title of all the open windows.</summary>
  /// <returns>A dictionary that contains the handle and title of all the open windows.</returns>
  public static IDictionary<HWND, string> GetOpenWindows()
  {
    HWND shellWindow = GetShellWindow();
    Dictionary<HWND, string> windows = new Dictionary<HWND, string>();

    EnumWindows(delegate(HWND hWnd, int lParam)
    {
      if (hWnd == shellWindow) return true;
      if (!IsWindowVisible(hWnd)) return true;

      int length = GetWindowTextLength(hWnd);
      if (length == 0) return true;

      StringBuilder builder = new StringBuilder(length);
      GetWindowText(hWnd, builder, length + 1);

      windows[hWnd] = builder.ToString();
      return true;

    }, 0);

    return windows;
  }

  private delegate bool EnumWindowsProc(HWND hWnd, int lParam);

  [DllImport("USER32.DLL")]
  private static extern bool EnumWindows(EnumWindowsProc enumFunc, int lParam);

  [DllImport("USER32.DLL")]
  private static extern int GetWindowText(HWND hWnd, StringBuilder lpString, int nMaxCount);

  [DllImport("USER32.DLL")]
  private static extern int GetWindowTextLength(HWND hWnd);

  [DllImport("USER32.DLL")]
  private static extern bool IsWindowVisible(HWND hWnd);

  [DllImport("USER32.DLL")]
  private static extern IntPtr GetShellWindow();
}

And here’s some code that uses it:

foreach(KeyValuePair<IntPtr, string> window in OpenWindowGetter.GetOpenWindows())
{
  IntPtr handle = window.Key;
  string title = window.Value;

  Console.WriteLine("{0}: {1}", handle, title);
}

Credit: http://www.tcx.be/blog/2006/list-open-windows/

VB.NET - Remove a characters from a String

The String class has a Replace method that will do that.

Dim clean as String
clean = myString.Replace(",", "")

Editing specific line in text file in Python

#read file lines and edit specific item

file=open("pythonmydemo.txt",'r')
a=file.readlines()
print(a[0][6:11])

a[0]=a[0][0:5]+' Ericsson\n'
print(a[0])

file=open("pythonmydemo.txt",'w')
file.writelines(a)
file.close()
print(a)

I want to calculate the distance between two points in Java

Unlike maths-on-paper notation, most programming languages (Java included) need a * sign to do multiplication. Your distance calculation should therefore read:

distance = Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2));

Or alternatively:

distance = Math.sqrt(Math.pow((x1-x2), 2) + Math.pow((y1-y2), 2));

sudo echo "something" >> /etc/privilegedFile doesn't work

Can you change the ownership of the file then change it back after using cat >> to append?

sudo chown youruser /etc/hosts  
sudo cat /downloaded/hostsadditions >> /etc/hosts  
sudo chown root /etc/hosts  

Something like this work for you?

Can I exclude some concrete urls from <url-pattern> inside <filter-mapping>?

I have encounterd the same issue, but I find a anwser showing below.

web.xml

 <!-- set this param value for the filter-->
    <init-param>
            <param-name>freePages</param-name>
            <param-value>
            MainFrame.jsp;
            </param-value>
    </init-param>

filter.java

strFreePages = config.getInitParameter("freePages"); //get the exclue pattern from config file
isFreePage(strRequestPage)  //decide the exclude path

this way you don't have to harass the concrete Filter class.

How do I determine height and scrolling position of window in jQuery?

If you need to scroll to a point of an element. You can use Jquery function to scroll it up/down.

$('html, body').animate({
                scrollTop: $("#div1").offset().top
            }, 'slow');

How to format numbers as currency string?

Here are some solutions, all pass the test suite, test suite and benchmark included, if you want copy and paste to test, try This Gist.

Method 0 (RegExp)

Base on https://stackoverflow.com/a/14428340/1877620, but fix if there is no decimal point.

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');
        a[0] = a[0].replace(/\d(?=(\d{3})+$)/g, '$&,');
        return a.join('.');
    }
}

Method 1

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.'),
            // skip the '-' sign
            head = Number(this < 0);

        // skip the digits that's before the first thousands separator 
        head += (a[0].length - head) % 3 || 3;

        a[0] = a[0].slice(0, head) + a[0].slice(head).replace(/\d{3}/g, ',$&');
        return a.join('.');
    };
}

Method 2 (Split to Array)

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('.');

        a[0] = a[0]
            .split('').reverse().join('')
            .replace(/\d{3}(?=\d)/g, '$&,')
            .split('').reverse().join('');

        return a.join('.');
    };
}

Method 3 (Loop)

if (typeof Number.prototype.format === 'undefined') {
    Number.prototype.format = function (precision) {
        if (!isFinite(this)) {
            return this.toString();
        }

        var a = this.toFixed(precision).split('');
        a.push('.');

        var i = a.indexOf('.') - 3;
        while (i > 0 && a[i-1] !== '-') {
            a.splice(i, 0, ',');
            i -= 3;
        }

        a.pop();
        return a.join('');
    };
}

Usage Example

console.log('======== Demo ========')
console.log(
    (1234567).format(0),
    (1234.56).format(2),
    (-1234.56).format(0)
);
var n = 0;
for (var i=1; i<20; i++) {
    n = (n * 10) + (i % 10)/100;
    console.log(n.format(2), (-n).format(2));
}

Separator

If we want custom thousands separator or decimal separator, use replace():

123456.78.format(2).replace(',', ' ').replace('.', ' ');

Test suite

function assertEqual(a, b) {
    if (a !== b) {
        throw a + ' !== ' + b;
    }
}

function test(format_function) {
    console.log(format_function);
    assertEqual('NaN', format_function.call(NaN, 0))
    assertEqual('Infinity', format_function.call(Infinity, 0))
    assertEqual('-Infinity', format_function.call(-Infinity, 0))

    assertEqual('0', format_function.call(0, 0))
    assertEqual('0.00', format_function.call(0, 2))
    assertEqual('1', format_function.call(1, 0))
    assertEqual('-1', format_function.call(-1, 0))
    // decimal padding
    assertEqual('1.00', format_function.call(1, 2))
    assertEqual('-1.00', format_function.call(-1, 2))
    // decimal rounding
    assertEqual('0.12', format_function.call(0.123456, 2))
    assertEqual('0.1235', format_function.call(0.123456, 4))
    assertEqual('-0.12', format_function.call(-0.123456, 2))
    assertEqual('-0.1235', format_function.call(-0.123456, 4))
    // thousands separator
    assertEqual('1,234', format_function.call(1234.123456, 0))
    assertEqual('12,345', format_function.call(12345.123456, 0))
    assertEqual('123,456', format_function.call(123456.123456, 0))
    assertEqual('1,234,567', format_function.call(1234567.123456, 0))
    assertEqual('12,345,678', format_function.call(12345678.123456, 0))
    assertEqual('123,456,789', format_function.call(123456789.123456, 0))
    assertEqual('-1,234', format_function.call(-1234.123456, 0))
    assertEqual('-12,345', format_function.call(-12345.123456, 0))
    assertEqual('-123,456', format_function.call(-123456.123456, 0))
    assertEqual('-1,234,567', format_function.call(-1234567.123456, 0))
    assertEqual('-12,345,678', format_function.call(-12345678.123456, 0))
    assertEqual('-123,456,789', format_function.call(-123456789.123456, 0))
    // thousands separator and decimal
    assertEqual('1,234.12', format_function.call(1234.123456, 2))
    assertEqual('12,345.12', format_function.call(12345.123456, 2))
    assertEqual('123,456.12', format_function.call(123456.123456, 2))
    assertEqual('1,234,567.12', format_function.call(1234567.123456, 2))
    assertEqual('12,345,678.12', format_function.call(12345678.123456, 2))
    assertEqual('123,456,789.12', format_function.call(123456789.123456, 2))
    assertEqual('-1,234.12', format_function.call(-1234.123456, 2))
    assertEqual('-12,345.12', format_function.call(-12345.123456, 2))
    assertEqual('-123,456.12', format_function.call(-123456.123456, 2))
    assertEqual('-1,234,567.12', format_function.call(-1234567.123456, 2))
    assertEqual('-12,345,678.12', format_function.call(-12345678.123456, 2))
    assertEqual('-123,456,789.12', format_function.call(-123456789.123456, 2))
}

console.log('======== Testing ========');
test(Number.prototype.format);
test(Number.prototype.format1);
test(Number.prototype.format2);
test(Number.prototype.format3);

Benchmark

function benchmark(f) {
    var start = new Date().getTime();
    f();
    return new Date().getTime() - start;
}

function benchmark_format(f) {
    console.log(f);
    time = benchmark(function () {
        for (var i = 0; i < 100000; i++) {
            f.call(123456789, 0);
            f.call(123456789, 2);
        }
    });
    console.log(time.format(0) + 'ms');
}

// if not using async, browser will stop responding while running.
// this will create a new thread to benchmark
async = [];
function next() {
    setTimeout(function () {
        f = async.shift();
        f && f();
        next();
    }, 10);
}

console.log('======== Benchmark ========');
async.push(function () { benchmark_format(Number.prototype.format); });
next();

How can I clear event subscriptions in C#?

The best practice to clear all subscribers is to set the someEvent to null by adding another public method if you want to expose this functionality to outside. This has no unseen consequences. The precondition is to remember to declare SomeEvent with the keyword 'event'.

Please see the book - C# 4.0 in the nutshell, page 125.

Some one here proposed to use Delegate.RemoveAll method. If you use it, the sample code could follow the below form. But it is really stupid. Why not just SomeEvent=null inside the ClearSubscribers() function?

public void ClearSubscribers ()
{
   SomeEvent = (EventHandler) Delegate.RemoveAll(SomeEvent, SomeEvent);
   // Then you will find SomeEvent is set to null.
}

Append text to file from command line without using io redirection

You can use Vim in Ex mode:

ex -sc 'a|BRAVO' -cx file
  1. a append text

  2. x save and close

Save and load weights in keras

Since this question is quite old, but still comes up in google searches, I thought it would be good to point out the newer (and recommended) way to save Keras models. Instead of saving them using the older h5 format like has been shown before, it is now advised to use the SavedModel format, which is actually a dictionary that contains both the model configuration and the weights.

More information can be found here: https://www.tensorflow.org/guide/keras/save_and_serialize

The snippets to save & load can be found below:

model.fit(test_input, test_target)
# Calling save('my_model') creates a SavedModel folder 'my_model'.
model.save('my_model')

# It can be used to reconstruct the model identically.
reconstructed_model = keras.models.load_model('my_model')

A sample output of this :

enter image description here

How can I print a circular structure in a JSON-like format?

To update the answer of overriding the way JSON works (probably not recommended, but super simple), don't use circular-json (it's deprecated). Instead, use the successor, flatted:

https://www.npmjs.com/package/flatted

Borrowed from the old answer above from @user1541685 , but replaced with the new one:

npm i --save flatted

then in your js file

const CircularJSON = require('flatted');
const json = CircularJSON.stringify(obj);

How to show the "Are you sure you want to navigate away from this page?" when changes committed?

This is an easy way to present the message if any data is input into the form, and not to show the message if the form is submitted:

$(function () {
    $("input, textarea, select").on("input change", function() {
        window.onbeforeunload = window.onbeforeunload || function (e) {
            return "You have unsaved changes.  Do you want to leave this page and lose your changes?";
        };
    });
    $("form").on("submit", function() {
        window.onbeforeunload = null;
    });
})

Resolving require paths with webpack

I didn't get why anybody suggested to include myDir's parent directory into modulesDirectories in webpack, that should make the trick easily:

resolve: {
    modulesDirectories: [
      'parentDir',
      'node_modules',
    ],
    extensions: ['', '.js', '.jsx']
  },

C# Clear Session

The other big difference is Abandon does not remove items immediately, but when it does then cleanup it does a loop over session items to check for STA COM objects it needs to handle specially. And this can be a problem.

Under high load it's possible for two (or more) requests to make it to the server for the same session (that is two requests with the same session cookie). Their execution will be serialized, but since Abandon doesn't clear out the items synchronously but rather sets a flag it's possible for both requests to run, and both requests to schedule a work item to clear out session "later". Both these work items can then run at the same time, and both are checking the session objects, and both are clearing out the array of objects, and what happens when you have two things iterating over a list and changing it?? Boom! And since this happens in a queueuserworkitem callback and is NOT done in a try/catch (thanks MS), it will bring down your entire app domain. Been there.

How to check the input is an integer or not in Java?

If you are getting the user input with Scanner, you can do:

if(yourScanner.hasNextInt()) {
    yourNumber = yourScanner.nextInt();
}

If you are not, you'll have to convert it to int and catch a NumberFormatException:

try{
    yourNumber = Integer.parseInt(yourInput);
}catch (NumberFormatException ex) {
    //handle exception here
}

Chosen Jquery Plugin - getting selected values

$("#select-id").chosen().val()

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

You can check the currently running transactions with

SELECT * FROM `information_schema`.`innodb_trx` ORDER BY `trx_started`

Your transaction should be one of the first, because it's the oldest in the list. Now just take the value from trx_mysql_thread_id and send it the KILL command:

KILL 1234;

If you're unsure which transaction is yours, repeat the first query very often and see which transactions persist.

ExpressJS - throw er Unhandled error event

Reason for this error

Some other process is already running on the port you have specified

Simple and Quick solution

On Linux OS, For example you have specified 3000 as the port

  • Open the terminal and run lsof -i :3000. If any process is already running on port 3000 then you will see this printing on the console

_x000D_
_x000D_
COMMAND   PID  USER   FD   TYPE DEVICE SIZE/OFF NODE NAME_x000D_
node    16615 aegon   13u  IPv6 183768      0t0  TCP *:3000 (LISTEN)
_x000D_
_x000D_
_x000D_

  • Copy the PID (process ID) from the output

  • Run sudo kill -9 16615 (you have to put PID after -9)

  • Start the server again

How to make the Facebook Like Box responsive?

NOTE: Colin's solution didn't work for me. Facebook may have changed their markup. Using * should be more future-proof.

Wrap the Like box with a div:

<div id="likebox-wrapper">
    <iframe src="..."></iframe> <!-- likebox code -->
</div>

and add this to your css file:

#likebox-wrapper * {
   width: 100% !important;
}

Save Dataframe to csv directly to s3 Python

You can directly use the S3 path. I am using Pandas 0.24.1

In [1]: import pandas as pd

In [2]: df = pd.DataFrame( [ [1, 1, 1], [2, 2, 2] ], columns=['a', 'b', 'c'])

In [3]: df
Out[3]:
   a  b  c
0  1  1  1
1  2  2  2

In [4]: df.to_csv('s3://experimental/playground/temp_csv/dummy.csv', index=False)

In [5]: pd.__version__
Out[5]: '0.24.1'

In [6]: new_df = pd.read_csv('s3://experimental/playground/temp_csv/dummy.csv')

In [7]: new_df
Out[7]:
   a  b  c
0  1  1  1
1  2  2  2

Release Note:

S3 File Handling

pandas now uses s3fs for handling S3 connections. This shouldn’t break any code. However, since s3fs is not a required dependency, you will need to install it separately, like boto in prior versions of pandas. GH11915.

.htaccess: where is located when not in www base dir

. (dot) files are hidden by default on Unix/Linux systems. Most likely, if you know they are .htaccess files, then they are probably in the root folder for the website.

If you are using a command line (terminal) to access, then they will only show up if you use:

ls -a

If you are using a GUI application, look for a setting to "show hidden files" or something similar.

If you still have no luck, and you are on a terminal, you can execute these commands to search the whole system (may take some time):

cd /
find . -name ".htaccess"

This will list out any files it finds with that name.