Programs & Examples On #Clientaccesspolicy.xml

clientaccesspolicy.xml file enables cross-domain access in Silverlight

Java time-based map/cache with expiring keys

Apache Commons has decorator for Map to expire entries: PassiveExpiringMap It's more simple than caches from Guava.

P.S. be careful, it's not synchronized.

error: ‘NULL’ was not declared in this scope

NULL can also be found in:

#include <string.h>

String.h will pull in the NULL from somewhere else.

Eclipse reported "Failed to load JNI shared library"

First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).

Second, the -vm argument in eclipse.ini should point to the java executable. See http://wiki.eclipse.org/Eclipse.ini for examples.

If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?

Async always WaitingForActivation

The reason is your result assigned to the returning Task which represents continuation of your method, and you have a different Task in your method which is running, if you directly assign Task like this you will get your expected results:

var task = Task.Run(() =>
        {
            for (int i = 10; i < 432543543; i++)
            {
                // just for a long job
                double d3 = Math.Sqrt((Math.Pow(i, 5) - Math.Pow(i, 2)) / Math.Sin(i * 8));
            }
           return "Foo Completed.";

        });

        while (task.Status != TaskStatus.RanToCompletion)
        {
            Console.WriteLine("Thread ID: {0}, Status: {1}", Thread.CurrentThread.ManagedThreadId,task.Status);

        }

        Console.WriteLine("Result: {0}", task.Result);
        Console.WriteLine("Finished.");
        Console.ReadKey(true);

The output:

enter image description here

Consider this for better explanation: You have a Foo method,let's say it Task A, and you have a Task in it,let's say it Task B, Now the running task, is Task B, your Task A awaiting for Task B result.And you assing your result variable to your returning Task which is Task A, because Task B doesn't return a Task, it returns a string. Consider this:

If you define your result like this:

Task result = Foo(5);

You won't get any error.But if you define it like this:

string result = Foo(5);

You will get:

Cannot implicitly convert type 'System.Threading.Tasks.Task' to 'string'

But if you add an await keyword:

string result = await Foo(5);

Again you won't get any error.Because it will wait the result (string) and assign it to your result variable.So for the last thing consider this, if you add two task into your Foo Method:

private static async Task<string> Foo(int seconds)
{
    await Task.Run(() =>
        {
            for (int i = 0; i < seconds; i++)
            {
                Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
                Task.Delay(TimeSpan.FromSeconds(1)).Wait();
            }

            // in here don't return anything
        });

   return await Task.Run(() =>
        {
            for (int i = 0; i < seconds; i++)
            {
                Console.WriteLine("Thread ID: {0}, second {1}.", Thread.CurrentThread.ManagedThreadId, i);
                Task.Delay(TimeSpan.FromSeconds(1)).Wait();
            }

            return "Foo Completed.";
        });
}

And if you run the application, you will get the same results.(WaitingForActivation) Because now, your Task A is waiting those two tasks.

Difference between Math.Floor() and Math.Truncate()

Math.Floor(): Returns the largest integer less than or equal to the specified double-precision floating-point number.

Math.Round(): Rounds a value to the nearest integer or to the specified number of fractional digits.

What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript?

As others have said, it's a new syntax to create functions.

However, this kind of functions differ from normal ones:

  • They bind the this value. As explained by the spec,

    An ArrowFunction does not define local bindings for arguments, super, this, or new.target. Any reference to arguments, super, this, or new.target within an ArrowFunction must resolve to a binding in a lexically enclosing environment. Typically this will be the Function Environment of an immediately enclosing function.

    Even though an ArrowFunction may contain references to super, the function object created in step 4 is not made into a method by performing MakeMethod. An ArrowFunction that references super is always contained within a non-ArrowFunction and the necessary state to implement super is accessible via the scope that is captured by the function object of the ArrowFunction.

  • They are non-constructors.

    That means they have no [[Construct]] internal method, and thus can't be instantiated, e.g.

    var f = a => a;
    f(123);  // 123
    new f(); // TypeError: f is not a constructor
    

MySQL Update Inner Join tables query

Try this:

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

Update:

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

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

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

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

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

Left join only selected columns in R with the merge() function

You can do this by subsetting the data you pass into your merge:

merge(x = DF1, y = DF2[ , c("Client", "LO")], by = "Client", all.x=TRUE)

Or you can simply delete the column after your current merge :)

PHP array delete by value (not key)

Using array_search() and unset, try the following:

if (($key = array_search($del_val, $messages)) !== false) {
    unset($messages[$key]);
}

array_search() returns the key of the element it finds, which can be used to remove that element from the original array using unset(). It will return FALSE on failure, however it can return a false-y value on success (your key may be 0 for example), which is why the strict comparison !== operator is used.

The if() statement will check whether array_search() returned a value, and will only perform an action if it did.

What are good grep tools for Windows?

Update July 2013:

Another grep tool I now use all the time on Windows is AstroGrep:

AstroGrep awesomeness

Its ability to show me more than just the line search (i.e. the --context=NUM of a command-line grep) is invaluable.
And it is fast. Very fast, even on an old computer with non-SSD drive (I know, they used to do this hard drive with spinning disks, called platters, crazy right?)

It is free.
It is portable (simple zip archive to unzip).


Original answer October 2008

alt textGnu Grep is alright

You can download it for example here: (site ftp)

All the usual options are here.

That, combined with gawk and xargs (includes 'find', from GnuWin32), and you can really script like you were on Unix!

See also the options I am using to grep recursively:

grep --include "*.xxx" -nRHI "my Text to grep" *

How do you convert WSDLs to Java classes using Eclipse?

I wouldn't suggest using the Eclipse tool to generate the WS Client because I had bad experience with it:

I am not really sure if this matters but I had to consume a WS written in .NET. When I used the Eclipse's "New Web Service Client" tool it generated the Java classes using Axis (version 1.x) which as you can check is old (last version from 2006). There is a newer version though that is has some major changes but Eclipse doesn't use it.

Why the old version of Axis matters you'll say? Because when using OpenJDK you can run into some problems like missing cryptography algorithms in OpenJDK that are presented in the Oracle's JDK and some libraries like this one depend on them.

So I just used the wsimport tool and ended my headaches.

Simulating Key Press C#

Here's an example...

static class Program
{
    [DllImport("user32.dll")]
    public static extern int SetForegroundWindow(IntPtr hWnd);

    [STAThread]
    static void Main()
    {
        while(true)
        {
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)
            {
                SetForegroundWindow(proc.MainWindowHandle);
                SendKeys.SendWait("{F5}");
            }

            Thread.Sleep(5000);
        }
    }
}

a better one... less anoying...

static class Program
{
    const UInt32 WM_KEYDOWN = 0x0100;
    const int VK_F5 = 0x74;

    [DllImport("user32.dll")]
    static extern bool PostMessage(IntPtr hWnd, UInt32 Msg, int wParam, int lParam);

    [STAThread]
    static void Main()
    {
        while(true)
        {
            Process [] processes = Process.GetProcessesByName("iexplore");

            foreach(Process proc in processes)
                PostMessage(proc.MainWindowHandle, WM_KEYDOWN, VK_F5, 0);

            Thread.Sleep(5000);
        }
    }
}

Renaming columns in Pandas

Renaming columns in Pandas is an easy task.

df.rename(columns={'$a': 'a', '$b': 'b', '$c': 'c', '$d': 'd', '$e': 'e'}, inplace=True)

Table column sizing

Updated 2018

Make sure your table includes the table class. This is because Bootstrap 4 tables are "opt-in" so the table class must be intentionally added to the table.

http://codeply.com/go/zJLXypKZxL

Bootstrap 3.x also had some CSS to reset the table cells so that they don't float..

table td[class*=col-], table th[class*=col-] {
    position: static;
    display: table-cell;
    float: none;
}

I don't know why this isn't is Bootstrap 4 alpha, but it may be added back in the final release. Adding this CSS will help all columns to use the widths set in the thead..

Bootstrap 4 Alpha 2 Demo


UPDATE (as of Bootstrap 4.0.0)

Now that Bootstrap 4 is flexbox, the table cells will not assume the correct width when adding col-*. A workaround is to use the d-inline-block class on the table cells to prevent the default display:flex of columns.

Another option in BS4 is to use the sizing utils classes for width...

<thead>
     <tr>
           <th class="w-25">25</th>
           <th class="w-50">50</th>
           <th class="w-25">25</th>
     </tr>
</thead>

Bootstrap 4 Alpha 6 Demo

Lastly, you could use d-flex on the table rows (tr), and the col-* grid classes on the columns (th,td)...

<table class="table table-bordered">
        <thead>
            <tr class="d-flex">
                <th class="col-3">25%</th>
                <th class="col-3">25%</th>
                <th class="col-6">50%</th>
            </tr>
        </thead>
        <tbody>
            <tr class="d-flex">
                <td class="col-sm-3">..</td>
                <td class="col-sm-3">..</td>
                <td class="col-sm-6">..</td>
            </tr>
        </tbody>
    </table>

Bootstrap 4.0.0 (stable) Demo

Note: Changing the TR to display:flex can alter the borders

When to use static keyword before global variables?

static before a global variable means that this variable is not accessible from outside the compilation module where it is defined.

E.g. imagine that you want to access a variable in another module:

foo.c

int var; // a global variable that can be accessed from another module
// static int var; means that var is local to the module only.
...

bar.c

extern int var; // use the variable in foo.c
...

Now if you declare var to be static you can't access it from anywhere but the module where foo.c is compiled into.

Note, that a module is the current source file, plus all included files. i.e. you have to compile those files separately, then link them together.

How can I reduce the waiting (ttfb) time

I have met the same problem. My project is running on the local server. I checked my php code.

$db = mysqli_connect('localhost', 'root', 'root', 'smart');

I use localhost to connect to my local database. That maybe the cause of the problem which you're describing. You can modify your HOSTS file. Add the line

127.0.0.1 localhost.

How to duplicate a whole line in Vim?

You can also try <C-x><C-l> which will repeat the last line from insert mode and brings you a completion window with all of the lines. It works almost like <C-p>

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

Also, see the Stack Overflow question How to detect what .NET Framework versions and service packs are installed? which also mentions:

There is an official Microsoft answer to this question at the knowledge base article [How to determine which versions and service pack levels of the Microsoft .NET Framework are installed][2]

Article ID: 318785 - Last Review: November 7, 2008 - Revision: 20.1 How to determine which versions of the .NET Framework are installed and whether service packs have been applied.

Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... Why would the official Microsoft answer be so misinformed?

matching query does not exist Error in Django

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return UniversityDetails.objects.get(email__exact=email)
    except UniversityDetails.DoesNotExist:
        return False

I want to remove double quotes from a String

If you have control over your data and you know your double quotes surround the string (so do not appear inside string) and the string is an integer ... say with :

"20151212211647278"

or similar this nicely removes the surrounding quotes

JSON.parse("20151212211647278");

Not a universal answer however slick for niche needs

How to convert a String to Bytearray

Since I cannot comment on the answer, I'd build on Jin Izzraeel's answer

var myBuffer = [];
var str = 'Stack Overflow';
var buffer = new Buffer(str, 'utf16le');
for (var i = 0; i < buffer.length; i++) {
    myBuffer.push(buffer[i]);
}

console.log(myBuffer);

by saying that you could use this if you want to use a Node.js buffer in your browser.

https://github.com/feross/buffer

Therefore, Tom Stickel's objection is not valid, and the answer is indeed a valid answer.

Update query PHP MySQL

you must write single quotes then double quotes then dot before name of field and after like that

mysql_query("UPDATE blogEntry SET content ='".$udcontent."', title = '".$udtitle."' WHERE id = '".$id."' ");

jQuery checkbox check/uncheck

Use prop() instead of attr() to set the value of checked. Also use :checkbox in find method instead of input and be specific.

Live Demo

$("#news_list tr").click(function() {
    var ele = $(this).find('input');
    if(ele.is(':checked')){
        ele.prop('checked', false);
        $(this).removeClass('admin_checked');
    }else{
        ele.prop('checked', true);
        $(this).addClass('admin_checked');
    }
});

Use prop instead of attr for properties like checked

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

I just got this error running kadence the installed "kadence" script checks for nodejs first and only runs node if there is no nodejs. I have the latest version of node linked into my ~/bin directory but nodejs runs an older version that I had forgotten to uninstall but never caused problems until just now.

So people with this problem might check if node and nodejs actually run the same version of node...

Set colspan dynamically with jquery

You'd need to remove the blank table cell element entirely, and change the colspan attribute on another cell in the row to encompass the released space, e.g.:

refToCellToRemove.remove();
refTocellToExpand.colspan = 4;

Note that setting it via setAttribute (which would otherwise be correct) will not work properly on IE.

Beware: IE does some very strange table layout things when you muck about with colspans dynamically. If you can avoid it, I would.

Sorting a tab delimited file

Lars Haugseth answer only worked from the command line for me where it gives this error if executed from a shell script:

sort: multi-character tab ‘$\t’

The solution if it's coded in a shell script if anyone's looking is

sort -t'    '

the tab character is in between the quote.

What are the true benefits of ExpandoObject?

It's example from great MSDN article about using ExpandoObject for creating dynamic ad-hoc types for incoming structured data (i.e XML, Json).

We can also assign delegate to ExpandoObject's dynamic property:

dynamic person = new ExpandoObject();
person.FirstName = "Dino";
person.LastName = "Esposito";

person.GetFullName = (Func<String>)(() => { 
  return String.Format("{0}, {1}", 
    person.LastName, person.FirstName); 
});

var name = person.GetFullName();
Console.WriteLine(name);

Thus it allows us to inject some logic into dynamic object at runtime. Therefore, together with lambda expressions, closures, dynamic keyword and DynamicObject class, we can introduce some elements of functional programming into our C# code, which we knows from dynamic languages as like JavaScript or PHP.

Integration Testing POSTing an entire object to Spring MVC controller

I ran into the same issue a while ago and did solve it by using reflection with some help from Jackson.

First populate a map with all the fields on an Object. Then add those map entries as parameters to the MockHttpServletRequestBuilder.

In this way you can use any Object and you are passing it as request parameters. I'm sure there are other solutions out there but this one worked for us:

    @Test
    public void testFormEdit() throws Exception {
        getMockMvc()
                .perform(
                        addFormParameters(post(servletPath + tableRootUrl + "/" + POST_FORM_EDIT_URL).servletPath(servletPath)
                                .param("entityID", entityId), validEntity)).andDo(print()).andExpect(status().isOk())
                .andExpect(content().contentType(MediaType.APPLICATION_JSON)).andExpect(content().string(equalTo(entityId)));
    }

    private MockHttpServletRequestBuilder addFormParameters(MockHttpServletRequestBuilder builder, Object object)
            throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

        SimpleDateFormat dateFormat = new SimpleDateFormat(applicationSettings.getApplicationDateFormat());

        Map<String, ?> propertyValues = getPropertyValues(object, dateFormat);

        for (Entry<String, ?> entry : propertyValues.entrySet()) {
            builder.param(entry.getKey(),
                    Util.prepareDisplayValue(entry.getValue(), applicationSettings.getApplicationDateFormat()));
        }

        return builder;
    }

    private Map<String, ?> getPropertyValues(Object object, DateFormat dateFormat) {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setDateFormat(dateFormat);
        mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        mapper.registerModule(new JodaModule());

        TypeReference<HashMap<String, ?>> typeRef = new TypeReference<HashMap<String, ?>>() {};

        Map<String, ?> returnValues = mapper.convertValue(object, typeRef);

        return returnValues;

    }

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes

So

__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

Session variables not working php

I encountered this issue today. the issue has to do with the $config['base_url'] . I noticed htpp://www.domain.com and http://example.com was the issue. to fix , always set your base_url to http://www.example.com

Difference between Return and Break statements

Break statement will break the whole loop and execute the code after loop and Return will not execute the code after that return statement and execute the loop with next increment.

Break

for(int i=0;i<5;i++){
    print(i)
    if(i==2)
    {
      break;
    }
}

output: 0 1

return

for(int i=0;i<5;i++)
{
   print(i)
   if(i==2)
   {
    return;
   }
}

output: 0 1 3 4

ORA-00904: invalid identifier

I was passing the values without the quotes. Once I passed the conditions inside the single quotes worked like a charm.

Select * from emp_table where emp_id=123;

instead of the above use this:

Select * from emp_table where emp_id='123';

Is there a good reason I see VARCHAR(255) used so often (as opposed to another length)?

Note: I found this question (varchar(255) v tinyblob v tinytext), which says that VARCHAR(n) requires n+1 bytes of storage for n<=255, n+2 bytes of storage for n>255. Is this the only reason? That seems kind of arbitrary, since you would only be saving two bytes compared to VARCHAR(256), and you could just as easily save another two bytes by declaring it VARCHAR(253).

No. you don't save two bytes by declaring 253. The implementation of the varchar is most likely a length counter and a variable length, nonterminated array. This means that if you store "hello" in a varchar(255) you will occupy 6 bytes: one byte for the length (the number 5) and 5 bytes for the five letters.

Is there a method that tells my program to quit?

One way is to do:

sys.exit(0)

You will have to import sys of course.

Another way is to break out of your infinite loop. For example, you could do this:

while True:
    choice = get_input()
    if choice == "a":
        # do something
    elif choice == "q":
        break

Yet another way is to put your main loop in a function, and use return:

def run():
    while True:
        choice = get_input()
        if choice == "a":
            # do something
        elif choice == "q":
            return

if __name__ == "__main__":
    run()

The only reason you need the run() function when using return is that (unlike some other languages) you can't directly return from the main part of your Python code (the part that's not inside a function).

How to make a JSONP request from Javascript without JQuery?

/**
 * Get JSONP data for cross-domain AJAX requests
 * @private
 * @link http://cameronspear.com/blog/exactly-what-is-jsonp/
 * @param  {String} url      The URL of the JSON request
 * @param  {String} callback The name of the callback to run on load
 */
var loadJSONP = function ( url, callback ) {

    // Create script with url and callback (if specified)
    var ref = window.document.getElementsByTagName( 'script' )[ 0 ];
    var script = window.document.createElement( 'script' );
    script.src = url + (url.indexOf( '?' ) + 1 ? '&' : '?') + 'callback=' + callback;

    // Insert script tag into the DOM (append to <head>)
    ref.parentNode.insertBefore( script, ref );

    // After the script is loaded (and executed), remove it
    script.onload = function () {
        this.remove();
    };

};

/** 
 * Example
 */

// Function to run on success
var logAPI = function ( data ) {
    console.log( data );
}

// Run request
loadJSONP( 'http://api.petfinder.com/shelter.getPets?format=json&key=12345&shelter=AA11', 'logAPI' );

What is the preferred Bash shebang?

#!/bin/sh

as most scripts do not need specific bash feature and should be written for sh.

Also, this makes scripts work on the BSDs, which do not have bash per default.

Submitting a multidimensional array via POST with php

you could submit all parameters with such naming:

params[0][topdiameter]
params[0][bottomdiameter]
params[1][topdiameter]
params[1][bottomdiameter]

then later you do something like this:

foreach ($_REQUEST['params'] as $item) {
    echo $item['topdiameter'];
    echo $item['bottomdiameter'];
}

Split column at delimiter in data frame

@Taesung Shin is right, but then just some more magic to make it into a data.frame. I added a "x|y" line to avoid ambiguities:

df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
foo <- data.frame(do.call('rbind', strsplit(as.character(df$FOO),'|',fixed=TRUE)))

Or, if you want to replace the columns in the existing data.frame:

within(df, FOO<-data.frame(do.call('rbind', strsplit(as.character(FOO), '|', fixed=TRUE))))

Which produces:

  ID FOO.X1 FOO.X2
1 11      a      b
2 12      b      c
3 13      x      y

Git push error '[remote rejected] master -> master (branch is currently checked out)'

What you probably did to cause this:

This kind of thing happens when you go to bang out a little program. You're about to change something which was already working, so you cast your level-3 spell of perpetual undoability:

machine1:~/proj1> git init

and you start adding/committing. But then, the project starts getting more involved and you want to work on it from another computer (like your home PC or laptop), so you do something like

machine2:~> git clone ssh://machine1/~/proj1

and it clones and everything looks good, and so you work on your code from machine2.

Then... you try to push your commits from machine2, and you get the warning message in the title.

The reason for this message is because the git repo you pulled from was kinda intended to be used just for that folder on machine1. You can clone from it just fine, but pushing can cause problems. The "proper" way to be managing the code in two different locations is with a "bare" repo, like has been suggested. A bare repo isn't designed to have any work being done in it, it is meant to coordinate the commits from multiple sources. This is why the top-rated answer suggests deleting all files/folders other than the .git folder after you git config --bool core.bare true.

Clarifying the top-rated answer: Many of the comments to that answer say something like "I didn't delete the non-.git files from the machine1 and I was still able to commit from machine2". That's right. However, those other files are completely "divorced" from the git repo, now. Go try git status in there and you should see something like "fatal: This operation must be run in a work tree". So, the suggestion to delete the files isn't so that the commit from machine2 will work; it's so that you don't get confused and think that git is still tracking those files. But, deleting the files is a problem if you still want to work on the files on machine1, isn't it?

So, what should you really do?

Depends upon how much you plan to still work on machine1 and machine2...

If you're done developing from machine1 and have moved all of your development to machine2... just do what the top-rated answer suggests: git config --bool core.bare true and then, optionally, delete all files/folders other than .git from that folder, since they're untracked and likely to cause confusion.

If your work on machine2 was just a one-time thing, and you don't need to continue development there... then don't bother with making a bare repo; just ftp/rsync/scp/etc. your files from machine*2* on top of the files on machine*1*, commit/push from machine*1*, and then delete the files off of machine*2*. Others have suggested creating a branch, but I think that's a little messy if you just want to merge some development you did on a one-time basis from another machine.

If you need to continue development on both machine1 and machine2... then you need to set things up properly. You need to convert your repo to a bare, then you need to make a clone of that on machine1 for you to work in. Probably the quickest way to do this is to do

machine1:~/proj1> git config --bool core.bare true
machine1:~/proj1> mv .git/ ../proj1.git
machine1:~/proj1> cd ..
machine1:~> rm -rf proj1
machine1:~> git clone proj1.git
machine1:~> cd proj1

Very important: because you've moved the location of the repo from proj1 to proj1.git, you need to update this in the .git/config file on machine2. After that, you can commit your changes from machine2. Lastly, I try to keep my bare repos in a central location, away from my work trees (i.e. don't put 'proj1.git' in the same parent folder as 'proj1'). I advise you to do likewise, but I wanted to keep the steps above as simple as possible.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

If Andy Copley's answer worked for you but simply rebuilding the solution doesn't work, then go to Project | Project Dependencies and make sure that the project that has your Global.asax.cs file in it is dependent on all the other non-test projects in the solution.

How to update core-js to core-js@3 dependency?

Install

npm i core-js

Modular standard library for JavaScript. Includes polyfills for ECMAScript up to 2019: promises, symbols, collections, iterators, typed arrays, many other features, ECMAScript proposals, some cross-platform WHATWG / W3C features and proposals like URL. You can load only required features or use it without global namespace pollution.

Read: https://www.npmjs.com/package/core-js

How can I check if some text exist or not in the page using Selenium?

JUnit+Webdriver

assertEquals(driver.findElement(By.xpath("//this/is/the/xpath/location/where/the/text/sits".getText(),"insert the text you're expecting to see here");

If in the event your expected text doesn't match the xpath text, webdriver will tell you what the actual text was vs what you were expecting.

Clearing an HTML file upload field via JavaScript

For compatibility when ajax is not available, set .val('') or it will resend the last ajax-uploaded file that is still present in the input. The following should properly clear the input whilst retaining .on() events:

var input = $("input[type='file']");
input.html(input.html()).val('');

JDK on OSX 10.7 Lion

You can download the 10.7 Lion JDK from http://connect.apple.com.

  1. Sign in and click the java section on the right.

  2. The jdk is installed into a different location then previous. This will result in IDEs (such as Eclipse) being unable to locate source code and javadocs.

  3. At the time of writing the JDK ended up here:

    /Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home

  4. Open up eclipse preferences and go to Java --> Installed JREs page

  5. Rather than use the "JVM Contents (MacOS X Default) we will need to use the JDK location

  6. At the time of writing Search is not aware of the new JDK location; we we will need to click on the Add button

  7. From the Add JRE wizard choose "MacOS X VM" for the JRE Type

  8. For the JRE Definition Page we need to fill in the following:

    • JRE Home: /Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home
  9. The other fields will now auto fill, with the default JRE name being "Home". You can quickly correct this to something more meaningful:

    • JRE name: System JDK
  10. Finish the wizard and return to the Installed JREs page

  11. Choose "System JDK" from the list

  12. You can now develop normally with:

    • javadocs correctly shown for base classes
    • source code correctly shown when debugging

How to check if number is divisible by a certain number?

package lecture3;

import java.util.Scanner;

public class divisibleBy2and5 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        System.out.println("Enter an integer number:");
        Scanner input = new Scanner(System.in);
        int x;
        x = input.nextInt();
         if (x % 2==0){
             System.out.println("The integer number you entered is divisible by 2");
         }
         else{
             System.out.println("The integer number you entered is not divisible by 2");
             if(x % 5==0){
                 System.out.println("The integer number you entered is divisible by 5");
             } 
             else{
                 System.out.println("The interger number you entered is not divisible by 5");
             }
        }

    }
}

Predict() - Maybe I'm not understanding it

To avoid error, an important point about the new dataset is the name of independent variable. It must be the same as reported in the model. Another way is to nest the two function without creating a new dataset

model <- lm(Coupon ~ Total, data=df)
predict(model, data.frame(Total=c(79037022, 83100656, 104299800)))

Pay attention on the model. The next two commands are similar, but for predict function, the first work the second don't work.

model <- lm(Coupon ~ Total, data=df) #Ok
model <- lm(df$Coupon ~ df$Total) #Ko

pandas unique values multiple columns

An updated solution using numpy v1.13+ requires specifying the axis in np.unique if using multiple columns, otherwise the array is implicitly flattened.

import numpy as np

np.unique(df[['col1', 'col2']], axis=0)

This change was introduced Nov 2016: https://github.com/numpy/numpy/commit/1f764dbff7c496d6636dc0430f083ada9ff4e4be

Regular Expressions: Search in list

Full Example (Python 3):
For Python 2.x look into Note below

import re

mylist = ["dog", "cat", "wildcat", "thundercat", "cow", "hooo"]
r = re.compile(".*cat")
newlist = list(filter(r.match, mylist)) # Read Note
print(newlist)

Prints:

['cat', 'wildcat', 'thundercat']

Note:

For Python 2.x developers, filter returns a list already. In Python 3.x filter was changed to return an iterator so it has to be converted to list (in order to see it printed out nicely).

Python 3 code example
Python 2.x code example

Javascript variable access in HTML

<html>
<head>
<script>
    function putText() {
        var simpleText = "hello_world";
        var finalSplitText = simpleText.split("_");
        var splitText = finalSplitText[0];
        document.getElementById("destination").innerHTML = "I need the value of " + splitText + " variable here";
    }
</script>
</head>
<body onLoad = putText()>
    <a id="destination" href = test.html>I need the value of "splitText" variable here</a>
</body>
</html>

Python: Total sum of a list of numbers with the for loop

l = [1,2,3,4,5]
sum = 0
for x in l:
    sum = sum + x

And you can change l for any list you want.

How to determine if string contains specific substring within the first X characters

Use IndexOf is easier and high performance.

int index = Value1.IndexOf("abc");
bool found = index >= 0 && index < x;

How can I de-install a Perl module installed via `cpan`?

Update 2013: This code is obsolescent. Upvote bsb's late-coming answer instead.


I don't need to uninstall modules often, but the .packlist file based approach has never failed me so far.

use 5.010;
use ExtUtils::Installed qw();
use ExtUtils::Packlist qw();

die "Usage: $0 Module::Name Module::Name\n" unless @ARGV;

for my $mod (@ARGV) {
    my $inst = ExtUtils::Installed->new;

    foreach my $item (sort($inst->files($mod))) {
        say "removing $item";
        unlink $item or warn "could not remove $item: $!\n";
    }

    my $packfile = $inst->packlist($mod)->packlist_file;
    print "removing $packfile\n";
    unlink $packfile or warn "could not remove $packfile: $!\n";
}

Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

Request.Redirect(url,false);

false indicates whether execution of current page should terminate.

How do I grep recursively?

Note that find . -type f | xargs grep whatever sorts of solutions will run into "Argument list to long" errors when there are too many files matched by find.

The best bet is grep -r but if that isn't available, use find . -type f -exec grep -H whatever {} \; instead.

Adding attributes to an XML node

The latest and supposedly greatest way to construct the XML is by using LINQ to XML:

using System.Xml.Linq

       var xmlNode =
            new XElement("Login",
                         new XElement("id",
                             new XAttribute("userName", "Tushar"),
                             new XAttribute("password", "Tushar"),
                             new XElement("Name", "Tushar"),
                             new XElement("Age", "24")
                         )
            );
       xmlNode.Save("Tushar.xml");

Supposedly this way of coding should be easier, as the code closely resembles the output (which Jon's example above does not). However, I found that while coding this relatively easy example I was prone to lose my way between the cartload of comma's that you have to navigate among. Visual studio's auto spacing of code does not help either.

socket programming multiple client to one server

Here is code for Multiple Client to one Server Working Fine .. Give it a try :)

Server.java:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

class Multi extends Thread{
private Socket s=null;
DataInputStream infromClient;
Multi() throws IOException{


}
Multi(Socket s) throws IOException{
    this.s=s;
    infromClient = new DataInputStream(s.getInputStream());
}
public void run(){  

    String SQL=new String();
    try {
        SQL = infromClient.readUTF();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
    }
    System.out.println("Query: " + SQL); 
    try {
        System.out.println("Socket Closing");
        s.close();
    } catch (IOException ex) {
        Logger.getLogger(Multi.class.getName()).log(Level.SEVERE, null, ex);
       }
   }  
}
public class Server {

public static void main(String args[]) throws IOException, 
InterruptedException{   

    while(true){
        ServerSocket ss=new ServerSocket(11111);
        System.out.println("Server is Awaiting"); 
        Socket s=ss.accept();
        Multi t=new Multi(s);
        t.start();

        Thread.sleep(2000);
        ss.close();
    }    




    }   
}

Client1.java:

 import java.io.DataOutputStream;
 import java.io.ObjectInputStream;
 import java.net.Socket;


public class client1 {
   public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I  am  client 1";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
}

Client2.java

import java.io.DataOutputStream; 
import java.net.Socket;


public class client2 {
    public static void main(String[] arg) {
  try {

     Socket socketConnection = new Socket("127.0.0.1", 11111);


     //QUERY PASSING
     DataOutputStream outToServer = new DataOutputStream(socketConnection.getOutputStream());

     String SQL="I am  Client 2";
     outToServer.writeUTF(SQL);


  } catch (Exception e) {System.out.println(e); }
   }
 }

How do I assign a port mapping to an existing Docker container?

In Fujimoto Youichi's example test01 is a container, whereas test02 is an image.

Before doing docker run you can remove the original container and then assign the container the same name again:

$ docker stop container01
$ docker commit container01 image01
$ docker rm container01
$ docker run -d -P --name container01 image01

(Using -P to expose ports to random ports rather than manually assigning).

Angular-cli from css to scss

For Angular 6 check the Official documentation

Note: For @angular/cli versions older than 6.0.0-beta.6 use ng set in place of ng config.

For existing projects

In an existing angular-cli project that was set up with the default css styles you will need to do a few things:

  1. Change the default style extension to scss

Manually change in .angular-cli.json (Angular 5.x and older) or angular.json (Angular 6+) or run:

ng config defaults.styleExt=scss

if you get an error: Value cannot be found. use the command:

ng config schematics.@schematics/angular:component.styleext scss

(*source: Angular CLI SASS options)

  1. Rename your existing .css files to .scss (i.e. styles.css and app/app.component.css)

  2. Point the CLI to find styles.scss

Manually change the file extensions in apps[0].styles in angular.json

  1. Point the components to find your new style files

Change the styleUrls in your components to match your new file names

For future projects

As @Serginho mentioned you can set the style extension when running the ng new command

ng new your-project-name --style=scss

If you want to set the default for all projects you create in the future run the following command:

ng config --global defaults.styleExt=scss

How to pass an array within a query string?

A query string carries textual data so there is no option but to explode the array, encode it correctly and pass it in a representational format of your choice:

p1=value1&pN=valueN...
data=[value1,...,valueN]
data={p1:value1,...,pN:valueN}

and then decode it in your server side code.

How to add a new audio (not mixing) into a video using ffmpeg?

Code to add audio to video using ffmpeg.

If audio length is greater than video length it will cut the audio to video length. If you want full audio in video remove -shortest from the cmd.

String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy", ,outputFile.getPath()};

private void execFFmpegBinaryShortest(final String[] command) {



            final File outputFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/videoaudiomerger/"+"Vid"+"output"+i1+".mp4");




            String[] cmd = new String[]{"-i", selectedVideoPath,"-i",audiopath,"-map","1:a","-map","0:v","-codec","copy","-shortest",outputFile.getPath()};


            try {

                ffmpeg.execute(cmd, new ExecuteBinaryResponseHandler() {
                    @Override
                    public void onFailure(String s) {
                        System.out.println("on failure----"+s);
                    }

                    @Override
                    public void onSuccess(String s) {
                        System.out.println("on success-----"+s);
                    }

                    @Override
                    public void onProgress(String s) {
                        //Log.d(TAG, "Started command : ffmpeg "+command);
                        System.out.println("Started---"+s);

                    }

                    @Override
                    public void onStart() {


                        //Log.d(TAG, "Started command : ffmpeg " + command);
                        System.out.println("Start----");

                    }

                    @Override
                    public void onFinish() {
                        System.out.println("Finish-----");


                    }
                });
            } catch (FFmpegCommandAlreadyRunningException e) {
                // do nothing for now
                System.out.println("exceptio :::"+e.getMessage());
            }


        }

How to style a div to be a responsive square?

It is as easy as specifying a padding bottom the same size as the width in percent. So if you have a width of 50%, just use this example below

id or class{
    width: 50%;
    padding-bottom: 50%;
}

Here is a jsfiddle http://jsfiddle.net/kJL3u/2/

Edited version with responsive text: http://jsfiddle.net/kJL3u/394

How do I do an OR filter in a Django query?

You want to make filter dynamic then you have to use Lambda like

from django.db.models import Q

brands = ['ABC','DEF' , 'GHI']

queryset = Product.objects.filter(reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]))

reduce(lambda x, y: x | y, [Q(brand=item) for item in brands]) is equivalent to

Q(brand=brands[0]) | Q(brand=brands[1]) | Q(brand=brands[2]) | .....

How to get full REST request body using Jersey?

Turns out you don't have to do much at all.

See below - the parameter x will contain the full HTTP body (which is XML in our case).

@POST
public Response go(String x) throws IOException {
    ...
}

How do you import classes in JSP?

FYI - if you are importing a List into a JSP, chances are pretty good that you are violating MVC principles. Take a few hours now to read up on the MVC approach to web app development (including use of taglibs) - do some more googling on the subject, it's fascinating and will definitely help you write better apps.

If you are doing anything more complicated than a single JSP displaying some database results, please consider using a framework like Spring, Grails, etc... It will absolutely take you a bit more effort to get going, but it will save you so much time and effort down the road that I really recommend it. Besides, it's cool stuff :-)

How to install MySQLdb (Python data access library to MySQL) on Mac OS X?

Or simple try:

> sudo easy_install MySQL-python

If it gives a error like below:

EnvironmentError: mysql_config not found

, then just run this

> export PATH=$PATH:/usr/local/mysql/bin

How to style dt and dd so they are on the same line?

Here is one possible flex-based solution (SCSS):

dl {
  display: flex;
  flex-wrap: wrap;
  width: 100%;
  dt {
    width: 150px;
  }
  dd {
    margin: 0;
    flex: 1 0 calc(100% - 150px);
  }
}

that works for the following HTML (pug)

dl
  dt item 1
  dd desc 1
  dt item 2
  dd desc 2

"You may need an appropriate loader to handle this file type" with Webpack and Babel

If you are using Webpack > 3 then you only need to install babel-preset-env, since this preset accounts for es2015, es2016 and es2017.

var path = require('path');
let webpack = require("webpack");

module.exports = {
    entry: {
        app: './app/App.js',
        vendor: ["react","react-dom"]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '../public')
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader?cacheDirectory=true',
            }
        }]
    }
};

This picks up its configuration from my .babelrc file:

{
    "presets": [
        [
            "env",
            {
                "targets": {
                    "browsers":["last 2 versions"],
                    "node":"current"
                }
            }
        ],["react"]
    ]
}

Error in eval(expr, envir, enclos) : object not found

I think I got what I was looking for..

data.train <- read.table("Assign2.WineComplete.csv",sep=",",header=T)
fit <- rpart(quality ~ ., method="class",data=data.train)
plot(fit)
text(fit, use.n=TRUE)
summary(fit)

React fetch data in server before render

What you're looking for is componentWillMount.

From the documentation:

Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call setState within this method, render() will see the updated state and will be executed only once despite the state change.

So you would do something like this:

componentWillMount : function () {
    var data = this.getData();
    this.setState({data : data});
},

This way, render() will only be called once, and you'll have the data you're looking for in the initial render.

Getting the length of two-dimensional array

Remember, 2D array is not a 2D array in real sense.Every element of an array in itself is an array, not necessarily of the same size. so, nir[0].length may or may not be equal to nir[1].length or nir[2]length.

Hope that helps..:)

Git cli: get user info from username

Try this

git config user.name

git config command stores and gives all the information.

git config -l

This commands gives you all the required info that you want.

You can change the information using

git config --global user.name "<Your-name>"

Similarly you can change many info shown to you using -l option.

automating telnet session using bash scripts

Following is working for me... put all of your IPs you want to telnet in IP_sheet.txt

while true
read a
do
{
    sleep 3
    echo df -kh
    sleep 3
    echo exit
} | telnet $a
done<IP_sheet.txt

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;
    }

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;
    }

    //MUST CALL THIS
    setMeasuredDimension(width, height);
}

Hope that Helps.

How to program a fractal?

I would start with something simple, like a Koch Snowflake. It's a simple process of taking a line and transforming it, then repeating the process recursively until it looks neat-o.

Something super simple like taking 2 points (a line) and adding a 3rd point (making a corner), then repeating on each new section that's created.

fractal(p0, p1){
    Pmid = midpoint(p0,p1) + moved some distance perpendicular to p0 or p1;
    fractal(p0,Pmid);
    fractal(Pmid, p1);
}

How do I give text or an image a transparent background using CSS?

You can solve this for Internet Explorer 8 by (ab)using the gradient syntax. The color format is ARGB. If you are using the Sass preprocessor you can convert colors using the built-in function "ie-hex-str()".

background: rgba(0,0,0, 0.5);
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#80000000')";

Difference between opening a file in binary vs text

The link you gave does actually describe the differences, but it's buried at the bottom of the page:

http://www.cplusplus.com/reference/cstdio/fopen/

Text files are files containing sequences of lines of text. Depending on the environment where the application runs, some special character conversion may occur in input/output operations in text mode to adapt them to a system-specific text file format. Although on some environments no conversions occur and both text files and binary files are treated the same way, using the appropriate mode improves portability.

The conversion could be to normalize \r\n to \n (or vice-versa), or maybe ignoring characters beyond 0x7F (a-la 'text mode' in FTP). Personally I'd open everything in binary-mode and use a good text-encoding library for dealing with text.

Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Tested in IE9, and latest Firefox and Chrome and also supported in IE8.

document.onreadystatechange = function () {
  var state = document.readyState;
  if (state == 'interactive') {
      init();
  } else if (state == 'complete') {
      initOnCompleteLoad();
  }
}?;

Example: http://jsfiddle.net/electricvisions/Jacck/

UPDATE - reusable version

I have just developed the following. It's a rather simplistic equivalent to jQuery or Dom ready without backwards compatibility. It probably needs further refinement. Tested in latest versions of Chrome, Firefox and IE (10/11) and should work in older browsers as commented on. I'll update if I find any issues.

window.readyHandlers = [];
window.ready = function ready(handler) {
  window.readyHandlers.push(handler);
  handleState();
};

window.handleState = function handleState () {
  if (['interactive', 'complete'].indexOf(document.readyState) > -1) {
    while(window.readyHandlers.length > 0) {
      (window.readyHandlers.shift())();
    }
  }
};

document.onreadystatechange = window.handleState;

Usage:

ready(function () {
  // your code here
});

It's written to handle async loading of JS but you might want to sync load this script first unless you're minifying. I've found it useful in development.

Modern browsers also support async loading of scripts which further enhances the experience. Support for async means multiple scripts can be downloaded simultaneously all while still rendering the page. Just watch out when depending on other scripts loaded asynchronously or use a minifier or something like browserify to handle dependencies.

json and empty array

null is a legal value (and reserved word) in JSON, but some environments do not have a "NULL" object (as opposed to a NULL value) and hence cannot accurately represent the JSON null. So they will sometimes represent it as an empty array.

Whether null is a legal value in that particular element of that particular API is entirely up to the API designer.

How do I format a String in an email so Outlook will print the line breaks?

Microsoft Outlook 2002 and above removes "extra line breaks" from text messages by default (kb308319). That is, Outlook seems to simply ignore line feed and/or carriage return sequences in text messages, running all of the lines together.

This can cause problems if you're trying to write code that will automatically generate an email message to be read by someone using Outlook.

For example, suppose you want to supply separate pieces of information each on separate lines for clarity, like this:

Transaction needs attention!
PostedDate: 1/30/2009
Amount: $12,222.06
TransID: 8gk288g229g2kg89
PostalCode: 91543

Your Outlook recipient will see the information all smashed together, as follows:

Transaction needs attention! PostedDate: 1/30/2009 Amount: $12,222.06 TransID: 8gk288g229g2kg89 ZipCode: 91543

There doesn't seem to be an easy solution. Alternatives are:

  1. You can supply two sets of line breaks between each line. That does stop Outlook from combining the lines onto one line, but it then displays an extra blank line between each line (creating the opposite problem). By "supply two sets of line breaks" I mean you should use "\r\n\r\n" or "\r\r" or "\n\n" but not "\r\n" or "\n\r".
  2. You can supply two spaces at the beginning of every line in the body of your email message. That avoids introducing an extra blank line between each line. But this works best if each line in your message is fairly short, because the user may be previewing the text in a very narrow Outlook window that wraps the end of each line around to the first position on the next line, where it won't line up with your two-space-indented lines. This strategy has been used for some newsletters.
  3. You can give up on using a plain text format, and use an html format.

How to filter (key, value) with ng-repeat in AngularJs?

Or simply use

ng-show="v.hasOwnProperty('secId')"

See updated solution here:

http://jsfiddle.net/RFontana/WA2BE/93/

Forcing label to flow inline with input that they label

If you want they to be paragraph, then use it.

<p><label for="id1">label1:</label> <input type="text" id="id1"/></p>
<p><label for="id2">label2:</label> <input type="text" id="id2"/></p>

Both <label> and <input> are paragraph and flow content so you can insert as paragraph elements and as block elements.

Append to the end of a Char array in C++

You should have enough space for array1 array and use something like strcat to contact array1 to array2:

char array1[BIG_ENOUGH];
char array2[X];
/* ......             */
/* check array bounds */
/* ......             */

strcat(array1, array2);

Match all elements having class name starting with a specific string

The following should do the trick:

div[class^='myclass'], div[class*=' myclass']{
    color: #F00;
}

Edit: Added wildcard (*) as suggested by David

How do I check what version of Python is running my script?

With six module, you can do it by:

import six

if six.PY2:
  # this is python2.x
else:
  # six.PY3
  # this is python3.x

Location of the mongodb database on mac

If mongodb is installed via Homebrew the default location is:

/usr/local/var/mongodb

See the answer from @simonbogarde for the location of other interesting files that are different when using Homebrew.

javascript - Create Simple Dynamic Array

updated = > june 2020

if are you using node js you can create or append a string value with " ," operator then inside the loop you can

for (var j = 0; j <= data.legth -1; j++) {
                    lang += data.lang  +", " ;

                }

 var langs = lang.split(',')
 console.log("Languages =>",  lang, typeof(lang), typeof(langs), langs) 
 console.log(lang[0]) // here access arrary by index value
            

you can see the type of string and object

How to install a specific version of Node on Ubuntu?

Here is a list of available builds for debian: https://github.com/nodesource/distributions/tree/master/deb

For this example, lets assume you want version 14 (LTS at the time of writing)

We can download this script from github, execute it and install the version of node we want. For security reasons it's a good idea to read the script prior to executing it.

curl -sL https://raw.githubusercontent.com/nodesource/distributions/master/deb/setup_14.x | bash
apt-get install -y nodejs # may or may not require sudo based on your setup 

I like this approach because it doesn't require extraneous dependencies like nvm to target specific versions

If you are building for a different distro or architecture you can find more builds here https://nodejs.org/dist/

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

You need to add a new service for DBcontext in the startup

Default

services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("DefaultConnection")));

Add this

services.AddDbContext<NewDBContext>(options =>
                options.UseSqlServer(
                    Configuration.GetConnectionString("NewConnection")));

git ignore all files of a certain type, except those in a specific subfolder

An optional prefix ! which negates the pattern; any matching file excluded by a previous pattern will become included again. If a negated pattern matches, this will override lower precedence patterns sources.

http://schacon.github.com/git/gitignore.html

*.json
!spec/*.json

ORA-01652: unable to extend temp segment by 128 in tablespace SYSTEM: How to extend?

Each tablespace has one or more datafiles that it uses to store data.

The max size of a datafile depends on the block size of the database. I believe that, by default, that leaves with you with a max of 32gb per datafile.

To find out if the actual limit is 32gb, run the following:

select value from v$parameter where name = 'db_block_size';

Compare the result you get with the first column below, and that will indicate what your max datafile size is.

I have Oracle Personal Edition 11g r2 and in a default install it had an 8,192 block size (32gb per data file).

Block Sz   Max Datafile Sz (Gb)   Max DB Sz (Tb)

--------   --------------------   --------------

   2,048                  8,192          524,264

   4,096                 16,384        1,048,528

   8,192                 32,768        2,097,056

  16,384                 65,536        4,194,112

  32,768                131,072        8,388,224

You can run this query to find what datafiles you have, what tablespaces they are associated with, and what you've currrently set the max file size to (which cannot exceed the aforementioned 32gb):

select bytes/1024/1024 as mb_size,
       maxbytes/1024/1024 as maxsize_set,
       x.*
from   dba_data_files x

MAXSIZE_SET is the maximum size you've set the datafile to. Also relevant is whether you've set the AUTOEXTEND option to ON (its name does what it implies).

If your datafile has a low max size or autoextend is not on you could simply run:

alter database datafile 'path_to_your_file\that_file.DBF' autoextend on maxsize unlimited;

However if its size is at/near 32gb an autoextend is on, then yes, you do need another datafile for the tablespace:

alter tablespace system add datafile 'path_to_your_datafiles_folder\name_of_df_you_want.dbf' size 10m autoextend on maxsize unlimited;

Reading Space separated input in python

For python 3 use this

inp = list(map(int,input().split()))
#input => java is a programming language
#return as => ("java","is","a","programming","language")

input() accepts a string from STDIN.

split() splits the string about whitespace character and returns a list of strings.

map() passes each element of the 2nd argument to the first argument and returns a map object

Finally list() converts the map to a list

Create controller for partial view in ASP.NET MVC

If it were me, I would simply create a new Controller with a Single Action and then use RenderAction in place of Partial:

// Assuming the controller is named NewController
@{Html.RenderAction("ActionName", 
                     "New", 
                      new { routeValueOne = "SomeValue" });
}

Apache: client denied by server configuration

OK I am using the wrong syntax, I should be using

Allow from 127.0.0.1
Allow from ::1
...

Eclipse - debugger doesn't stop at breakpoint

Remove all breakpoints and re-add them.

Find if a textbox is disabled or not using jquery

You can use $(":disabled") to select all disabled items in the current context.

To determine whether a single item is disabled you can use $("#textbox1").is(":disabled").

How to generate and auto increment Id with Entity Framework

You have a bad table design. You can't autoincrement a string, that doesn't make any sense. You have basically two options:

1.) change type of ID to int instead of string
2.) not recommended!!! - handle autoincrement by yourself. You first need to get the latest value from the database, parse it to the integer, increment it and attach it to the entity as a string again. VERY BAD idea

First option requires to change every table that has a reference to this table, BUT it's worth it.

Creating a simple XML file using python

These days, the most popular (and very simple) option is the ElementTree API, which has been included in the standard library since Python 2.5.

The available options for that are:

  • ElementTree (Basic, pure-Python implementation of ElementTree. Part of the standard library since 2.5)
  • cElementTree (Optimized C implementation of ElementTree. Also offered in the standard library since 2.5)
  • LXML (Based on libxml2. Offers a rich superset of the ElementTree API as well XPath, CSS Selectors, and more)

Here's an example of how to generate your example document using the in-stdlib cElementTree:

import xml.etree.cElementTree as ET

root = ET.Element("root")
doc = ET.SubElement(root, "doc")

ET.SubElement(doc, "field1", name="blah").text = "some value1"
ET.SubElement(doc, "field2", name="asdfasd").text = "some vlaue2"

tree = ET.ElementTree(root)
tree.write("filename.xml")

I've tested it and it works, but I'm assuming whitespace isn't significant. If you need "prettyprint" indentation, let me know and I'll look up how to do that. (It may be an LXML-specific option. I don't use the stdlib implementation much)

For further reading, here are some useful links:

As a final note, either cElementTree or LXML should be fast enough for all your needs (both are optimized C code), but in the event you're in a situation where you need to squeeze out every last bit of performance, the benchmarks on the LXML site indicate that:

  • LXML clearly wins for serializing (generating) XML
  • As a side-effect of implementing proper parent traversal, LXML is a bit slower than cElementTree for parsing.

How to get the type of T from a member of a generic class or method?

public bool IsCollection<T>(T value){
  var valueType = value.GetType();
  return valueType.IsArray() || typeof(IEnumerable<object>).IsAssignableFrom(valueType) || typeof(IEnumerable<T>).IsAssignableFrom(valuetype);
}

How to open warning/information/error dialog in Swing?

import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class ErrorDialog {

  public static void main(String argv[]) {
    String message = "\"The Comedy of Errors\"\n"
        + "is considered by many scholars to be\n"
        + "the first play Shakespeare wrote";
    JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
        JOptionPane.ERROR_MESSAGE);
  }
}

Html Agility Pack get all elements by class

You can use the following script:

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

How to capture a backspace on the onkeydown event

In your function check for the keycode 8 (backspace) or 46 (delete)

Keycode information
Keycode list

How to sum data.frame column values?

To sum values in data.frame you first need to extract them as a vector.

There are several way to do it:

# $ operatior
x <- people$Weight
x
# [1] 65 70 64

Or using [, ] similar to matrix:

x <- people[, 'Weight']
x
# [1] 65 70 64

Once you have the vector you can use any vector-to-scalar function to aggregate the result:

sum(people[, 'Weight'])
# [1] 199

If you have NA values in your data, you should specify na.rm parameter:

sum(people[, 'Weight'], na.rm = TRUE)

How can I rollback a git repository to a specific commit?

Another way:

Checkout the branch you want to revert, then reset your local working copy back to the commit that you want to be the latest one on the remote server (everything after it will go bye-bye). To do this, in SourceTree, I right-clicked on the and selected "Reset BRANCHNAME to this commit".

Then navigate to your repository's local directory and run this command:

git -c diff.mnemonicprefix=false -c core.quotepath=false push -v -f -- tags REPOSITORY_NAME BRANCHNAME:BRANCHNAME 

This will erase all commits after the current one in your local repository but only for that one branch.

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

Fragment pressing back button

you can use this one in onCreateView, you can use transaction or replace

 OnBackPressedCallback callback = new OnBackPressedCallback(true) {
                @Override
                public void handleOnBackPressed() {
                    //what you want to do 
                }
            };
    requireActivity().getOnBackPressedDispatcher().addCallback(this, callback);

Regular Expression to match only alphabetic characters

[a-zA-Z] should do that just fine.

You can reference the cheat sheet.

check if "it's a number" function in Oracle

Here's a simple method which :

  • does not rely on TRIM
  • does not rely on REGEXP
  • allows to specify decimal and/or thousands separators ("." and "," in my example)
  • works very nicely on Oracle versions as ancient as 8i (personally tested on 8.1.7.4.0; yes, you read that right)
SELECT
    TEST_TABLE.*,

    CASE WHEN
        TRANSLATE(TEST_TABLE.TEST_COLUMN, 'a.,0123456789', 'a') IS NULL
    THEN 'Y'
    ELSE 'N'
    END
    AS IS_NUMERIC

FROM
    (
    -- DUMMY TEST TABLE
        (SELECT '1' AS TEST_COLUMN FROM DUAL) UNION
        (SELECT '1,000.00' AS TEST_COLUMN FROM DUAL) UNION
        (SELECT 'xyz1' AS TEST_COLUMN FROM DUAL) UNION
        (SELECT 'xyz 123' AS TEST_COLUMN FROM DUAL) UNION
        (SELECT '.,' AS TEST_COLUMN FROM DUAL)
    ) TEST_TABLE

Result:

TEST_COLUMN IS_NUMERIC
----------- ----------
.,          Y
1           Y
1,000.00    Y
xyz 123     N
xyz1        N

5 rows selected.

Granted this might not be the most powerful method of all; for example ".," is falsely identified as a numeric. However it is quite simple and fast and it might very well do the job, depending on the actual data values that need to be processed.

For integers, we can simplify the Translate operation as follows :

TRANSLATE(TEST_TABLE.TEST_COLUMN, 'a0123456789', 'a') IS NULL

How it works

From the above, note the Translate function's syntax is TRANSLATE(string, from_string, to_string). Now the Translate function cannot accept NULL as the to_string argument. So by specifying 'a0123456789' as the from_string and 'a' as the to_string, two things happen:

  • character a is left alone;
  • numbers 0 to 9 are replaced with nothing since no replacement is specified for them in the to_string.

In effect the numbers are discarded. If the result of that operation is NULL it means it was purely numbers to begin with.

Python non-greedy regexes

Do you want it to match "(b)"? Do as Zitrax and Paolo have suggested. Do you want it to match "b"? Do

>>> x = "a (b) c (d) e"
>>> re.search(r"\((.*?)\)", x).group(1)
'b'

How to exclude records with certain values in sql select

One way:

SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
    SELECT * FROM StoreClients sc2 
    WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)

Get Element value with minidom with Python

Probably something like this if it's the text part you want...

from xml.dom.minidom import parse
dom = parse("C:\\eve.xml")
name = dom.getElementsByTagName('name')

print " ".join(t.nodeValue for t in name[0].childNodes if t.nodeType == t.TEXT_NODE)

The text part of a node is considered a node in itself placed as a child-node of the one you asked for. Thus you will want to go through all its children and find all child nodes that are text nodes. A node can have several text nodes; eg.

<name>
  blabla
  <somestuff>asdf</somestuff>
  znylpx
</name>

You want both 'blabla' and 'znylpx'; hence the " ".join(). You might want to replace the space with a newline or so, or perhaps by nothing.

Remove all line breaks from a long string of text

You can try using string replace:

string = string.replace('\r', '').replace('\n', '')

How to change the font on the TextView?

Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.

Check below link to check roboto fonts:

How to use Roboto in xml layout

Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ......
    <item name="android:buttonStyle">@style/MyButton</item>
    <item name="android:textViewStyle">@style/MyTextView</item>
</style>

<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

And don't forget to use 'AppTheme' in your AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ......
</application>

Elastic Search: how to see the indexed data

Kibana is also a good solution. It is a data visualization platform for Elastic.If installed it runs by default on port 5601.

Out of the many things it provides. It has "Dev Tools" where we can do your debugging.

For example you can check your available indexes here using the command

GET /_cat/indices

Showing Difference between two datetime values in hours

var startTime = new TimeSpan(6, 0, 0); // 6:00 AM
var endTime = new TimeSpan(5, 30, 0); // 5:30 AM 
var hours24 = new TimeSpan(24, 0, 0);
var difference = endTime.Subtract(startTime); // (-00:30:00)
difference = (difference.Duration() != difference) ? hours24.Subtract(difference.Duration()) : difference; // (23:30:00)

can also add difference between the dates if we compare two different dates

new TimeSpan(24 * days, 0, 0)

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

How to correctly write async method?

You are calling DoDownloadAsync() but you don't wait it. So your program going to the next line. But there is another problem, Async methods should return Task or Task<T>, if you return nothing and you want your method will be run asyncronously you should define your method like this:

private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } 

And in Main method you can't await for DoDownloadAsync, because you can't use await keyword in non-async function, and you can't make Main async. So consider this:

var result = DoDownloadAsync();  Debug.WriteLine("DoDownload done"); result.Wait(); 

How can you use optional parameters in C#?

Using overloads or using C# 4.0 or above

 private void GetVal(string sName, int sRoll)
 {
   if (sRoll > 0)
   {
    // do some work
   }
 }

 private void GetVal(string sName)
 {
    GetVal("testing", 0);
 }

How to access parent Iframe from JavaScript

Simply call window.frameElement from your framed page. If the page is not in a frame then frameElement will be null.

The other way (getting the window element inside a frame is less trivial) but for sake of completeness:

/**
 * @param f, iframe or frame element
 * @return Window object inside the given frame
 * @effect will append f to document.body if f not yet part of the DOM
 * @see Window.frameElement
 * @usage myFrame.document = getFramedWindow(myFrame).document;
 */
function getFramedWindow(f)
{
    if(f.parentNode == null)
        f = document.body.appendChild(f);
    var w = (f.contentWindow || f.contentDocument);
    if(w && w.nodeType && w.nodeType==9)
        w = (w.defaultView || w.parentWindow);
    return w;
}

Java System.out.print formatting

Just use \t to space it.

Example:

System.out.println(monthlyInterest + "\t")

//as far as the two 0 in front of it just use a if else statement. ex: 
x = x+1;
if (x < 10){
    System.out.println("00" +x);
}
else if( x < 100){
    System.out.println("0" +x);
}
else{
    System.out.println(x);
}

There are other ways to do it, but this is the simplest.

Run react-native on android emulator

You can also try use "doctor" command. It will fix most cases.

npx @react-native-community/cli doctor

SVN Error - Not a working copy

Same, I needed to update a 'contrib' folder:

  1. Moved the old folder out,
  2. Copied the new one
  3. Copied the .svn folders into each (only three in my case) new folder.

I my case too the problem was due to deleted .svn folders.

Solved.

C++ inheritance - inaccessible base?

By default, inheritance is private. You have to explicitly use public:

class Bar : public Foo

How to get the mobile number of current sim card in real device?

You can use the TelephonyManager to do this:

TelephonyManager tm = (TelephonyManager)getSystemService(TELEPHONY_SERVICE); 
String number = tm.getLine1Number();

The documentation for getLine1Number() says this method will return null if the number is "unavailable", but it does not say when the number might be unavailable.

You'll need to give your application permission to make this query by adding the following to your Manifest:

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

(You shouldn't use TelephonyManager.getDefault() to get the TelephonyManager as that is a private undocumented API call and may change in future.)

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

How do I look inside a Python object?

You can list the attributes of a object with dir() in the shell:

>>> dir(object())
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

Of course, there is also the inspect module: http://docs.python.org/library/inspect.html#module-inspect

What is a regular expression for a MAC Address?

This regex matches pretty much every mac format including Cisco format such as 0102-0304-abcd

^([[:xdigit:]]{2}[:.-]?){5}[[:xdigit:]]{2}$

Example strings which it matches:

01:02:03:04:ab:cd
01-02-03-04-ab-cd
01.02.03.04.ab.cd
0102-0304-abcd
01020304abcd

Mixed format will be matched also!

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

How to display custom view in ActionBar?

There is an example in the launcher app of Android (that I've made a library out of it, here), inside the class that handles wallpapers-picking ("WallpaperPickerActivity") .

The example shows that you need to set a customized theme for this to work. Sadly, this worked for me only using the normal framework, and not the one of the support library.

Here're the themes:

styles.xml

 <style name="Theme.WallpaperPicker" parent="Theme.WallpaperCropper">
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:colorBackgroundCacheHint">@null</item>
    <item name="android:windowShowWallpaper">true</item>
  </style>

  <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
  </style>

  <style name="WallpaperCropperActionBar" parent="@android:style/Widget.DeviceDefault.ActionBar">
    <item name="android:displayOptions">showCustom</item>
    <item name="android:background">#88000000</item>
  </style>

value-v19/styles.xml

 <style name="Theme.WallpaperCropper" parent="@android:style/Theme.DeviceDefault">
    <item name="android:actionBarStyle">@style/WallpaperCropperActionBar</item>
    <item name="android:windowFullscreen">true</item>
    <item name="android:windowActionBarOverlay">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

  <style name="Theme" parent="@android:style/Theme.DeviceDefault.Wallpaper.NoTitleBar">
    <item name="android:windowTranslucentStatus">true</item>
    <item name="android:windowTranslucentNavigation">true</item>
  </style>

EDIT: there is a better way to do it, which works on the support library too. Just add this line of code instead of what I've written above:

getSupportActionBar().setDisplayShowCustomEnabled(true);

JavaScript file upload size validation

No Yes, using the File API in newer browsers. See TJ's answer for details.

If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUpload or Uploadify to do this.

The SWFUpload Features Demo shows how the file_size_limit setting works.

Note that this (obviously) needs Flash, plus the way it works is a bit different from normal upload forms.

What is the difference between Task.Run() and Task.Factory.StartNew()

The Task.Run got introduced in newer .NET framework version and it is recommended.

Starting with the .NET Framework 4.5, the Task.Run method is the recommended way to launch a compute-bound task. Use the StartNew method only when you require fine-grained control for a long-running, compute-bound task.

The Task.Factory.StartNew has more options, the Task.Run is a shorthand:

The Run method provides a set of overloads that make it easy to start a task by using default values. It is a lightweight alternative to the StartNew overloads.

And by shorthand I mean a technical shortcut:

public static Task Run(Action action)
{
    return Task.InternalStartNew(null, action, null, default(CancellationToken), TaskScheduler.Default,
        TaskCreationOptions.DenyChildAttach, InternalTaskOptions.None, ref stackMark);
}

How do I replace a character at a particular index in JavaScript?

@CemKalyoncu: Thanks for the great answer!

I also adapted it slightly to make it more like the Array.splice method (and took @Ates' note into consideration):

spliceString=function(string, index, numToDelete, char) {
      return string.substr(0, index) + char + string.substr(index+numToDelete);
   }

var myString="hello world!";
spliceString(myString,myString.lastIndexOf('l'),2,'mhole'); // "hello wormhole!"

"Uncaught (in promise) undefined" error when using with=location in Facebook Graph API query

The reject actually takes one parameter: that's the exception that occurred in your code that caused the promise to be rejected. So, when you call reject() the exception value is undefined, hence the "undefined" part in the error that you get.

You do not show the code that uses the promise, but I reckon it is something like this:

var promise = doSth();
promise.then(function() { doSthHere(); });

Try adding an empty failure call, like this:

promise.then(function() { doSthHere(); }, function() {});

This will prevent the error to appear.

However, I would consider calling reject only in case of an actual error, and also... having empty exception handlers isn't the best programming practice.

$(document).ready(function() is not working

I have same issue ... at http://www.xaluan.com .. but after log. I find out that after jQuery run I make a function using one element id which not exists ..

Eg:

$('#aaa').remove()  <span class="aaa">sss</spam> 

so the id="aaa" did not exist .. then jQuery stops running.. because errors like that

How to use regex in String.contains() method in Java

As of Java 11 one can use Pattern#asMatchPredicate which returns Predicate<String>.

String string = "stores%store%product";
String regex = "stores.*store.*product.*";
Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();

boolean match = matchesRegex.test(string);                   // true

The method enables chaining with other String predicates, which is the main advantage of this method as long as the Predicate offers and, or and negate methods.

String string = "stores$store$product";
String regex = "stores.*store.*product.*";

Predicate<String> matchesRegex = Pattern.compile(regex).asMatchPredicate();
Predicate<String> hasLength = s -> s.length() > 20;

boolean match = hasLength.and(matchesRegex).test(string);    // false

How to split the name string in mysql?

DELIMITER $$

DROP FUNCTION IF EXISTS `split_name`$$

CREATE FUNCTION split_name (p_fullname TEXT, p_part INTEGER)
RETURNS TEXT
    READS SQL DATA
BEGIN
    DECLARE v_words INT UNSIGNED;
    DECLARE v_name TEXT;

    SET p_fullname=RTRIM(LTRIM(p_fullname));

    SET v_words=(SELECT SUM(LENGTH(p_fullname) - LENGTH(REPLACE(p_fullname, ' ', ''))+1));

    IF v_words=1 THEN 
        IF p_part=1 THEN
            SET v_name=p_fullname;
        ELSEIF p_part=2 THEN
            SET v_name=NULL;
        ELSEIF p_part=3 THEN
            SET v_name=NULL;
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words=2 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET v_name=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
        ELSEIF p_part=3 THEN
            SET v_name=NULL;
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words=3 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1);
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=3 THEN
            SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
            SET v_name=REVERSE(p_fullname);
        ELSE
            SET v_name=NULL;
        END IF; 
    ELSEIF v_words>3 THEN 
        IF p_part=1 THEN
            SET v_name=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
        ELSEIF p_part=2 THEN
            SET p_fullname=REVERSE(SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, LOCATE(' ', p_fullname,SUBSTRING_INDEX(p_fullname,' ',1)+1) + 1);
            SET v_name=REVERSE(p_fullname);
        ELSEIF p_part=3 THEN
            SET p_fullname=REVERSE (SUBSTRING(p_fullname, LOCATE(' ', p_fullname) + 1));
            SET p_fullname=SUBSTRING(p_fullname, 1, LOCATE(' ', p_fullname) - 1);
            SET v_name=REVERSE(p_fullname);
        ELSE
            SET v_name=NULL;
        END IF;
    ELSE
        SET v_name=NULL;
    END IF;
 RETURN v_name; 
END;

SELECT split_name('Md. Obaidul Haque Sarker',1) AS first_name,
split_name('Md. Obaidul Haque Sarker',2) AS middle_name,
split_name('Md. Obaidul Haque Sarker',3) AS last_name

How to make div appear in front of another?

Upper div use higher z-index and lower div use lower z-index then use absolute/fixed/relative position

"Object doesn't support this property or method" error in IE11

Add the code snippet in JS file used in master page or used globally.

<script language="javascript">
if (typeof browseris !== 'undefined') {
    browseris.ie = false;
}
</script>

For more information refer blog: http://blogs2share.blogspot.in/2016/11/object-doesnt-support-property-or.html

Getting all types that implement an interface

I appreciate this is a very old question but I thought I would add another answer for future users as all the answers to date use some form of Assembly.GetTypes.

Whilst GetTypes() will indeed return all types, it does not necessarily mean you could activate them and could thus potentially throw a ReflectionTypeLoadException.

A classic example for not being able to activate a type would be when the type returned is derived from base but base is defined in a different assembly from that of derived, an assembly that the calling assembly does not reference.

So say we have:

Class A // in AssemblyA
Class B : Class A, IMyInterface // in AssemblyB
Class C // in AssemblyC which references AssemblyB but not AssemblyA

If in ClassC which is in AssemblyC we then do something as per accepted answer:

var type = typeof(IMyInterface);
var types = AppDomain.CurrentDomain.GetAssemblies()
    .SelectMany(s => s.GetTypes())
    .Where(p => type.IsAssignableFrom(p));

Then it will throw a ReflectionTypeLoadException.

This is because without a reference to AssemblyA in AssemblyC you would not be able to:

var bType = typeof(ClassB);
var bClass = (ClassB)Activator.CreateInstance(bType);

In other words ClassB is not loadable which is something that the call to GetTypes checks and throws on.

So to safely qualify the result set for loadable types then as per this Phil Haacked article Get All Types in an Assembly and Jon Skeet code you would instead do something like:

public static class TypeLoaderExtensions {
    public static IEnumerable<Type> GetLoadableTypes(this Assembly assembly) {
        if (assembly == null) throw new ArgumentNullException("assembly");
        try {
            return assembly.GetTypes();
        } catch (ReflectionTypeLoadException e) {
            return e.Types.Where(t => t != null);
        }
    }
}

And then:

private IEnumerable<Type> GetTypesWithInterface(Assembly asm) {
    var it = typeof (IMyInterface);
    return asm.GetLoadableTypes().Where(it.IsAssignableFrom).ToList();
}

How to close form

Your closing your instance of the settings window right after you create it. You need to display the settings window first then wait for a dialog result. If it comes back as canceled then close the window. For Example:

private void button1_Click(object sender, EventArgs e)
{
    Settings newSettingsWindow = new Settings();

    if (newSettingsWindow.ShowDialog() == DialogResult.Cancel)
    {
        newSettingsWindow.Close();
    }
}

How can I remove a key and its value from an associative array?

You may need two or more loops depending on your array:

$arr[$key1][$key2][$key3]=$value1; // ....etc

foreach ($arr as $key1 => $values) {
  foreach ($key1 as $key2 => $value) {
  unset($arr[$key1][$key2]);
  }
}

is it possible to update UIButton title/text programmatically?

I kept having problems with this, the only solution was to add an image and label as subviews to the uibutton. Then I discovered that the main problem was that I was using a UIButton with title: Attributed. When I changed it to Plain, just setting the titleLabel.text did the trick!

how to convert java string to Date object

var startDate = "06/27/2007";
startDate = new Date(startDate);

console.log(startDate);

How to show PIL Image in ipython notebook

Use IPython display to render PIL images in a notebook.

from PIL import Image               # to load images
from IPython.display import display # to display images

pil_im = Image.open('path/to/image.jpg')
display(pil_im)

Get bottom and right position of an element

// Returns bottom offset value + or - from viewport top
function offsetBottom(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().bottom }

// Returns right offset value
function offsetRight(el, i) { i = i || 0; return $(el)[i].getBoundingClientRect().right }

var bottom = offsetBottom('#logo');
var right = offsetRight('#logo');

This will find the distance from the top and left of your viewport to your element's exact edge and nothing beyond that. So say your logo was 350px and it had a left margin of 50px, variable 'right' will hold a value of 400 because that's the actual distance in pixels it took to get to the edge of your element, no matter if you have more padding or margin to the right of it.

If your box-sizing CSS property is set to border-box it will continue to work just as if it were set as the default content-box.

How to sort List<Integer>?

To sort in ascending order :

Collections.sort(lList);

And for reverse order :

Collections.reverse(lList);

Change the value in app.config file dynamically

Expanding on Adis H's example to include the null case (got bit on this one)

 Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            if (config.AppSettings.Settings["HostName"] != null)
                config.AppSettings.Settings["HostName"].Value = hostName;
            else                
                config.AppSettings.Settings.Add("HostName", hostName);                
            config.Save(ConfigurationSaveMode.Modified);
            ConfigurationManager.RefreshSection("appSettings");

RESTful Authentication

That's the way to do that: Using OAuth 2.0 for Login.

You may use other authentication methods other then Google's as long as it supports OAuth.

Convert Variable Name to String?

TL;DR: Not possible. See 'conclusion' at the end.


There is an usage scenario where you might need this. I'm not implying there are not better ways or achieving the same functionality.

This would be useful in order to 'dump' an arbitrary list of dictionaries in case of error, in debug modes and other similar situations.

What would be needed, is the reverse of the eval() function:

get_indentifier_name_missing_function()

which would take an identifier name ('variable','dictionary',etc) as an argument, and return a string containing the identifier’s name.


Consider the following current state of affairs:

random_function(argument_data)

If one is passing an identifier name ('function','variable','dictionary',etc) argument_data to a random_function() (another identifier name), one actually passes an identifier (e.g.: <argument_data object at 0xb1ce10>) to another identifier (e.g.: <function random_function at 0xafff78>):

<function random_function at 0xafff78>(<argument_data object at 0xb1ce10>)

From my understanding, only the memory address is passed to the function:

<function at 0xafff78>(<object at 0xb1ce10>)

Therefore, one would need to pass a string as an argument to random_function() in order for that function to have the argument's identifier name:

random_function('argument_data')

Inside the random_function()

def random_function(first_argument):

, one would use the already supplied string 'argument_data' to:

  1. serve as an 'identifier name' (to display, log, string split/concat, whatever)

  2. feed the eval() function in order to get a reference to the actual identifier, and therefore, a reference to the real data:

    print("Currently working on", first_argument)
    some_internal_var = eval(first_argument)
    print("here comes the data: " + str(some_internal_var))
    

Unfortunately, this doesn't work in all cases. It only works if the random_function() can resolve the 'argument_data' string to an actual identifier. I.e. If argument_data identifier name is available in the random_function()'s namespace.

This isn't always the case:

# main1.py
import some_module1

argument_data = 'my data'

some_module1.random_function('argument_data')


# some_module1.py
def random_function(first_argument):
    print("Currently working on", first_argument)
    some_internal_var = eval(first_argument)
    print("here comes the data: " + str(some_internal_var))
######

Expected results would be:

Currently working on: argument_data
here comes the data: my data

Because argument_data identifier name is not available in the random_function()'s namespace, this would yield instead:

Currently working on argument_data
Traceback (most recent call last):
  File "~/main1.py", line 6, in <module>
    some_module1.random_function('argument_data')
  File "~/some_module1.py", line 4, in random_function
    some_internal_var = eval(first_argument)
  File "<string>", line 1, in <module>
NameError: name 'argument_data' is not defined

Now, consider the hypotetical usage of a get_indentifier_name_missing_function() which would behave as described above.

Here's a dummy Python 3.0 code: .

# main2.py
import some_module2
some_dictionary_1       = { 'definition_1':'text_1',
                            'definition_2':'text_2',
                            'etc':'etc.' }
some_other_dictionary_2 = { 'key_3':'value_3',
                            'key_4':'value_4', 
                            'etc':'etc.' }
#
# more such stuff
#
some_other_dictionary_n = { 'random_n':'random_n',
                            'etc':'etc.' }

for each_one_of_my_dictionaries in ( some_dictionary_1,
                                     some_other_dictionary_2,
                                     ...,
                                     some_other_dictionary_n ):
    some_module2.some_function(each_one_of_my_dictionaries)


# some_module2.py
def some_function(a_dictionary_object):
    for _key, _value in a_dictionary_object.items():
        print( get_indentifier_name_missing_function(a_dictionary_object)    +
               "    " +
               str(_key) +
               "  =  " +
               str(_value) )
######

Expected results would be:

some_dictionary_1    definition_1  =  text_1
some_dictionary_1    definition_2  =  text_2
some_dictionary_1    etc  =  etc.
some_other_dictionary_2    key_3  =  value_3
some_other_dictionary_2    key_4  =  value_4
some_other_dictionary_2    etc  =  etc.
......
......
......
some_other_dictionary_n    random_n  =  random_n
some_other_dictionary_n    etc  =  etc.

Unfortunately, get_indentifier_name_missing_function() would not see the 'original' identifier names (some_dictionary_,some_other_dictionary_2,some_other_dictionary_n). It would only see the a_dictionary_object identifier name.

Therefore the real result would rather be:

a_dictionary_object    definition_1  =  text_1
a_dictionary_object    definition_2  =  text_2
a_dictionary_object    etc  =  etc.
a_dictionary_object    key_3  =  value_3
a_dictionary_object    key_4  =  value_4
a_dictionary_object    etc  =  etc.
......
......
......
a_dictionary_object    random_n  =  random_n
a_dictionary_object    etc  =  etc.

So, the reverse of the eval() function won't be that useful in this case.


Currently, one would need to do this:

# main2.py same as above, except:

    for each_one_of_my_dictionaries_names in ( 'some_dictionary_1',
                                               'some_other_dictionary_2',
                                               '...',
                                               'some_other_dictionary_n' ):
        some_module2.some_function( { each_one_of_my_dictionaries_names :
                                     eval(each_one_of_my_dictionaries_names) } )
    
    
    # some_module2.py
    def some_function(a_dictionary_name_object_container):
        for _dictionary_name, _dictionary_object in a_dictionary_name_object_container.items():
            for _key, _value in _dictionary_object.items():
                print( str(_dictionary_name) +
                       "    " +
                       str(_key) +
                       "  =  " +
                       str(_value) )
    ######

In conclusion:

  • Python passes only memory addresses as arguments to functions.
  • Strings representing the name of an identifier, can only be referenced back to the actual identifier by the eval() function if the name identifier is available in the current namespace.
  • A hypothetical reverse of the eval() function, would not be useful in cases where the identifier name is not 'seen' directly by the calling code. E.g. inside any called function.
  • Currently one needs to pass to a function:
    1. the string representing the identifier name
    2. the actual identifier (memory address)

This can be achieved by passing both the 'string' and eval('string') to the called function at the same time. I think this is the most 'general' way of solving this egg-chicken problem across arbitrary functions, modules, namespaces, without using corner-case solutions. The only downside is the use of the eval() function which may easily lead to unsecured code. Care must be taken to not feed the eval() function with just about anything, especially unfiltered external-input data.

How do you write a migration to rename an ActiveRecord model and its table in Rails?

In Rails 4 all I had to do was the def change

def change
  rename_table :old_table_name, :new_table_name
end

And all of my indexes were taken care of for me. I did not need to manually update the indexes by removing the old ones and adding new ones.

And it works using the change for going up or down in regards to the indexes as well.

Difference between Encapsulation and Abstraction

Just a few more points to make thing clear,

One must not confuse data abstraction and the abstract class. They are different.

Generally we say abstract class or method is to basically hide something. But no.. That is wrong. What is the word abstract means ? Google search says the English word abstraction means

"Existing in thought or as an idea but not having a physical or concrete existence."

And thats right in case of abstract class too. It is not hiding the content of the method but the method's content is already empty (not having a physical or concrete existence) but it determines how a method should be (existing in thought or as an idea) or a method should be in the calss.

So when do you actually use abstract methods ?

  • When a method from base class will differ in each child class that extends it.
  • And so you want to make sure the child class have this function implemented.
  • This also ensures that method, to have compulsory signature like, it must have n number of parameters.

So about abstract class! - An Abstract class cannot be instantiated only extended! But why ?

  • A class with abstract method must be prevented from creating its own instance because the abstract methods in it, are not having any meaningful implementation.
  • You can even make a class abstract, if for some reason you find that it is meaning less to have a instance of your that class.

An Abstract class help us avoid creating new instance of it!

An abstract method in a class forces the child class to implement that function for sure with the provided signature!

How to split one string into multiple variables in bash shell?

read with IFS are perfect for this:

$ IFS=- read var1 var2 <<< ABCDE-123456
$ echo "$var1"
ABCDE
$ echo "$var2"
123456

Edit:

Here is how you can read each individual character into array elements:

$ read -a foo <<<"$(echo "ABCDE-123456" | sed 's/./& /g')"

Dump the array:

$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]="-" [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'

If there are spaces in the string:

$ IFS=$'\v' read -a foo <<<"$(echo "ABCDE 123456" | sed 's/./&\v/g')"
$ declare -p foo
declare -a foo='([0]="A" [1]="B" [2]="C" [3]="D" [4]="E" [5]=" " [6]="1" [7]="2" [8]="3" [9]="4" [10]="5" [11]="6")'

How to split a string in Ruby and get all items except the first one?

ex.split(',', 2).last

The 2 at the end says: split into 2 pieces, not more.

normally split will cut the value into as many pieces as it can, using a second value you can limit how many pieces you will get. Using ex.split(',', 2) will give you:

["test1", "test2, test3, test4, test5"]

as an array, instead of:

["test1", "test2", "test3", "test4", "test5"]

how to run a winform from console application?

You can create a winform project in VS2005/ VS2008 and then change its properties to be a command line application. It can then be started from the command line, but will still open a winform.

if, elif, else statement issues in Bash

Missing space between elif and [ rest your program is correct. you need to correct it an check it out. here is fixed program:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

useful link related to this bash if else statement

java calling a method from another class

You're very close. What you need to remember is when you're calling a method from another class you need to tell the compiler where to find that method.

So, instead of simply calling addWord("someWord"), you will need to initialise an instance of the WordList class (e.g. WordList list = new WordList();), and then call the method using that (i.e. list.addWord("someWord");.

However, your code at the moment will still throw an error there, because that would be trying to call a non-static method from a static one. So, you could either make addWord() static, or change the methods in the Words class so that they're not static.

My bad with the above paragraph - however you might want to reconsider ProcessInput() being a static method - does it really need to be?

"Invalid form control" only in Google Chrome

$("...").attr("required"); and $("...").removeAttr("required"); 

didn't work for me until I putted all my jQuery code between that:

$(document).ready(function() {
    //jQuery code goes here
});

How to replace text in a column of a Pandas dataframe?

Replace all commas with underscore in the column names

data.columns= data.columns.str.replace(' ','_',regex=True)

How to remove Left property when position: absolute?

In the future one would use left: unset; for unsetting the value of left.

As of today 4 nov 2014 unset is only supported in Firefox.

Read more about unset in MDN.

My guess is we'll be able to use it around year 2022 when IE 11 is properly phased out.

How to escape "&" in XML?

'&' --> '&amp;'

'<' --> '&lt;'

'>' --> '&gt;'

There are no primary or candidate keys in the referenced table that match the referencing column list in the foreign key

You need either

  • A unique index on Title in BookTitle
  • An ISBN column in BookCopy and the FK is on both columns

A foreign key needs to uniquely identify the parent row: you currently have no way to do that because Title is not unique.

$(this).attr("id") not working

your using this in a function, when you should be using the parameter.

You only use $(this) in callbacks... from selections like

$('a').click(function() {
   alert($(this).href);
})

In closing, the proper way (using your code example) would be to do this

obj.attr('id');

Split a List into smaller lists of N size

List<int> orginalList =new List<int>(){1,2,3,4,5,6,7,8,9,10,12};
Dictionary<int,List<int>> dic = new Dictionary <int,List<int>> ();
int batchcount = orginalList.Count/2; //To List into two 2 parts if you 
 want three give three
List<int> lst = new List<int>();
for (int i=0;i<orginalList.Count; i++)
{
lst.Add(orginalList[i]);
if (i % batchCount == 0 && i!=0)
{
Dic.Add(threadId, lst);
lst = new List<int>();**strong text**
threadId++;
}
}
if(lst.Count>0)
Dic.Add(threadId, lst); //in case if any dayleft 
foreach(int BatchId in Dic.Keys)
{
  Console.Writeline("BatchId:"+BatchId);
  Console.Writeline('Batch Count:"+Dic[BatchId].Count);
}

Sublime Text 2: How do I change the color that the row number is highlighted?

The easy way: Pick an alternative Color Scheme:

Preferences > Color Scheme > ...pick one

The more complicated way: Edit the current color scheme file:

Preferences > Browse Packages > Color Scheme - Default > ... edit the Color Scheme file you are using:

Looking at the structure of the XML, drill down into dict > settings > settings > dict >

Look for the key (or add it if it's missing): lineHighlight. Add a string with an #RRGGBB or #RRGGBBAA format.

Simultaneously merge multiple data.frames in a list

You can do it using merge_all in the reshape package. You can pass parameters to merge using the ... argument

reshape::merge_all(list_of_dataframes, ...)

Here is an excellent resource on different methods to merge data frames.

Android SDK location should not contain whitespace, as this cause problems with NDK tools

Just change

C:\Users\Giacomo B\AppData\Local\Android\sdk

to

C:\Users\Giacomo_B\AppData\Local\Android\sdk

Trying to use Spring Boot REST to Read JSON String from POST

The issue appears with parsing the JSON from request body, tipical for an invalid JSON. If you're using curl on windows, try escaping the json like -d "{"name":"value"}" or even -d "{"""name""":"value"""}"

On the other hand you can ommit the content-type header in which case whetewer is sent will be converted to your String argument

How to pass command line arguments to a shell alias?

Just to reiterate what has been posted for other shells, in Bash the following works:

alias blah='function _blah(){ echo "First: $1"; echo "Second: $2"; };_blah'

Running the following:

blah one two

Gives the output below:

First: one
Second: two

How to find the UpgradeCode and ProductCode of an installed application in Windows 7

You can use the MsiEnumProductsEx and MsiGetProductInfoEx methods to enumerate all the installed applications on your system and match the data to your application

Multiple parameters in a List. How to create without a class?

If you do not mind the items being imutable you can use the Tuple class added to .net 4

var list = new List<Tuple<string,int>>();
list.Add(new Tuple<string,int>("hello", 1));

list[0].Item1 //Hello
list[0].Item2 //1

However if you are adding two items every time and one of them is unique id you can use a Dictionary

Declare and assign multiple string variables at the same time

Fairly old question but incase someone goes back.
This isn't as compact as the other answers above, but fairly readable and easier to type using Visual Studio Multi-Line selection shortcut [Alt+ Shift + ?] (or other directions)

string Camnr = string.Empty;
string Klantnr = string.Empty;

Type out all variable names on new lines. Multi-Select in front of them an type "string". Multi-Select behind them and type "= string.Empty;".

How can I remove file extension from a website address?

Tony, your script is ok, but if you have 100 files? Need add this code in all these :

include_once('scripts.php');
strip_php_extension();

I think you include a menu in each php file (probably your menu is showed in all your web pages), so you can add these 2 lines of code only in your menu file. This work for me :D

Best way to check if object exists in Entity Framework?

I know this is a very old thread but just incase someone like myself needs this solution but in VB.NET here's what I used base on the answers above.

Private Function ValidateUniquePayroll(PropertyToCheck As String) As Boolean
    // Return true if Username is Unique
    Dim rtnValue = False
    Dim context = New CPMModel.CPMEntities
    If (context.Employees.Any()) Then ' Check if there are "any" records in the Employee table
        Dim employee = From c In context.Employees Select c.PayrollNumber ' Select just the PayrollNumber column to work with
        For Each item As Object In employee ' Loop through each employee in the Employees entity
            If (item = PropertyToCheck) Then ' Check if PayrollNumber in current row matches PropertyToCheck
                // Found a match, throw exception and return False
                rtnValue = False
                Exit For
            Else
                // No matches, return True (Unique)
                rtnValue = True
            End If
        Next
    Else
        // The is currently no employees in the person entity so return True (Unqiue)
        rtnValue = True
    End If
    Return rtnValue
End Function

Date constructor returns NaN in IE, but works in Firefox and Chrome

Here's a code snippet that fixes that behavior of IE (v['date'] is a comma separated date-string, e.g. "2010,4,1"):

if($.browser.msie){
    $.lst = v['date'].split(',');
    $.tmp = new Date(parseInt($.lst[0]),parseInt($.lst[1])-1,parseInt($.lst[2]));
} else {
    $.tmp = new Date(v['date']);
}

The previous approach didn't consider that JS Date month is ZERO based...

Sorry for not explaining too much, I'm at work and just thought this might help.

Convert list of ints to one number?

If you happen to be using numpy (with import numpy as np):

In [24]: x
Out[24]: array([1, 2, 3, 4, 5])

In [25]: np.dot(x, 10**np.arange(len(x)-1, -1, -1))
Out[25]: 12345

Check if any ancestor has a class using jQuery

There are many ways to filter for element ancestors.

if ($elem.closest('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents('.parentClass').length /* > 0*/) {/*...*/}
if ($elem.parents().hasClass('parentClass')) {/*...*/}
if ($('.parentClass').has($elem).length /* > 0*/) {/*...*/}
if ($elem.is('.parentClass *')) {/*...*/} 

Beware, closest() method includes element itself while checking for selector.

Alternatively, if you have a unique selector matching the $elem, e.g #myElem, you can use:

if ($('.parentClass:has(#myElem)').length /* > 0*/) {/*...*/}
if(document.querySelector('.parentClass #myElem')) {/*...*/}

If you want to match an element depending any of its ancestor class for styling purpose only, just use a CSS rule:

.parentClass #myElem { /* CSS property set */ }

How to create table using select query in SQL Server?

select <column list> into <table name> from <source> where <whereclause>

How do I check if an array includes a value in JavaScript?

Adding a unique item to a another list

searchResults: [
                {
                    name: 'Hello',
                    artist: 'Selana',
                    album: 'Riga',
                    id: 1,
                },
                {
                    name: 'Hello;s',
                    artist: 'Selana G',
                    album: 'Riga1',
                    id: 2,
                },
                {
                    name: 'Hello2',
                    artist: 'Selana',
                    album: 'Riga11',
                    id: 3,
                }
            ],
            playlistTracks: [
              {
                name: 'Hello',
                artist: 'Mamunuus',
                album: 'Riga',
                id: 4,
              },
              {
                name: 'Hello;s',
                artist: 'Mamunuus G',
                album: 'Riga1',
                id: 2,
              },
              {
                name: 'Hello2',
                artist: 'Mamunuus New',
                album: 'Riga11',
                id: 3,
              }
            ],
            playlistName: "New PlayListTrack",
        };
    }

    // Adding an unique track in the playList
    addTrack = track => {
      if(playlistTracks.find(savedTrack => savedTrack.id === track.id)) {
        return;
      }
      playlistTracks.push(track);

      this.setState({
        playlistTracks
      })
    };

How to reliably open a file in the same directory as a Python script

I always use:

__location__ = os.path.realpath(
    os.path.join(os.getcwd(), os.path.dirname(__file__)))

The join() call prepends the current working directory, but the documentation says that if some path is absolute, all other paths left of it are dropped. Therefore, getcwd() is dropped when dirname(__file__) returns an absolute path.

Also, the realpath call resolves symbolic links if any are found. This avoids troubles when deploying with setuptools on Linux systems (scripts are symlinked to /usr/bin/ -- at least on Debian).

You may the use the following to open up files in the same folder:

f = open(os.path.join(__location__, 'bundled-resource.jpg'))
# ...

I use this to bundle resources with several Django application on both Windows and Linux and it works like a charm!

Is it possible to send a variable number of arguments to a JavaScript function?

With ES6 you can use rest parameters for varagrs. This takes the argument list and converts it to an array.

function logArgs(...args) {
    console.log(args.length)
    for(let arg of args) {
        console.log(arg)
    }
}

Android Linear Layout - How to Keep Element At Bottom Of View?

You should put the parameter gravity to bottom not in the textview but in the Linear Layout. Like this:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="bottom|end">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Something"/>
</LinearLayout>

Freeing up a TCP/IP port?

To a kill a specific port in Linux use below command

sudo fuser -k Port_Number/tcp

replace Port_Number with your occupied port.

Installing MySQL-python

this worked for me on python 3

pip install mysqlclient

Compare two different files line by line in python

Once the file object is iterated, it is exausted.

>>> f = open('1.txt', 'w')
>>> f.write('1\n2\n3\n')
>>> f.close()
>>> f = open('1.txt', 'r')
>>> for line in f: print line
...
1

2

3

# exausted, another iteration does not produce anything.
>>> for line in f: print line
...
>>>

Use file.seek (or close/open the file) to rewind the file:

>>> f.seek(0)
>>> for line in f: print line
...
1

2

3

Node Version Manager (NVM) on Windows

nvm was designed for Linux. nvmw, which is completely different broke around node v0.10.30. Try NVM for Windows.

How to run a command in the background on Windows?

Use the start command with the /b flag to run a command/application without opening a new window. For example, this runs dotnet run in the background:

start /b dotnet run

You can pass parameters to the command/application too. For example, I'm starting 3 instances of this C# project, with parameter values of x, y, and z:

enter image description here

To stop the program(s) running in the background: CTRL + BREAK

In my experience, this stops all of the background commands/programs you have started in that cmd instance.

According to the Microsoft docs:

CTRL+C handling is ignored unless the application enables CTRL+C processing. Use CTRL+BREAK to interrupt the application.

Eclipse DDMS error "Can't bind to local 8600 for debugger"

For people running Android Studio and Eclipse:

I know that answers are already saturated, but I'll just add that it appears that this error surfaces after installing Android Studio and returning to Eclipse to build and run your project.

Make sure you close all other instances of ADB that may be running (including Android Studio). Once you've done this if you are still having troubles try killing all ADB server processes and restarting. If you haven't setup a global variable, open terminal and navigate to the platform-tools folder of the Android SDK Eclipse is referencing, then run:

./adb kill-server
./adb start-server

Generate a random double in a range

Use this:

double start = 400;
double end = 402;
double random = new Random().nextDouble();
double result = start + (random * (end - start));
System.out.println(result);

EDIT:

new Random().nextDouble(): randomly generates a number between 0 and 1.

start: start number, to shift number "to the right"

end - start: interval. Random gives you from 0% to 100% of this number, because random gives you a number from 0 to 1.


EDIT 2: Tks @daniel and @aaa bbb. My first answer was wrong.

What is the best way to check for Internet connectivity using .NET?

I have seen all the options listed above and the only viable option to check wither the internet is available or not is the "Ping" option. Importing [DllImport("Wininet.dll")] and System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces() Or any other variation of the NetworkInterface class does not work well in detecting the availability of the network.These Methods only check if the network cable is plugged in or not.

The "Ping option"

if(Connection is available) returns true

if(Connection is not available and the network cable is plugged in) returns false

if(Network cable is not plugged in) Throws an exception

The NetworkInterface

if(Internet Is available)Returns True

if(Internet is not Available and Network Cable is Plugged in ) Returns True

if(Network Cable is Not Plugged in )returns false

The [DllImport("Wininet.dll")]

if(Internet Is available)Returns True

if(Internet is not Available and Network Cable is Plugged in ) Returns True

if(Network Cable is Not Plugged in )returns false

So in case of [DllImport("Wininet.dll")] and NetworkInterface There is no way of knowing if internet connection is available.

jQuery - determine if input element is textbox or select list

You could do this:

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input
}

or this, which is slower, but shorter and cleaner:

if( ctrl.is('input') ) {
    // it was an input
}

If you want to be more specific, you can test the type:

if( ctrl.is('input:text') ) {
    // it was an input
}

Make Adobe fonts work with CSS3 @font-face in IE9

As a Mac user, I was unable to use the MS-DOS and Windows command line tools that were mentioned to fix the font embedding permission. However, I found out that you can fix this using FontLab to set the permission to 'Everything is allowed'. I hope this recipe on how to set the font permission to Installable on Mac OS X is useful for others as well.

How to handle anchor hash linking in AngularJS

<a href="/#/#faq-1">Question 1</a>
<a href="/#/#faq-2">Question 2</a>
<a href="/#/#faq-3">Question 3</a>

Response.Redirect with POST instead of Get?

I suggest building an HttpWebRequest to programmatically execute your POST and then redirect after reading the Response if applicable.

How can I keep my branch up to date with master with git?

Assuming you're fine with taking all of the changes in master, what you want is:

git checkout <my branch>

to switch the working tree to your branch; then:

git merge master

to merge all the changes in master with yours.

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

CSS: Set a background color which is 50% of the width of the window

Use on your image bg

Vertical split

background-size: 50% 100%

Horizontal split

background-size: 100% 50%

Example

.class {
   background-image: url("");
   background-color: #fff;
   background-repeat: no-repeat;
   background-size: 50% 100%;
}

Accessing an array out of bounds gives no error, why?

C or C++ will not check the bounds of an array access.

You are allocating the array on the stack. Indexing the array via array[3] is equivalent to *(array + 3), where array is a pointer to &array[0]. This will result in undefined behavior.

One way to catch this sometimes in C is to use a static checker, such as splint. If you run:

splint +bounds array.c

on,

int main(void)
{
    int array[1];

    array[1] = 1;

    return 0;
}

then you will get the warning:

array.c: (in function main) array.c:5:9: Likely out-of-bounds store: array[1] Unable to resolve constraint: requires 0 >= 1 needed to satisfy precondition: requires maxSet(array @ array.c:5:9) >= 1 A memory write may write to an address beyond the allocated buffer.

How to edit Docker container files from the host?

The way I am doing is using Emacs with docker package installed. I would recommend Spacemacs version of Emacs. I would follow the following steps:

1) Install Emacs (Instruction) and install Spacemacs (Instruction)

2) Add docker in your .spacemacs file

3) Start Emacs

4) Find file (SPC+f+f) and type /docker:<container-id>:/<path of dir/file in the container>

5) Now your emacs will use the container environment to edit the files