Programs & Examples On #Amazon ebs

Amazon Elastic Block Store (EBS) provides block level storage volumes for use with Amazon EC2 instances. Amazon EBS volumes are off-instance storage that persists independently from the life of an instance.

AWS EFS vs EBS vs S3 (differences & when to use?)

Fixing the comparison:

  • S3 is a storage facility accessible any where
  • EBS is a device you can mount onto EC2
  • EFS is a file system you can mount onto several EC2 instances at the same time

At this point it's a little premature to compare EFS and EBS- the performance of EFS isn't known, nor is its reliability known.

Why would you use S3?

  • You don't have a need for the files to be 'local' to one or more EC2 instances.
  • (effectively) infinite capacity
  • built-in web serving, authentication

Benefits of EBS vs. instance-store (and vice-versa)

EBS is like the virtual disk of a VM:

  • Durable, instances backed by EBS can be freely started and stopped (saving money)
  • Can be snapshotted at any point in time, to get point-in-time backups
  • AMIs can be created from EBS snapshots, so the EBS volume becomes a template for new systems

Instance storage is:

  • Local, so generally faster
  • Non-networked, in normal cases EBS I/O comes at the cost of network bandwidth (except for EBS-optimized instances, which have separate EBS bandwidth)
  • Has limited I/O per second IOPS. Even provisioned I/O maxes out at a few thousand IOPS
  • Fragile. As soon as the instance is stopped, you lose everything in instance storage.

Here's where to use each:

  • Use EBS for the backing OS partition and permanent storage (DB data, critical logs, application config)
  • Use instance storage for in-process data, noncritical logs, and transient application state. Example: external sort storage, tempfiles, etc.
  • Instance storage can also be used for performance-critical data, when there's replication between instances (NoSQL DBs, distributed queue/message systems, and DBs with replication)
  • Use S3 for data shared between systems: input dataset and processed results, or for static data used by each system when lauched.
  • Use AMIs for prebaked, launchable servers

What data is stored in Ephemeral Storage of Amazon EC2 instance?

ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store

So Everything will be stored on ephemeral.

if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.

How to view kafka message

Use the Kafka consumer provided by Kafka :

bin/kafka-console-consumer.sh --bootstrap-server BROKERS --topic TOPIC_NAME

It will display the messages as it will receive it. Add --from-beginning if you want to start from the beginning.

What is the difference between % and %% in a cmd file?

(Explanation in more details can be found in an archived Microsoft KB article.)

Three things to know:

  1. The percent sign is used in batch files to represent command line parameters: %1, %2, ...
  2. Two percent signs with any characters in between them are interpreted as a variable:

    echo %myvar%

  3. Two percent signs without anything in between (in a batch file) are treated like a single percent sign in a command (not a batch file): %%f

Why's that?

For example, if we execute your (simplified) command line

FOR /f %f in ('dir /b .') DO somecommand %f

in a batch file, rule 2 would try to interpret

%f in ('dir /b .') DO somecommand %

as a variable. In order to prevent that, you have to apply rule 3 and escape the % with an second %:

FOR /f %%f in ('dir /b .') DO somecommand %%f

Reload an iframe with jQuery

Here is another way

$( '#iframe' ).attr( 'src', function () { return $( this )[0].src; } );

How to re-sync the Mysql DB if Master and slave have different database incase of Mysql replication?

Adding to the popular answer to include this error:

"ERROR 1200 (HY000): The server is not configured as slave; fix in config file or with CHANGE MASTER TO",

Replication from slave in one shot:

In one terminal window:

mysql -h <Master_IP_Address> -uroot -p

After connecting,

RESET MASTER;
FLUSH TABLES WITH READ LOCK;
SHOW MASTER STATUS;

The status appears as below: Note that position number varies!

+------------------+----------+--------------+------------------+
| File             | Position | Binlog_Do_DB | Binlog_Ignore_DB |
+------------------+----------+--------------+------------------+
| mysql-bin.000001 |      98  | your_DB      |                  |
+------------------+----------+--------------+------------------+

Export the dump similar to how he described "using another terminal"!

Exit and connect to your own DB(which is the slave):

mysql -u root -p

The type the below commands:

STOP SLAVE;

Import the Dump as mentioned (in another terminal, of course!) and type the below commands:

RESET SLAVE;
CHANGE MASTER TO 
  MASTER_HOST = 'Master_IP_Address', 
  MASTER_USER = 'your_Master_user', // usually the "root" user
  MASTER_PASSWORD = 'Your_MasterDB_Password', 
  MASTER_PORT = 3306, 
  MASTER_LOG_FILE = 'mysql-bin.000001', 
  MASTER_LOG_POS = 98; // In this case

Once logged, set the server_id parameter (usually, for new / non-replicated DBs, this is not set by default),

set global server_id=4000;

Now, start the slave.

START SLAVE;
SHOW SLAVE STATUS\G;

The output should be the same as he described.

  Slave_IO_Running: Yes
  Slave_SQL_Running: Yes

Note: Once replicated, the master and slave share the same password!

Data truncation: Data too long for column 'logo' at row 1

You are trying to insert data that is larger than allowed for the column logo.

Use following data types as per your need

TINYBLOB   :     maximum length of 255 bytes  
BLOB       :     maximum length of 65,535 bytes  
MEDIUMBLOB :     maximum length of 16,777,215 bytes  
LONGBLOB   :     maximum length of 4,294,967,295 bytes  

Use LONGBLOB to avoid this exception.

sed edit file in place

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

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

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

See it live:

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

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

The redirection operator

[n]<>word

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

How do you stash an untracked file?

There are several correct answers here, but I wanted to point out that for new entire directories, 'git add path' will NOT work. So if you have a bunch of new files in untracked-path and do this:

git add untracked-path
git stash "temp stash"

this will stash with the following message:

Saved working directory and index state On master: temp stash
warning: unable to rmdir untracked-path: Directory not empty

and if untracked-path is the only path you're stashing, the stash "temp stash" will be an empty stash. Correct way is to add the entire path, not just the directory name (i.e. end the path with a '/'):

git add untracked-path/
git stash "temp stash"

Branch from a previous commit using Git

git checkout -b <branch-name> <sha1-of-commit>

Work with a time span in Javascript

a simple timestamp formatter in pure JS with custom patterns support and locale-aware, using Intl.RelativeTimeFormat

some formatting examples

/** delta: 1234567890, @locale: 'en-US', @style: 'long' */

/* D~ h~ m~ s~ */
14 days 6 hours 56 minutes 7 seconds

/* D~ h~ m~ s~ f~ */
14 days 6 hours 56 minutes 7 seconds 890

/* D#"d" h#"h" m#"m" s#"s" f#"ms" */
14d 6h 56m 7s 890ms

/* D,h:m:s.f */
14,06:56:07.890

/* D~, h:m:s.f */
14 days, 06:56:07.890

/* h~ m~ s~ */
342 hours 56 minutes 7 seconds

/* s~ m~ h~ D~ */
7 seconds 56 minutes 6 hours 14 days

/* up D~, h:m */
up 14 days, 06:56

the code & test

_x000D_
_x000D_
/**
    Init locale formatter:
    
        timespan.locale(@locale, @style)
    
    Example:

        timespan.locale('en-US', 'long');
        timespan.locale('es', 'narrow');

    Format time delta:
    
        timespan.format(@pattern, @milliseconds)

        @pattern tokens:
            D: days, h: hours, m: minutes, s: seconds, f: millis

        @pattern token extension:
            h  => '0'-padded value, 
            h# => raw value,
            h~ => locale formatted value

    Example:

        timespan.format('D~ h~ m~ s~ f "millis"', 1234567890);
        
        output: 14 days 6 hours 56 minutes 7 seconds 890 millis

    NOTES:

    * milliseconds unit have no locale translation
    * may encounter declension issues for some locales
    * use quoted text for raw inserts
            
*/

const timespan = (() => {
    let rtf, tokensRtf;
    const
    tokens = /[Dhmsf][#~]?|"[^"]*"|'[^']*'/g,
    map = [
        {t: [['D', 1], ['D#'], ['D~', 'day']], u: 86400000},
        {t: [['h', 2], ['h#'], ['h~', 'hour']], u: 3600000},
        {t: [['m', 2], ['m#'], ['m~', 'minute']], u: 60000},
        {t: [['s', 2], ['s#'], ['s~', 'second']], u: 1000},
        {t: [['f', 3], ['f#'], ['f~']], u: 1}
    ],
    locale = (value, style = 'long') => {
        try {
            rtf = new Intl.RelativeTimeFormat(value, {style});
        } catch (e) {
            if (rtf) throw e;
            return;
        }
        const h = rtf.format(1, 'hour').split(' ');
        tokensRtf = new Set(rtf.format(1, 'day').split(' ')
            .filter(t => t != 1 && h.indexOf(t) > -1));
        return true;
    },
    fallback = (t, u) => u + ' ' + t.fmt + (u == 1 ? '' : 's'),
    mapper = {
        number: (t, u) => (u + '').padStart(t.fmt, '0'),
        string: (t, u) => rtf ? rtf.format(u, t.fmt).split(' ')
            .filter(t => !tokensRtf.has(t)).join(' ')
            .trim().replace(/[+-]/g, '') : fallback(t, u),
    },
    replace = (out, t) => out[t] || t.slice(1, t.length - 1),
    format = (pattern, value) => {
        if (typeof pattern !== 'string')
            throw Error('invalid pattern');
        if (!Number.isFinite(value))
            throw Error('invalid value');
        if (!pattern)
            return '';
        const out = {};
        value = Math.abs(value);
        pattern.match(tokens)?.forEach(t => out[t] = null);
        map.forEach(m => {
            let u = null;
            m.t.forEach(t => {
                if (out[t.token] !== null)
                    return;
                if (u === null) {
                    u = Math.floor(value / m.u);
                    value %= m.u;
                }
                out[t.token] = '' + (t.fn ? t.fn(t, u) : u);
            })
        });
        return pattern.replace(tokens, replace.bind(null, out));
    };
    map.forEach(m => m.t = m.t.map(t => ({
        token: t[0], fmt: t[1], fn: mapper[typeof t[1]]
    })));
    locale('en');
    return {format, locale};
})();


/************************** test below *************************/

const
cfg = {
  locale: 'en,de,nl,fr,it,es,pt,ro,ru,ja,kor,zh,th,hi',
  style: 'long,narrow'
},
el = id => document.getElementById(id),
locale = el('locale'), loc = el('loc'), style = el('style'),
fd = new Date(), td = el('td'), fmt = el('fmt'),
run = el('run'), out = el('out'),
test = () => {
  try {
      const tv = new Date(td.value);
      if (isNaN(tv)) throw Error('invalid "datetime2" value');
      timespan.locale(loc.value || locale.value, style.value);
      const delta = fd.getTime() - tv.getTime();
      out.innerHTML = timespan.format(fmt.value, delta);
  } catch (e) { out.innerHTML = e.message; }
};
el('fd').innerText = el('td').value = fd.toISOString();
el('fmt').value = 'D~ h~ m~ s~ f~ "ms"';
for (const [id, value] of Object.entries(cfg)) {
  const elm = el(id);
  value.split(',').forEach(i => elm.innerHTML += `<option>${i}</option>`);
}
_x000D_
i {color:green}
_x000D_
locale: <select id="locale"></select>
custom: <input id="loc" style="width:8em"><br>
style: <select id="style"></select><br>
datetime1: <i id="fd"></i><br>
datetime2: <input id="td"><br>
pattern: <input id="fmt">
<button id="run" onclick="test()">test</button><br><br>
<i id="out"></i>
_x000D_
_x000D_
_x000D_

Good PHP ORM Library?

I am currently working on phpDataMapper, which is an ORM designed to have simple syntax like Ruby's Datamapper project. It's still in early development as well, but it works great.

What's wrong with foreign keys?

"They can make deleting records more cumbersome - you can't delete the "master" record where there are records in other tables where foreign keys would violate that constraint."

It's important to remember that the SQL standard defines actions that are taken when a foreign key is deleted or updated. The ones I know of are:

  • ON DELETE RESTRICT - Prevents any rows in the other table that have keys in this column from being deleted. This is what Ken Ray described above.
  • ON DELETE CASCADE - If a row in the other table is deleted, delete any rows in this table that reference it.
  • ON DELETE SET DEFAULT - If a row in the other table is deleted, set any foreign keys referencing it to the column's default.
  • ON DELETE SET NULL - If a row in the other table is deleted, set any foreign keys referencing it in this table to null.
  • ON DELETE NO ACTION - This foreign key only marks that it is a foreign key; namely for use in OR mappers.

These same actions also apply to ON UPDATE.

The default seems to depend on which server you're using.

How do I enable index downloads in Eclipse for Maven dependency search?

  1. In Eclipse, click on Windows > Preferences, and then choose Maven in the left side.
  2. Check the box "Download repository index updates on startup".
    • Optionally, check the boxes Download Artifact Sources and Download Artifact JavaDoc.
  3. Click OK. The warning won't appear anymore.
  4. Restart Eclipse.

http://i.imgur.com/IJ2T3vc.png

Best way to check function arguments?

One way is to use assert:

def myFunction(a,b,c):
    "This is an example function I'd like to check arguments of"
    assert isinstance(a, int), 'a should be an int'
    # or if you want to allow whole number floats: assert int(a) == a
    assert b > 0 and b < 10, 'b should be betwen 0 and 10'
    assert isinstance(c, str) and c, 'c should be a non-empty string'

how to use a like with a join in sql?

If this is something you'll need to do often...then you may want to denormalize the relationship between tables A and B.

For example, on insert to table B, you could write zero or more entries to a juncion table mapping B to A based on partial mapping. Similarly, changes to either table could update this association.

This all depends on how frequently tables A and B are modified. If they are fairly static, then taking a hit on INSERT is less painful then repeated hits on SELECT.

C# static class why use?

Making a class static just prevents people from trying to make an instance of it. If all your class has are static members it is a good practice to make the class itself static.

How to markdown nested list items in Bitbucket?

4 spaces do the trick even inside definition list:

Endpoint
: `/listAgencies`

Method
: `GET`

Arguments
:   * `level` - bla-bla.
    * `withDisabled` - should we include disabled `AGENT`s.
    * `userId` - bla-bla.

I am documenting API using BitBucket Wiki and Markdown proprietary extension for definition list is most pleasing (MD's table syntax is awful, imaging multiline and embedding requirements...).

How can I call a function using a function pointer?

I think your question has already been answered more than adequately, but it might be useful to point out explicitly that given a function pointer

void (*pf)(int foo, int bar);

the two calls

pf(1, 0);
(*pf)(1, 0);

are exactly equivalent in every way by definition. The choice of which to use is up to you, although it's a good idea to be consistent. For a long time, I preferred (*pf)(1, 0) because it seemed to me that it better reflected the type of pf, however in the last few years I've switched to pf(1, 0).

Change text color with Javascript?

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

Do the parentheses after the type name make a difference with new?

Let's get pedantic, because there are differences that can actually affect your code's behavior. Much of the following is taken from comments made to an "Old New Thing" article.

Sometimes the memory returned by the new operator will be initialized, and sometimes it won't depending on whether the type you're newing up is a POD (plain old data), or if it's a class that contains POD members and is using a compiler-generated default constructor.

  • In C++1998 there are 2 types of initialization: zero and default
  • In C++2003 a 3rd type of initialization, value initialization was added.

Assume:

struct A { int m; }; // POD
struct B { ~B(); int m; }; // non-POD, compiler generated default ctor
struct C { C() : m() {}; ~C(); int m; }; // non-POD, default-initialising m

In a C++98 compiler, the following should occur:

  • new A - indeterminate value
  • new A() - zero-initialize

  • new B - default construct (B::m is uninitialized)

  • new B() - default construct (B::m is uninitialized)

  • new C - default construct (C::m is zero-initialized)

  • new C() - default construct (C::m is zero-initialized)

In a C++03 conformant compiler, things should work like so:

  • new A - indeterminate value
  • new A() - value-initialize A, which is zero-initialization since it's a POD.

  • new B - default-initializes (leaves B::m uninitialized)

  • new B() - value-initializes B which zero-initializes all fields since its default ctor is compiler generated as opposed to user-defined.

  • new C - default-initializes C, which calls the default ctor.

  • new C() - value-initializes C, which calls the default ctor.

So in all versions of C++ there's a difference between new A and new A() because A is a POD.

And there's a difference in behavior between C++98 and C++03 for the case new B().

This is one of the dusty corners of C++ that can drive you crazy. When constructing an object, sometimes you want/need the parens, sometimes you absolutely cannot have them, and sometimes it doesn't matter.

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

How do I check if a cookie exists?

ATTENTION! the chosen answer contains a bug (Jac's answer).

if you have more than one cookie (very likely..) and the cookie you are retrieving is the first on the list, it doesn't set the variable "end" and therefore it will return the entire string of characters following the "cookieName=" within the document.cookie string!

here is a revised version of that function:

function getCookie( name ) {
    var dc,
        prefix,
        begin,
        end;

    dc = document.cookie;
    prefix = name + "=";
    begin = dc.indexOf("; " + prefix);
    end = dc.length; // default to end of the string

    // found, and not in first position
    if (begin !== -1) {
        // exclude the "; "
        begin += 2;
    } else {
        //see if cookie is in first position
        begin = dc.indexOf(prefix);
        // not found at all or found as a portion of another cookie name
        if (begin === -1 || begin !== 0 ) return null;
    } 

    // if we find a ";" somewhere after the prefix position then "end" is that position,
    // otherwise it defaults to the end of the string
    if (dc.indexOf(";", begin) !== -1) {
        end = dc.indexOf(";", begin);
    }

    return decodeURI(dc.substring(begin + prefix.length, end) ).replace(/\"/g, ''); 
}

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

When is a github repository not empty, like .gitignore and license

Use pull --allow-unrelated-histories and push --force-with-lease

Use commands

git init
git add .
git commit -m "initial commit"
git remote add origin https://github.com/...
git pull origin master --allow-unrelated-histories
git push --force-with-lease

Most efficient way to create a zero filled JavaScript array?

My fastest function would be:

function newFilledArray(len, val) {
    var a = [];
    while(len--){
        a.push(val);
    }
    return a;
}

var st = (new Date()).getTime();
newFilledArray(1000000, 0)
console.log((new Date()).getTime() - st); // returned 63, 65, 62 milliseconds

Using the native push and shift to add items to the array is much faster (about 10 times) than declaring the array scope and referencing each item to set it's value.

fyi: I consistently get faster times with the first loop, which is counting down, when running this in firebug (firefox extension).

var a = [];
var len = 1000000;
var st = (new Date()).getTime();
while(len){
    a.push(0);
    len -= 1;
}
console.log((new Date()).getTime() - st); // returned 863, 894, 875 milliseconds
st = (new Date()).getTime();
len = 1000000;
a = [];
for(var i = 0; i < len; i++){
    a.push(0);
}
console.log((new Date()).getTime() - st); // returned 1155, 1179, 1163 milliseconds

I'm interested to know what T.J. Crowder makes of that ? :-)

How do I make a self extract and running installer

I have created step by step instructions on how to do this as I also was very confused about how to get this working.

How to make a self extracting archive that runs your setup.exe with 7zip -sfx switch

Here are the steps.

Step 1 - Setup your installation folder

To make this easy create a folder c:\Install. This is where we will copy all the required files.

Step 2 - 7Zip your installers

  1. Go to the folder that has your .msi and your setup.exe
  2. Select both the .msi and the setup.exe
  3. Right-Click and choose 7Zip --> "Add to Archive"
  4. Name your archive "Installer.7z" (or a name of your choice)
  5. Click Ok
  6. You should now have "Installer.7z".
  7. Copy this .7z file to your c:\Install directory

Step 3 - Get the 7z-Extra sfx extension module

You need to download 7zSD.sfx

  1. Download one of the LZMA packages from here
  2. Extract the package and find 7zSD.sfx in the bin folder.
  3. Copy the file "7zSD.sfx" to c:\Install

Step 4 - Setup your config.txt

I would recommend using NotePad++ to edit this text file as you will need to encode in UTF-8, the following instructions are using notepad++.

  1. Using windows explorer go to c:\Install
  2. right-click and choose "New Text File" and name it config.txt
  3. right-click and choose "Edit with NotePad++
  4. Click the "Encoding Menu" and choose "Encode in UTF-8"
  5. Enter something like this:

    ;!@Install@!UTF-8!
    Title="SOFTWARE v1.0.0.0"
    BeginPrompt="Do you want to install SOFTWARE v1.0.0.0?"
    RunProgram="setup.exe"
    ;!@InstallEnd@!
    

Edit this replacing [SOFTWARE v1.0.0.0] with your product name. Notes on the parameters and options for the setup file are here.

CheckPoint

You should now have a folder "c:\Install" with the following 3 files:

  1. Installer.7z
  2. 7zSD.sfx
  3. config.txt

Step 5 - Create the archive

These instructions I found on the web but nowhere did it explain any of the 4 steps above.

  1. Open a cmd window, Window + R --> cmd --> press enter
  2. In the command window type the following

    cd \
    cd Install
    copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe
    
  3. Look in c:\Install and you will now see you have a MyInstaller.exe

  4. You are finished

Run the installer

Double click on MyInstaller.exe and it will prompt with your message. Click OK and the setup.exe will run.

P.S. Note on Automation

Now that you have this working in your c:\Install directory I would create an "Install.bat" file and put the copy script in it.

copy /b 7zSD.sfx + config.txt + Installer.7z MyInstaller.exe

Now you can just edit and run the Install.bat every time you need to rebuild a new version of you deployment package.

How to return a file using Web API?

Example with IHttpActionResult in ApiController.

[HttpGet]
[Route("file/{id}/")]
public IHttpActionResult GetFileForCustomer(int id)
{
    if (id == 0)
      return BadRequest();

    var file = GetFile(id);

    IHttpActionResult response;
    HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.OK);
    responseMsg.Content = new ByteArrayContent(file.SomeData);
    responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
    responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;
    responseMsg.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
    response = ResponseMessage(responseMsg);
    return response;
}

If you don't want to download the PDF and use a browsers built in PDF viewer instead remove the following two lines:

responseMsg.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
responseMsg.Content.Headers.ContentDisposition.FileName = file.FileName;

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

The top answer is flawed in my opinion. Hopefully, no one is mass importing all of pandas into their namespace with from pandas import *. Also, the map method should be reserved for those times when passing it a dictionary or Series. It can take a function but this is what apply is used for.

So, if you must use the above approach, I would write it like this

df["A1"], df["A2"] = zip(*df["a"].apply(calculate))

There's actually no reason to use zip here. You can simply do this:

df["A1"], df["A2"] = calculate(df['a'])

This second method is also much faster on larger DataFrames

df = pd.DataFrame({'a': [1,2,3] * 100000, 'b': [2,3,4] * 100000})

DataFrame created with 300,000 rows

%timeit df["A1"], df["A2"] = calculate(df['a'])
2.65 ms ± 92.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit df["A1"], df["A2"] = zip(*df["a"].apply(calculate))
159 ms ± 5.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

60x faster than zip


In general, avoid using apply

Apply is generally not much faster than iterating over a Python list. Let's test the performance of a for-loop to do the same thing as above

%%timeit
A1, A2 = [], []
for val in df['a']:
    A1.append(val**2)
    A2.append(val**3)

df['A1'] = A1
df['A2'] = A2

298 ms ± 7.14 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

So this is twice as slow which isn't a terrible performance regression, but if we cythonize the above, we get much better performance. Assuming, you are using ipython:

%load_ext cython

%%cython
cpdef power(vals):
    A1, A2 = [], []
    cdef double val
    for val in vals:
        A1.append(val**2)
        A2.append(val**3)

    return A1, A2

%timeit df['A1'], df['A2'] = power(df['a'])
72.7 ms ± 2.16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Directly assigning without apply

You can get even greater speed improvements if you use the direct vectorized operations.

%timeit df['A1'], df['A2'] = df['a'] ** 2, df['a'] ** 3
5.13 ms ± 320 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

This takes advantage of NumPy's extremely fast vectorized operations instead of our loops. We now have a 30x speedup over the original.


The simplest speed test with apply

The above example should clearly show how slow apply can be, but just so its extra clear let's look at the most basic example. Let's square a Series of 10 million numbers with and without apply

s = pd.Series(np.random.rand(10000000))

%timeit s.apply(calc)
3.3 s ± 57.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Without apply is 50x faster

%timeit s ** 2
66 ms ± 2 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

return results from a function (javascript, nodejs)

You are trying to execute an asynchronous function in a synchronous way, which is unfortunately not possible in Javascript.

As you guessed correctly, the roomId=results.... is executed when the loading from the DB completes, which is done asynchronously, so AFTER the resto of your code is completed.

Look at this article, it talks about .insert and not .find, but the idea is the same : http://metaduck.com/01-asynchronous-iteration-patterns.html

Using group by on two fields and count in SQL

SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup

I want to exception handle 'list index out of range.'

for i in range (1, len(list))
    try:
        print (list[i])

    except ValueError:
        print("Error Value.")
    except indexError:
        print("Erorr index")
    except :
        print('error ')

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

Comment shortcut Android Studio

In spanish keyboard without changing anything I can make a comment with the keys:

cmd + -

OR

cmd + alt + -

This works because in english keyboard / is located at the same place than - on a spanish keyboard

Decode Base64 data in Java

In a code compiled with Java 7 but potentially running in a higher java version, it seems useful to detect presence of java.util.Base64 class and use the approach best for given JVM mentioned in other questions here.

I used this code:

private static final Method JAVA_UTIL_BASE64_GETENCODER;

static {
    Method getEncoderMethod;
    try {
        final Class<?> base64Class = Class.forName("java.util.Base64");
        getEncoderMethod = base64Class.getMethod("getEncoder");
    } catch (ClassNotFoundException | NoSuchMethodException e) {
        getEncoderMethod = null;
    }
    JAVA_UTIL_BASE64_GETENCODER = getEncoderMethod;
}

static String base64EncodeToString(String s) {
    final byte[] bytes = s.getBytes(StandardCharsets.ISO_8859_1);
    if (JAVA_UTIL_BASE64_GETENCODER == null) {
        // Java 7 and older // TODO: remove this branch after switching to Java 8
        return DatatypeConverter.printBase64Binary(bytes);
    } else {
        // Java 8 and newer
        try {
            final Object encoder = JAVA_UTIL_BASE64_GETENCODER.invoke(null);
            final Class<?> encoderClass = encoder.getClass();
            final Method encodeMethod = encoderClass.getMethod("encode", byte[].class);
            final byte[] encodedBytes = (byte[]) encodeMethod.invoke(encoder, bytes);
            return new String(encodedBytes);
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            throw new IllegalStateException(e);
        }
    }
}

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Send email from localhost running XAMMP in PHP using GMAIL mail server

[sendmail]

smtp_server=smtp.gmail.com  
smtp_port=25  
error_logfile=error.log  
debug_logfile=debug.log  
[email protected] 
auth_password=gmailpassword  
[email protected]

need authenticate username and password of mail then only once can successfully send mail from localhost

How to access a dictionary element in a Django template?

Ideally, you would create a method on the choice object that found itself in votes, or create a relationship between the models. A template tag that performed the dictionary lookup would work, too.

Microsoft.ReportViewer.Common Version=12.0.0.0

here the link to webreports version 12 https://www.nuget.org/packages/Microsoft.ReportViewer.WebForms.v12/12.0.0?_src=template

after the package installed

on your toolbox browse the dll reference it to bin then that's it run the visual studio

Java Enum Methods - return opposite direction enum

Create an abstract method, and have each of your enumeration values override it. Since you know the opposite while you're creating it, there's no need to dynamically generate or create it.

It doesn't read nicely though; perhaps a switch would be more manageable?

public enum Direction {
    NORTH(1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.SOUTH;
        }
    },
    SOUTH(-1) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.NORTH;
        }
    },
    EAST(-2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.WEST;
        }
    },
    WEST(2) {
        @Override
        public Direction getOppositeDirection() {
            return Direction.EAST;
        }
    };

    Direction(int code){
        this.code=code;
    }
    protected int code;

    public int getCode() {
        return this.code;
    }

    public abstract Direction getOppositeDirection();
}

Android: How to enable/disable option menu item on button click?

simplify @Vikas version

@Override
public boolean onPrepareOptionsMenu (Menu menu) {

    menu.findItem(R.id.example_foobar).setEnabled(isFinalized);
    return true;
}

How to request Location Permission at runtime

You need to actually request the Location permission at runtime (notice the comments in your code stating this).

Here is tested and working code to request the Location permission.

Be sure to import android.Manifest:

import android.Manifest;

Then put this code in the Activity:

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

public boolean checkLocationPermission() {
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) {

        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.
            new AlertDialog.Builder(this)
                    .setTitle(R.string.title_location_permission)
                    .setMessage(R.string.text_location_permission)
                    .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(MainActivity.this,
                                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                    MY_PERMISSIONS_REQUEST_LOCATION);
                        }
                    })
                    .create()
                    .show();


        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
        }
        return false;
    } else {
        return true;
    }
}

@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case MY_PERMISSIONS_REQUEST_LOCATION: {
            // If request is cancelled, the result arrays are empty.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                // permission was granted, yay! Do the
                // location-related task you need to do.
                if (ContextCompat.checkSelfPermission(this,
                        Manifest.permission.ACCESS_FINE_LOCATION)
                        == PackageManager.PERMISSION_GRANTED) {

                    //Request location updates:
                    locationManager.requestLocationUpdates(provider, 400, 1, this);
                }

            } else {

                // permission denied, boo! Disable the
                // functionality that depends on this permission.

            }
            return;
        }

    }
}

Then call the checkLocationPermission() method in onCreate():

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    //.........

    checkLocationPermission();
}

You can then use onResume() and onPause() exactly as it is in the question.

Here is a condensed version that is a bit more clean:

@Override
protected void onResume() {
    super.onResume();
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {

        locationManager.requestLocationUpdates(provider, 400, 1, this);
    }
}

@Override
protected void onPause() {
    super.onPause();
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION)
            == PackageManager.PERMISSION_GRANTED) {

        locationManager.removeUpdates(this);
    }
}

Converting date between DD/MM/YYYY and YYYY-MM-DD?

Your example code is wrong. This works:

import datetime

datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")

The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.

Spring Data JPA - "No Property Found for Type" Exception

Another scenario, that was not yet mentioned here, that caused this error is an API that receives Pageable (or Sort) and passes it, as is, to the JPA repository when calling the API from Swagger.

Swagger default value for the Pageable parameter is this:

  {
    "page": 0,
    "size": 0,
    "sort": [
      "string"
    ]
  }

Notice the "string" there which is a property that does exist. Running the API without deleting or changing it will cause org.springframework.data.mapping.PropertyReferenceException: No property string found for type ...

How to justify a single flexbox item (override justify-content)

There doesn't seem to be justify-self, but you can achieve similar result setting appropriate margin to auto¹. E. g. for flex-direction: row (default) you should set margin-right: auto to align the child to the left.

_x000D_
_x000D_
.container {_x000D_
  height: 100px;_x000D_
  border: solid 10px skyblue;_x000D_
  _x000D_
  display: flex;_x000D_
  justify-content: flex-end;_x000D_
}_x000D_
.block {_x000D_
  width: 50px;_x000D_
  background: tomato;_x000D_
}_x000D_
.justify-start {_x000D_
  margin-right: auto;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="block justify-start"></div>_x000D_
  <div class="block"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

¹ This behaviour is defined by the Flexbox spec.

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

Passing vector by reference

You can pass the container by reference in order to modify it in the function. What other answers haven’t addressed is that std::vector does not have a push_front member function. You can use the insert() member function on vector for O(n) insertion:

void do_something(int el, std::vector<int> &arr){
    arr.insert(arr.begin(), el);
}

Or use std::deque instead for amortised O(1) insertion:

void do_something(int el, std::deque<int> &arr){
    arr.push_front(el);
}

IOError: [Errno 13] Permission denied

IOError: [Errno 13] Permission denied: 'juliodantas2015.json'

tells you everything you need to know: though you successfully made your python program executable with your chmod, python can't open that juliodantas2015.json' file for writing. You probably don't have the rights to create new files in the folder you're currently in.

Exporting data In SQL Server as INSERT INTO

After search a lot, it was my best shot:

If you have a lot of data and needs a compact and elegant script, try it: SSMS Tools Pack

It generates a union all select statements to insert items into target tables and handle transactions pretty well.

Screenshot

Send password when using scp to copy files from one server to another

You should use better authentication with open keys. In these case you need no password and no expect.

If you want it with expect, use this script (see answer Automate scp file transfer using a shell script ):

#!/usr/bin/expect -f

# connect via scp
    spawn scp "[email protected]:/home/santhosh/file.dmp" /u01/dumps/file.dmp
#######################
expect {
-re ".*es.*o.*" {
    exp_send "yes\r"
    exp_continue
}
-re ".*sword.*" {
    exp_send "PASSWORD\r"
}
}
interact

Also, you can use pexpect (python module):

def doScp(user,password, host, path, files):
 fNames = ' '.join(files)
 print fNames
 child = pexpect.spawn('scp %s %s@%s:%s' % (fNames, user, host,path))
 print 'scp %s %s@%s:%s' % (fNames, user, host,path)
    i = child.expect(['assword:', r"yes/no"], timeout=30)
    if i == 0:
        child.sendline(password)
    elif i == 1:
        child.sendline("yes")
        child.expect("assword:", timeout=30)
        child.sendline(password)
    data = child.read()
    print data
    child.close()

LDAP server which is my base dn

The base dn is dc=example,dc=com.

I don't know about openca, but I will try this answer since you got very little traffic so far.

A base dn is the point from where a server will search for users. So I would try to simply use admin as a login name.

If openca behaves like most ldap aware applications, this is what is going to happen :

  1. An ldap search for the user admin will be done by the server starting at the base dn (dc=example,dc=com).
  2. When the user is found, the full dn (cn=admin,dc=example,dc=com) will be used to bind with the supplied password.
  3. The ldap server will hash the password and compare with the stored hash value. If it matches, you're in.

Getting step 1 right is the hardest part, but mostly because we don't get to do it often. Things you have to look out for in your configuraiton file are :

  • The dn your application will use to bind to the ldap server. This happens at application startup, before any user comes to authenticate. You will have to supply a full dn, maybe something like cn=admin,dc=example,dc=com.
  • The authentication method. It is usually a "simple bind".
  • The user search filter. Look at the attribute named objectClass for your admin user. It will be either inetOrgPerson or user. There will be others like top, you can ignore them. In your openca configuration, there should be a string like (objectClass=inetOrgPerson). Whatever it is, make sure it matches your admin user's object Class. You can specify two object class with this search filter (|(objectClass=inetOrgPerson)(objectClass=user)).

Download an LDAP Browser, such as Apache's Directory Studio. Connect using your application's credentials, so you will see what your application sees.

Reverse order of foreach list items

If your array is populated through an SQL Query consider reversing the result in MySQL, ie :

SELECT * FROM model_input order by creation_date desc

Return an empty Observable

In my case with Angular2 and rxjs, it worked with:

import {EmptyObservable} from 'rxjs/observable/EmptyObservable';
...
return new EmptyObservable();
...

Setting up a websocket on Apache?

The new version 2.4 of Apache HTTP Server has a module called mod_proxy_wstunnel which is a websocket proxy.

http://httpd.apache.org/docs/2.4/mod/mod_proxy_wstunnel.html

How to destroy an object?

A handy post explaining several mis-understandings about this:

Don't Call The Destructor explicitly

This covers several misconceptions about how the destructor works. Calling it explicitly will not actually destroy your variable, according to the PHP5 doc:

PHP 5 introduces a destructor concept similar to that of other object-oriented languages, such as C++. The destructor method will be called as soon as there are no other references to a particular object, or in any order during the shutdown sequence.

The post above does state that setting the variable to null can work in some cases, as long as nothing else is pointing to the allocated memory.

Impersonate tag in Web.Config

The identity section goes under the system.web section, not under authentication:

<system.web>
  <authentication mode="Windows"/>
  <identity impersonate="true" userName="foo" password="bar"/>
</system.web>

How to install Java SDK on CentOS?

Since Oracle inserted some md5hash in their download links, one cannot automatically assemble a download link for command line.

So I tinkered some nasty bash command line to get the latest jdk download link, download it and directly install via rpm. For all who are interested:

wget -q http://www.oracle.com/technetwork/java/javase/downloads/index.html -O ./index.html && grep -Eoi ']+>' index.html | grep -Eoi '/technetwork/java/javase/downloads/jdk8-downloads-[0-9]+.html' | (head -n 1) | awk '{print "http://www.oracle.com"$1}' | xargs wget --no-cookies --header "Cookie: gpw_e24=xxx; oraclelicense=accept-securebackup-cookie;" -O index.html -q && grep -Eoi '"filepath":"[^"]+jdk-8u[0-9]+-linux-x64.rpm"' index.html | grep -Eoi 'http:[^"]+' | xargs wget --no-cookies --header "Cookie: gpw_e24=xxx; oraclelicense=accept-securebackup-cookie;" -q -O ./jdk8.rpm && sudo rpm -i ./jdk8.rpm

The bold part should be replaced by the package of your liking.

How to generate range of numbers from 0 to n in ES2015 only?

const keys = Array(n).keys();
[...Array.from(keys)].forEach(callback);

in Typescript

How to execute Python code from within Visual Studio Code

You can add a custom task to do this. Here is a basic custom task for Python.

{
    "version": "0.1.0",
    "command": "c:\\Python34\\python",
    "args": ["app.py"],
    "problemMatcher": {
        "fileLocation": ["relative", "${workspaceRoot}"],
        "pattern": {
            "regexp": "^(.*)+s$",
            "message": 1
        }
    }
}

You add this to file tasks.json and press Ctrl + Shift + B to run it.

What does Maven do, in theory and in practice? When is it worth to use it?

Maven is a build tool. Along with Ant or Gradle are Javas tools for building.
If you are a newbie in Java though just build using your IDE since Maven has a steep learning curve.

How do I get the height of a div's full content with jQuery?

Element.scrollHeight is a property, not a function, as noted here. As noted here, the scrollHeight property is only supported after IE8. If you need it to work before that, temporarily set the CSS overflow and height to auto, which will cause the div to take the maximum height it needs. Then get the height, and change the properties back to what they were before.

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

HTTP redirect: 301 (permanent) vs. 302 (temporary)

301 is that the requested resource has been assigned a new permanent URI and any future references to this resource should be done using one of the returned URIs.

302 is that the requested resource resides temporarily under a different URI.

Since the redirection may be altered on occasion, the client should continue to use the Request-URI for future requests.

This response is only cachable if indicated by a Cache-Control or Expires header field.

using batch echo with special characters

One easy solution is to use delayed expansion, as this doesn't change any special characters.

set "line=<?xml version="1.0" encoding="utf-8" ?>"
setlocal EnableDelayedExpansion
(
  echo !line!
) > myfile.xml

EDIT : Another solution is to use a disappearing quote.

This technic uses a quotation mark to quote the special characters

@echo off
setlocal EnableDelayedExpansion
set ""="
echo !"!<?xml version="1.0" encoding="utf-8" ?>

The trick works, as in the special characters phase the leading quotation mark in !"! will preserve the rest of the line (if there aren't other quotes).
And in the delayed expansion phase the !"! will replaced with the content of the variable " (a single quote is a legal name!).

If you are working with disabled delayed expansion, you could use a FOR /F loop instead.

for /f %%^" in ("""") do echo(%%~" <?xml version="1.0" encoding="utf-8" ?>

But as the seems to be a bit annoying you could also build a macro.

set "print=for /f %%^" in ("""") do echo(%%~""

%print%<?xml version="1.0" encoding="utf-8" ?>
%print% Special characters like &|<>^ works now without escaping

Programmatically Add CenterX/CenterY Constraints

Programmatically you can do it by adding the following constraints.

NSLayoutConstraint *constraintHorizontal = [NSLayoutConstraint constraintWithItem:self  
                                                                      attribute:NSLayoutAttributeCenterX 
                                                                      relatedBy:NSLayoutRelationEqual 
                                                                         toItem:self.superview 
                                                                      attribute:attribute 
                                                                     multiplier:1.0f 
                                                                       constant:0.0f];

NSLayoutConstraint *constraintVertical = [NSLayoutConstraint constraintWithItem:self
                                                                        attribute:NSLayoutAttributeCenterY 
                                                                        relatedBy:NSLayoutRelationEqual
                                                                           toItem:self.superview 
                                                                        attribute:attribute 
                                                                       multiplier:1.0f
                                                                         constant:0.0f];

Counting unique values in a column in pandas dataframe like in Qlik?

you can use unique property by using len function

len(df['hID'].unique()) 5

Why am I getting AttributeError: Object has no attribute

Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName.

How to see the changes between two commits without commits in-between?

Let's say you have this

A
|
B    A0
|    |
C    D
\   /
  |
 ...

And you want to make sure that A is the same as A0.

This will do the trick:

$ git diff B A > B-A.diff
$ git diff D A0 > D-A0.diff
$ diff B-A.diff D-A0.diff

JPA getSingleResult() or null

The undocumented method uniqueResultOptional in org.hibernate.query.Query should do the trick. Instead of having to catch a NoResultException you can just call query.uniqueResultOptional().orElse(null).

Numpy - add row to array

import numpy as np
array_ = np.array([[1,2,3]])
add_row = np.array([[4,5,6]])

array_ = np.concatenate((array_, add_row), axis=0)

Getting current directory in VBScript

You can use CurrentDirectory property.

Dim WshShell, strCurDir
Set WshShell = CreateObject("WScript.Shell")
strCurDir    = WshShell.CurrentDirectory
WshShell.Run strCurDir & "\attribute.exe", 0
Set WshShell = Nothing

How to Implement DOM Data Binding in JavaScript

I think my answer will be more technical, but not different as the others present the same thing using different techniques.
So, first things first, the solution to this problem is the use of a design pattern known as "observer", it let's you decouple your data from your presentation, making the change in one thing be broadcasted to their listeners, but in this case it's made two-way.

For the DOM to JS way

To bind the data from the DOM to the js object you may add markup in the form of data attributes (or classes if you need compatibility), like this:

<input type="text" data-object="a" data-property="b" id="b" class="bind" value=""/>
<input type="text" data-object="a" data-property="c" id="c" class="bind" value=""/>
<input type="text" data-object="d" data-property="e" id="e" class="bind" value=""/>

This way it can be accessed via js using querySelectorAll (or the old friend getElementsByClassName for compatibility).

Now you can bind the event listening to the changes in to ways: one listener per object or one big listener to the container/document. Binding to the document/container will trigger the event for every change made in it or it's child, it willhave a smaller memory footprint but will spawn event calls.
The code will look something like this:

//Bind to each element
var elements = document.querySelectorAll('input[data-property]');

function toJS(){
    //Assuming `a` is in scope of the document
    var obj = document[this.data.object];
    obj[this.data.property] = this.value;
}

elements.forEach(function(el){
    el.addEventListener('change', toJS, false);
}

//Bind to document
function toJS2(){
    if (this.data && this.data.object) {
        //Again, assuming `a` is in document's scope
        var obj = document[this.data.object];
        obj[this.data.property] = this.value;
    }
}

document.addEventListener('change', toJS2, false);

For the JS do DOM way

You will need two things: one meta-object that will hold the references of witch DOM element is binded to each js object/attribute and a way to listen to changes in objects. It is basically the same way: you have to have a way to listen to changes in the object and then bind it to the DOM node, as your object "can't have" metadata you will need another object that holds metadata in a way that the property name maps to the metadata object's properties. The code will be something like this:

var a = {
        b: 'foo',
        c: 'bar'
    },
    d = {
        e: 'baz'
    },
    metadata = {
        b: 'b',
        c: 'c',
        e: 'e'
    };
function toDOM(changes){
    //changes is an array of objects changed and what happened
    //for now i'd recommend a polyfill as this syntax is still a proposal
    changes.forEach(function(change){
        var element = document.getElementById(metadata[change.name]);
        element.value = change.object[change.name];
    });
}
//Side note: you can also use currying to fix the second argument of the function (the toDOM method)
Object.observe(a, toDOM);
Object.observe(d, toDOM);

I hope that i was of help.

Converting JavaScript object with numeric keys into array

Assuming your have a value like the following

var obj = {"0":"1","1":"2","2":"3","3":"4"};

Then you can turn this into a javascript array using the following

var arr = [];
json = JSON.stringify(eval('(' + obj + ')')); //convert to json string
arr = $.parseJSON(json); //convert to javascript array

This works for converting json into multi-diminsional javascript arrays as well.

None of the other methods on this page seemed to work completely for me when working with php json-encoded strings except the method I am mentioning herein.

What is the purpose of the "final" keyword in C++11 for functions?

Final keyword in C++ when added to a function, prevents it from being overridden by a base class. Also when added to a class prevents inheritance of any type. Consider the following example which shows use of final specifier. This program fails in compilation.

#include <iostream>
using namespace std;

class Base
{
  public:
  virtual void myfun() final
  {
    cout << "myfun() in Base";
  }
};
class Derived : public Base
{
  void myfun()
  {
    cout << "myfun() in Derived\n";
  }
};

int main()
{
  Derived d;
  Base &b = d;
  b.myfun();
  return 0;
}

Also:

#include <iostream>
class Base final
{
};

class Derived : public Base
{
};

int main()
{
  Derived d;
  return 0;
}

HttpClient not supporting PostAsJsonAsync method C#

Instead of writing this amount of code to make a simple call, you could use one of the wrappers available over the internet.

I've written one called WebApiClient, available at NuGet... check it out!

https://www.nuget.org/packages/WebApiRestService.WebApiClient/

AndroidStudio SDK directory does not exists

Today upgraded to Android 3.3, which broke everything for me.

This one was related to importing the project, not opening it.

Solution which worked for me, was to import the project. During the import it detects that the SDK directory is missing and proposes to open it from a location which actually exists. It worked in my case but your case might be different.

Many other changes still needed to be done to make old projects work. What a pain any update is. I wonder why don't they do a thorough QA first before releasing these updates. It has become an industry norm to release problem filled software, probably thinking that users will figure out solutions via Stackoverflow.

How to implement a Keyword Search in MySQL?

Ideally, have a keyword table containing the fields:

Keyword
Id
Count (possibly)

with an index on Keyword. Create an insert/update/delete trigger on the other table so that, when a row is changed, every keyword is extracted and put into (or replaced in) this table.

You'll also need a table of words to not count as keywords (if, and, so, but, ...).

In this way, you'll get the best speed for queries wanting to look for the keywords and you can implement (relatively easily) more complex queries such as "contains Java and RCA1802".

"LIKE" queries will work but they won't scale as well.

How are Anonymous inner classes used in Java?

Yes, anonymous inner classes is definitely one of the advantages of Java.

With an anonymous inner class you have access to final and member variables of the surrounding class, and that comes in handy in listeners etc.

But a major advantage is that the inner class code, which is (at least should be) tightly coupled to the surrounding class/method/block, has a specific context (the surrounding class, method, and block).

Get element by id - Angular2

if you want to set value than you can do the same in some function on click or on some event fire.

also you can get value using ViewChild using local variable like this

<input type='text' id='loginInput' #abc/>

and get value like this

this.abc.nativeElement.value

here is working example

Update

okay got it , you have to use ngAfterViewInit method of angualr2 for the same like this

ngAfterViewInit(){
    document.getElementById('loginInput').value = '123344565';
  }

ngAfterViewInit will not throw any error because it will render after template loading

calling parent class method from child class object in java

NOTE calling parent method via super will only work on parent class, If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();

interface Vehicle {
    //Non abstract method
    public default void printVehicleTypeName() { //default keyword can be used only in interface.
        System.out.println("Vehicle");
    }
}


class FordFigo extends FordImpl implements Vehicle, Ford {
    @Override
    public void printVehicleTypeName() { 
        System.out.println("Figo");
        Vehicle.super.printVehicleTypeName();
    }
}

Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.

Jenkins / Hudson environment variables

Jenkins also supports the format PATH+<name> to prepend to any variable, not only PATH:

Global Environment variables or node Environment variables:

Jenkins variable + notation

This is also supported in the pipeline step withEnv:

node {
  withEnv(['PATH+JAVA=/path/to/java/bin']) {
    ...
  }
}

Just take note, it prepends to the variable. If it must be appended you need to do what the other answers show.

See the pipeline steps document here.

You may also use the syntax PATH+WHATEVER=/something to prepend /something to $PATH

Or the java docs on EnvVars here.

npm throws error without sudo

I like to use ubuntu groups to achieve this instead of changing owner. Its quite simple.

  1. First install nodejs and npm using apt-get

    sudo apt-get update && sudo apt-get install nodejs npm

  2. Figure out who is logged in i.e username, run following command to see it in terminal

    whoami

  3. You can see the list of groups you are assigned by using a very simple command, normally the first group is your username itself

    groups

  4. Run following to allow access to logged in user

    sudo chmod 777 -R /usr/local && sudo chgrp $(whoami) -R /usr/local

  5. Update npm and nodejs

    npm install -g npm

You are allset, your user can run npm commands without sudo

You can also refer to this link https://askubuntu.com/a/1115373/687804

Is there any difference between a GUID and a UUID?

Microsoft's GUID's textual representation can be in the form of a UUID being surrounded by two curly braces {}.

Google Play Services Library update and missing symbol @integer/google_play_services_version

The problem for me was that the library project and the project using play services were in different directories. So just:

  • 1.Add the files to the same workspace then remove the library.
  • 2.Restart eclipse
  • 3.Add the library project again
  • 4.Clear

Why is processing a sorted array faster than processing an unsorted array?

It's about branch prediction. What is it?

  • A branch predictor is one of the ancient performance improving techniques which still finds relevance into modern architectures. While the simple prediction techniques provide fast lookup and power efficiency they suffer from a high misprediction rate.

  • On the other hand, complex branch predictions –either neural based or variants of two-level branch prediction –provide better prediction accuracy, but they consume more power and complexity increases exponentially.

  • In addition to this, in complex prediction techniques the time taken to predict the branches is itself very high –ranging from 2 to 5 cycles –which is comparable to the execution time of actual branches.

  • Branch prediction is essentially an optimization (minimization) problem where the emphasis is on to achieve lowest possible miss rate, low power consumption, and low complexity with minimum resources.

There really are three different kinds of branches:

Forward conditional branches - based on a run-time condition, the PC (program counter) is changed to point to an address forward in the instruction stream.

Backward conditional branches - the PC is changed to point backward in the instruction stream. The branch is based on some condition, such as branching backwards to the beginning of a program loop when a test at the end of the loop states the loop should be executed again.

Unconditional branches - this includes jumps, procedure calls and returns that have no specific condition. For example, an unconditional jump instruction might be coded in assembly language as simply "jmp", and the instruction stream must immediately be directed to the target location pointed to by the jump instruction, whereas a conditional jump that might be coded as "jmpne" would redirect the instruction stream only if the result of a comparison of two values in a previous "compare" instructions shows the values to not be equal. (The segmented addressing scheme used by the x86 architecture adds extra complexity, since jumps can be either "near" (within a segment) or "far" (outside the segment). Each type has different effects on branch prediction algorithms.)

Static/dynamic Branch Prediction: Static branch prediction is used by the microprocessor the first time a conditional branch is encountered, and dynamic branch prediction is used for succeeding executions of the conditional branch code.

References:

Get a list of all functions and procedures in an Oracle database

Do a describe on dba_arguments, dba_errors, dba_procedures, dba_objects, dba_source, dba_object_size. Each of these has part of the pictures for looking at the procedures and functions.

Also the object_type in dba_objects for packages is 'PACKAGE' for the definition and 'PACKAGE BODY" for the body.

If you are comparing schemas on the same database then try:

select * from dba_objects 
   where schema_name = 'ASCHEMA' 
     and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )
minus
select * from dba_objects 
where schema_name = 'BSCHEMA' 
  and object_type in ( 'PROCEDURE', 'PACKAGE', 'FUNCTION', 'PACKAGE BODY' )

and switch around the orders of ASCHEMA and BSCHEMA.

If you also need to look at triggers and comparing other stuff between the schemas you should take a look at the Article on Ask Tom about comparing schemas

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

Clean your maven cache and rerun:

mvn dependency:purge-local-repository

Get href attribute on jQuery

Very simply, use this as the context: http://api.jquery.com/jQuery/#selector-context

var a_href = $('div.cpt', this).find('h2 a').attr('href');

Which says, find 'div.cpt' only inside this

How can I select rows by range?

Using Between condition

SELECT *
FROM TEST
WHERE COLUMN_NAME BETWEEN x AND y ;

Or using Just operators,

SELECT *
FROM TEST
WHERE COLUMN_NAME >= x AND COLUMN_NAME   <= y;

How do I obtain the frequencies of each value in an FFT?

I have used the following:

public static double Index2Freq(int i, double samples, int nFFT) {
  return (double) i * (samples / nFFT / 2.);
}

public static int Freq2Index(double freq, double samples, int nFFT) {
  return (int) (freq / (samples / nFFT / 2.0));
}

The inputs are:

  • i: Bin to access
  • samples: Sampling rate in Hertz (i.e. 8000 Hz, 44100Hz, etc.)
  • nFFT: Size of the FFT vector

Normalizing images in OpenCV

If you want to change the range to [0, 1], make sure the output data type is float.

image = cv2.imread("lenacolor512.tiff", cv2.IMREAD_COLOR)  # uint8 image
norm_image = cv2.normalize(image, None, alpha=0, beta=1, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_32F)

What does HTTP/1.1 302 mean exactly?

A 302 status code is HTTP response status code indicating that the requested resource has been temporarily moved to a different URI. Since the location or current redirection directive might be changed in the future, a client that receives a 302 Found response code should continue to use the original URI for future requests.

An HTTP response with this status code will additionally provide a URL in the header field Location. This is an invitation to the user agent (e.g. a web browser) to make a second, otherwise identical, request to the new URL specified in the location field. The end result is a redirection to the new URL.

How to iterate over columns of pandas dataframe to run regression

Using list comprehension, you can get all the columns names (header):

[column for column in df]

Separators for Navigation

The other solution are OK, but there is no need to add separator at the very last if using :after or at the very beginning if using :before.

SO:

case :after

.link:after {
  content: '|';
  padding: 0 1rem;
}

.link:last-child:after {
  content: '';
}

case :before

.link:before {
  content: '|';
  padding: 0 1rem;
}

.link:first-child:before {
  content: '';
}

Socket accept - "Too many open files"

I had similar problem. Quick solution is :

ulimit -n 4096

explanation is as follows - each server connection is a file descriptor. In CentOS, Redhat and Fedora, probably others, file user limit is 1024 - no idea why. It can be easily seen when you type: ulimit -n

Note this has no much relation to system max files (/proc/sys/fs/file-max).

In my case it was problem with Redis, so I did:

ulimit -n 4096
redis-server -c xxxx

in your case instead of redis, you need to start your server.

How to "z-index" to make a menu always on top of the content

Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute and right:0

#right { 
    background-color: red;
    height: 300px;
    width: 300px;
    z-index: 999999;
    margin-top: 0px;
    position: absolute;
    right:0;
}

here is the full code: http://jsfiddle.net/T9FJL/

Why do I need to do `--set-upstream` all the time?

I personally use these following alias in bash

in ~/.gitconfig file

[alias]
    pushup = "!git push --set-upstream origin $(git symbolic-ref --short HEAD)"

and in ~/.bashrc or ~/.zshrc file

alias gpo="git pushup"
alias gpof="gpo -f"
alias gf="git fetch"
alias gp="git pull"

Enable vertical scrolling on textarea

You can try adding:

#aboutDescription
{
    height: 100px;
    max-height: 100px;  
}

Copy an entire worksheet to a new worksheet in Excel 2010

If anyone has, like I do, an Estimating workbook with a default number of visible pricing sheets, a Summary and a larger number of hidden and 'protected' worksheets full of sensitive data but may need to create additional visible worksheets to arrive at a proper price, I have variant of the above responses that creates the said visible worksheets based on a protected hidden "Master". I have used the code provided by @/jean-fran%c3%a7ois-corbett and @thanos-a in combination with simple VBA as shown below.

Sub sbInsertWorksheetAfter()

    'This adds a new visible worksheet after the last visible worksheet

    ThisWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)

    'This copies the content of the HIDDEN "Master" worksheet to the new VISIBLE ActiveSheet just created

    ThisWorkbook.Sheets("Master").Cells.Copy _
        Destination:=ActiveSheet.Cells

    'This gives the the new ActiveSheet a default name

    With ActiveSheet
        .Name = Sheet12.Name & " copied"
    End With

    'This changes the name of the ActiveSheet to the user's preference

    Dim sheetname As String

    With ActiveSheet
        sheetname = InputBox("Enter name of this Worksheet")
        .Name = sheetname
    End With

End Sub

Laravel back button

Laravel 5.2+, back button

<a href="{{ url()->previous() }}" class="btn btn-default">Back</a>

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.

Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.

You can do the convertion following this articles:

Check if a number is odd or even in python

if num % 2 == 0:
    pass # Even 
else:
    pass # Odd

The % sign is like division only it checks for the remainder, so if the number divided by 2 has a remainder of 0 it's even otherwise odd.

Or reverse them for a little speed improvement, since any number above 0 is also considered "True" you can skip needing to do any equality check:

if num % 2:
    pass # Odd
else:
    pass # Even 

Combining INSERT INTO and WITH/CTE

The WITH clause for Common Table Expressions go at the top.

Wrapping every insert in a CTE has the benefit of visually segregating the query logic from the column mapping.

Spot the mistake:

WITH _INSERT_ AS (
  SELECT
    [BatchID]      = blah
   ,[APartyNo]     = blahblah
   ,[SourceRowID]  = blahblahblah
  FROM Table1 AS t1
)
INSERT Table2
      ([BatchID], [SourceRowID], [APartyNo])
SELECT [BatchID], [APartyNo], [SourceRowID]   
FROM _INSERT_

Same mistake:

INSERT Table2 (
  [BatchID]
 ,[SourceRowID]
 ,[APartyNo]
)
SELECT
  [BatchID]      = blah
 ,[APartyNo]     = blahblah
 ,[SourceRowID]  = blahblahblah
FROM Table1 AS t1

A few lines of boilerplate make it extremely easy to verify the code inserts the right number of columns in the right order, even with a very large number of columns. Your future self will thank you later.

jQuery input button click event listener

$("#filter").click(function(){
    //Put your code here
});

ConcurrentModificationException for ArrayList

You can't remove from list if you're browsing it with "for each" loop. You can use Iterator. Replace:

for (DrugStrength aDrugStrength : aDrugStrengthList) {
    if (!aDrugStrength.isValidDrugDescription()) {
        aDrugStrengthList.remove(aDrugStrength);
    }
}

With:

for (Iterator<DrugStrength> it = aDrugStrengthList.iterator(); it.hasNext(); ) {
    DrugStrength aDrugStrength = it.next();
    if (!aDrugStrength.isValidDrugDescription()) {
        it.remove();
    }
}

Prefer composition over inheritance?

Prefer composition over inheritance as it is more malleable / easy to modify later, but do not use a compose-always approach. With composition, it's easy to change behavior on the fly with Dependency Injection / Setters. Inheritance is more rigid as most languages do not allow you to derive from more than one type. So the goose is more or less cooked once you derive from TypeA.

My acid test for the above is:

  • Does TypeB want to expose the complete interface (all public methods no less) of TypeA such that TypeB can be used where TypeA is expected? Indicates Inheritance.

    • e.g. A Cessna biplane will expose the complete interface of an airplane, if not more. So that makes it fit to derive from Airplane.
  • Does TypeB want only some/part of the behavior exposed by TypeA? Indicates need for Composition.

    • e.g. A Bird may need only the fly behavior of an Airplane. In this case, it makes sense to extract it out as an interface / class / both and make it a member of both classes.

Update: Just came back to my answer and it seems now that it is incomplete without a specific mention of Barbara Liskov's Liskov Substitution Principle as a test for 'Should I be inheriting from this type?'

Install numpy on python3.3 - Install pip for python3

I'm on Ubuntu 15.04. This seemed to work:

$ sudo pip3 install numpy

On RHEL this worked:

$ sudo python3 -m pip install numpy

Git - Ignore files during merge

Example:

  1. You have two branches: master, develop
  2. You created file in develop branch and want to ignore it while merging

Code:

git config --global merge.ours.driver true
git checkout master
echo "path/file_to_ignore merge=ours" >> .gitattributes
git merge develop

You can also ignore files with same extension

for example all files with .txt extension:

echo "*.txt merge=ours" >> .gitattributes

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

simply pass the argument

attachtoroot = false

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

Reordering arrays

Immutable version, no side effects (doesn’t mutate original array):

const testArr = [1, 2, 3, 4, 5];

function move(from, to, arr) {
    const newArr = [...arr];

    const item = newArr.splice(from, 1)[0];
    newArr.splice(to, 0, item);

    return newArr;
}

console.log(move(3, 1, testArr));

// [1, 4, 2, 3, 5]

codepen: https://codepen.io/mliq/pen/KKNyJZr

How to fix 'Notice: Undefined index:' in PHP form action

if(!empty($_POST['filename'])){
$filename = $_POST['filename'];

echo $filename;
}

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

I had the same error for quite a while, and here what fixed it for me.

I simply declared in service that i use what follows:

Description= Your node service description
After=network.target

[Service]
Type=forking
PIDFile=/tmp/node_pid_name.pid
Restart=on-failure
KillSignal=SIGQUIT
WorkingDirectory=/path/to/node/app/root/directory
ExecStart=/path/to/node /path/to/server.js

[Install]
WantedBy=multi-user.target

What should catch your attention here is "After=network.target". I spent days and days looking for fixes on nginx side, while the problem was just that. To be sure, stop running the node service you have, launch the ExecStart command directly and try to reproduce the bug. If it doesn't pop, it just means that your service has a problem. At least this is how i found my answer.

For everybody else, good luck!

Rails: How can I rename a database column in a Ruby on Rails migration?

Just generate migration using command

rails g migration rename_hased_password

After that edit the migration add following line in change method

rename_column :table, :hased_password, :hashed_password

This should do the trick.

Oracle SQL escape character (for a '&')

the & is the default value for DEFINE, which allows you to use substitution variables. I like to turn it off using

SET DEFINE OFF

then you won't have to worry about escaping or CHR(38).

Laravel 5 - How to access image uploaded in storage within View?

According to Laravel 5.2 docs, your publicly accessible files should be put in directory

storage/app/public

To make them accessible from the web, you should create a symbolic link from public/storage to storage/app/public.

ln -s /path/to/laravel/storage/app/public /path/to/laravel/public/storage

Now you can create in your view an URL to the files using the asset helper:

echo asset('storage/file.txt');

Excel 2010: how to use autocomplete in validation list

As other people suggested, you need to use a combobox. However, most tutorials show you how to set up just one combobox and the process is quite tedious.

As I faced this problem before when entering a large amount of data from a list, I can suggest you use this autocomplete add-in . It helps you create the combobox on any cells you select and you can define a list to appear in the dropdown.

Read a file line by line assigning the value to a variable

I encourage you to use the -r flag for read which stands for:

-r  Do not treat a backslash character in any special way. Consider each
    backslash to be part of the input line.

I am citing from man 1 read.

Another thing is to take a filename as an argument.

Here is updated code:

#!/usr/bin/bash
filename="$1"
while read -r line; do
    name="$line"
    echo "Name read from file - $name"
done < "$filename"

How to get scrollbar position with Javascript?

I think the following function can help to have scroll coordinate values:

const getScrollCoordinate = (el = window) => ({
  x: el.pageXOffset || el.scrollLeft,
  y: el.pageYOffset || el.scrollTop,
});

I got this idea from this answer with a little change.

Transparent ARGB hex value

Transparency is controlled by the alpha channel (AA in #AARRGGBB). Maximal value (255 dec, FF hex) means fully opaque. Minimum value (0 dec, 00 hex) means fully transparent. Values in between are semi-transparent, i.e. the color is mixed with the background color.

To get a fully transparent color set the alpha to zero. RR, GG and BB are irrelevant in this case because no color will be visible. This means #00FFFFFF ("transparent White") is the same color as #00F0F8FF ("transparent AliceBlue"). To keep it simple one chooses black (#00000000) or white (#00FFFFFF) if the color does not matter.

In the table you linked to you'll find Transparent defined as #00FFFFFF.

How to search for rows containing a substring?

Info on MySQL's full text search. This is restricted to MyISAM tables, so may not be suitable if you wantto use a different table type.

http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html

Even if WHERE textcolumn LIKE "%SUBSTRING%" is going to be slow, I think it is probably better to let the Database handle it rather than have PHP handle it. If it is possible to restrict searches by some other criteria (date range, user, etc) then you may find the substring search is OK (ish).

If you are searching for whole words, you could pull out all the individual words into a separate table and use that to restrict the substring search. (So when searching for "my search string" you look for the the longest word "search" only do the substring search on records containing the word "search")

How do I crop an image in Java?

The solution I found most useful for cropping a buffered image uses the getSubImage(x,y,w,h);

My cropping routine ended up looking like this:

  private BufferedImage cropImage(BufferedImage src, Rectangle rect) {
      BufferedImage dest = src.getSubimage(0, 0, rect.width, rect.height);
      return dest; 
   }

What’s the best way to reload / refresh an iframe?

for new url

location.assign("http:google.com");

The assign() method loads a new document.

reload

location.reload();

The reload() method is used to reload the current document.

Easiest way to convert a List to a Set in Java

Set<Foo> foo = new HashSet<Foo>(myList);

Replace preg_replace() e modifier with preg_replace_callback

In a regular expression, you can "capture" parts of the matched string with (brackets); in this case, you are capturing the (^|_) and ([a-z]) parts of the match. These are numbered starting at 1, so you have back-references 1 and 2. Match 0 is the whole matched string.

The /e modifier takes a replacement string, and substitutes backslash followed by a number (e.g. \1) with the appropriate back-reference - but because you're inside a string, you need to escape the backslash, so you get '\\1'. It then (effectively) runs eval to run the resulting string as though it was PHP code (which is why it's being deprecated, because it's easy to use eval in an insecure way).

The preg_replace_callback function instead takes a callback function and passes it an array containing the matched back-references. So where you would have written '\\1', you instead access element 1 of that parameter - e.g. if you have an anonymous function of the form function($matches) { ... }, the first back-reference is $matches[1] inside that function.

So a /e argument of

'do_stuff(\\1) . "and" . do_stuff(\\2)'

could become a callback of

function($m) { return do_stuff($m[1]) . "and" . do_stuff($m[2]); }

Or in your case

'strtoupper("\\2")'

could become

function($m) { return strtoupper($m[2]); }

Note that $m and $matches are not magic names, they're just the parameter name I gave when declaring my callback functions. Also, you don't have to pass an anonymous function, it could be a function name as a string, or something of the form array($object, $method), as with any callback in PHP, e.g.

function stuffy_callback($things) {
    return do_stuff($things[1]) . "and" . do_stuff($things[2]);
}
$foo = preg_replace_callback('/([a-z]+) and ([a-z]+)/', 'stuffy_callback', 'fish and chips');

As with any function, you can't access variables outside your callback (from the surrounding scope) by default. When using an anonymous function, you can use the use keyword to import the variables you need to access, as discussed in the PHP manual. e.g. if the old argument was

'do_stuff(\\1, $foo)'

then the new callback might look like

function($m) use ($foo) { return do_stuff($m[1], $foo); }

Gotchas

  • Use of preg_replace_callback is instead of the /e modifier on the regex, so you need to remove that flag from your "pattern" argument. So a pattern like /blah(.*)blah/mei would become /blah(.*)blah/mi.
  • The /e modifier used a variant of addslashes() internally on the arguments, so some replacements used stripslashes() to remove it; in most cases, you probably want to remove the call to stripslashes from your new callback.

Android: remove left margin from actionbar's custom layout

<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"
android:paddingLeft="0dp">

This should be good enough.

Google Maps API - Get Coordinates of address

Althugh you asked for Google Maps API, I suggest an open source, working, legal, free and crowdsourced API by Open street maps

https://nominatim.openstreetmap.org/search?q=Mumbai&format=json

Here is the API documentation for reference.

Edit: It looks like there are discrepancies occasionally, at least in terms of postal codes, when compared to the Google Maps API, and the latter seems to be more accurate. This was the case when validating addresses in Canada with the Canada Post search service, however, it might be true for other countries too.

How to copy Outlook mail message into excel using VBA or Macros

Since you have not mentioned what needs to be copied, I have left that section empty in the code below.

Also you don't need to move the email to the folder first and then run the macro in that folder. You can run the macro on the incoming mail and then move it to the folder at the same time.

This will get you started. I have commented the code so that you will not face any problem understanding it.

First paste the below mentioned code in the outlook module.

Then

  1. Click on Tools~~>Rules and Alerts
  2. Click on "New Rule"
  3. Click on "start from a blank rule"
  4. Select "Check messages When they arrive"
  5. Under conditions, click on "with specific words in the subject"
  6. Click on "specific words" under rules description.
  7. Type the word that you want to check in the dialog box that pops up and click on "add".
  8. Click "Ok" and click next
  9. Select "move it to specified folder" and also select "run a script" in the same box
  10. In the box below, specify the specific folder and also the script (the macro that you have in module) to run.
  11. Click on finish and you are done.

When the new email arrives not only will the email move to the folder that you specify but data from it will be exported to Excel as well.

UNTESTED

Const xlUp As Long = -4162

Sub ExportToExcel(MyMail As MailItem)
    Dim strID As String, olNS As Outlook.Namespace
    Dim olMail As Outlook.MailItem
    Dim strFileName As String

    '~~> Excel Variables
    Dim oXLApp As Object, oXLwb As Object, oXLws As Object
    Dim lRow As Long

    strID = MyMail.EntryID
    Set olNS = Application.GetNamespace("MAPI")
    Set olMail = olNS.GetItemFromID(strID)

    '~~> Establish an EXCEL application object
    On Error Resume Next
    Set oXLApp = GetObject(, "Excel.Application")

    '~~> If not found then create new instance
    If Err.Number <> 0 Then
        Set oXLApp = CreateObject("Excel.Application")
    End If
    Err.Clear
    On Error GoTo 0

    '~~> Show Excel
    oXLApp.Visible = True

    '~~> Open the relevant file
    Set oXLwb = oXLApp.Workbooks.Open("C:\Sample.xls")

    '~~> Set the relevant output sheet. Change as applicable
    Set oXLws = oXLwb.Sheets("Sheet1")

    lRow = oXLws.Range("A" & oXLApp.Rows.Count).End(xlUp).Row + 1

    '~~> Write to outlook
    With oXLws
        '
        '~~> Code here to output data from email to Excel File
        '~~> For example
        '
        .Range("A" & lRow).Value = olMail.Subject
        .Range("B" & lRow).Value = olMail.SenderName
        '
    End With

    '~~> Close and Clean up Excel
    oXLwb.Close (True)
    oXLApp.Quit
    Set oXLws = Nothing
    Set oXLwb = Nothing
    Set oXLApp = Nothing

    Set olMail = Nothing
    Set olNS = Nothing
End Sub

FOLLOWUP

To extract the contents from your email body, you can split it using SPLIT() and then parsing out the relevant information from it. See this example

Dim MyAr() As String

MyAr = Split(olMail.body, vbCrLf)

For i = LBound(MyAr) To UBound(MyAr)
    '~~> This will give you the contents of your email
    '~~> on separate lines
    Debug.Print MyAr(i)
Next i

Execute curl command within a Python script

If you are not tweaking the curl command too much you can also go and call the curl command directly

import shlex
cmd = '''curl -X POST -d  '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001'''
args = shlex.split(cmd)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

how to File.listFiles in alphabetical order?

In Java 8:

Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));

Reverse order:

Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));

How to get multiple selected values from select box in JSP?

It would seem overkill but Spring Forms handles this elegantly. That is of course if you are already using Spring MVC and you want to take advantage of the Spring Forms feature.

// jsp form
    <form:select path="friendlyNumber" items="${friendlyNumberItems}" />

    // the command class
    public class NumberCmd {
      private String[] friendlyNumber;
    }

    // in your Spring MVC controller submit method
    @RequestMapping(method=RequestMethod.POST)
    public String manageOrders(@ModelAttribute("nbrCmd") NumberCmd nbrCmd){

       String[] selectedNumbers = nbrCmd.getFriendlyNumber();

    }

Create ArrayList from array

You can use the following 3 ways to create ArrayList from Array.

  String[] array = {"a", "b", "c", "d", "e"};

  //Method 1
  List<String> list = Arrays.asList(array);          

  //Method 2
  List<String> list1 = new ArrayList<String>();
  Collections.addAll(list1, array);

  //Method 3
  List<String> list2 = new ArrayList<String>();
  for(String text:array) {
     list2.add(text);
  }

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

For those that are not overflowing but hiding by negative margin:

$('#element').height() + -parseInt($('#element').css("margin-top"));

(ugly but only one that works so far)

How to import JsonConvert in C# application?

Tools -> NuGet Package Manager -> Package Manager Console

PM> Install-Package Newtonsoft.Json

Convert datetime value into string

Try this:

concat(left(datefield,10),left(timefield,8))
  • 10 char on date field based on full date yyyy-MM-dd.

  • 8 char on time field based on full time hh:mm:ss.

It depends on the format you want it. normally you can use script above and you can concat another field or string as you want it.

Because actually date and time field tread as string if you read it. But of course you will got error while update or insert it.

What is this date format? 2011-08-12T20:17:46.384Z

The T is just a literal to separate the date from the time, and the Z means "zero hour offset" also known as "Zulu time" (UTC). If your strings always have a "Z" you can use:

SimpleDateFormat format = new SimpleDateFormat(
    "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US);
format.setTimeZone(TimeZone.getTimeZone("UTC"));

Or using Joda Time, you can use ISODateTimeFormat.dateTime().

Stacked bar chart

You said :

Maybe my data.frame is not in a good format?

Yes this is true. Your data is in the wide format You need to put it in the long format. Generally speaking, long format is better for variables comparison.

Using reshape2 for example , you do this using melt:

dat.m <- melt(dat,id.vars = "Rank") ## just melt(dat) should work

Then you get your barplot:

ggplot(dat.m, aes(x = Rank, y = value,fill=variable)) +
    geom_bar(stat='identity')

But using lattice and barchart smart formula notation , you don't need to reshape your data , just do this:

barchart(F1+F2+F3~Rank,data=dat)

Origin null is not allowed by Access-Control-Allow-Origin

Origin null is the local file system, so that suggests that you're loading the HTML page that does the load call via a file:/// URL (e.g., just double-clicking it in a local file browser or similar). Different browsers take different approaches to applying the Same Origin Policy to local files.

My guess is that you're seeing this using Chrome. Chrome's rules for applying the SOP to local files are very tight, it disallows even loading files from the same directory as the document. So does Opera. Some other browsers, such as Firefox, allow limited access to local files. But basically, using ajax with local resources isn't going to work cross-browser.

If you're just testing something locally that you'll really be deploying to the web, rather than use local files, install a simple web server and test via http:// URLs instead. That gives you a much more accurate security picture.

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

How to make a <div> or <a href="#"> to align center

I don't know why but for me text-align:center; only works with:

text-align: grid;

OR

display: inline-grid;

I checked and no one style is overriding.

My structure:

<ul>
    <li>
        <a>ElementToCenter</a>
    </li>
</ul>

Disable Pinch Zoom on Mobile Web

This is all I needed:

<meta name="viewport" content="user-scalable=no"/>

Webpack - webpack-dev-server: command not found

For global installation : npm install webpack-dev-server -g

For local installation npm install --save-dev webpack

When you refer webpack in package.json file, it tries to look it in location node_modules\.bin\

After local installation, file wbpack will get created in location: \node_modules\.bin\webpack

unknown type name 'uint8_t', MinGW

Try including stdint.h or inttypes.h.

Saving a high resolution image in R

You can do the following. Add your ggplot code after the first line of code and end with dev.off().

tiff("test.tiff", units="in", width=5, height=5, res=300)
# insert ggplot code
dev.off()

res=300 specifies that you need a figure with a resolution of 300 dpi. The figure file named 'test.tiff' is saved in your working directory.

Change width and height in the code above depending on the desired output.

Note that this also works for other R plots including plot, image, and pheatmap.

Other file formats

In addition to TIFF, you can easily use other image file formats including JPEG, BMP, and PNG. Some of these formats require less memory for saving.

keycode 13 is for which key

The Enter key should have the keycode 13. Is it not working?

Link to Flask static files with url_for

In my case I had special instruction into nginx configuration file:

location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
            try_files $uri =404;
    }

All clients have received '404' because nginx nothing known about Flask.

I hope it help someone.

react-router getting this.props.location in child components

(Update) V5.1 & Hooks (Requires React >= 16.8)

You can use useHistory, useLocation and useRouteMatch in your component to get match, history and location .

const Child = () => {
  const location = useLocation();
  const history = useHistory();
  const match = useRouteMatch("write-the-url-you-want-to-match-here");

  return (
    <div>{location.pathname}</div>
  )
}

export default Child

(Update) V4 & V5

You can use withRouter HOC in order to inject match, history and location in your component props.

class Child extends React.Component {
  static propTypes = {
    match: PropTypes.object.isRequired,
    location: PropTypes.object.isRequired,
    history: PropTypes.object.isRequired
  }

  render() {
    const { match, location, history } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

(Update) V3

You can use withRouter HOC in order to inject router, params, location, routes in your component props.

class Child extends React.Component {

  render() {
    const { router, params, location, routes } = this.props

    return (
      <div>{location.pathname}</div>
    )
  }
}

export default withRouter(Child)

Original answer

If you don't want to use the props, you can use the context as described in React Router documentation

First, you have to set up your childContextTypes and getChildContext

class App extends React.Component{

  getChildContext() {
    return {
      location: this.props.location
    }
  }

  render() {
    return <Child/>;
  }
}

App.childContextTypes = {
    location: React.PropTypes.object
}

Then, you will be able to access to the location object in your child components using the context like this

class Child extends React.Component{

   render() {
     return (
       <div>{this.context.location.pathname}</div>
     )
   }

}

Child.contextTypes = {
    location: React.PropTypes.object
 }

Java synchronized method lock on object, or method?

If you declare the method as synchronized (as you're doing by typing public synchronized void addA()) you synchronize on the whole object, so two thread accessing a different variable from this same object would block each other anyway.

If you want to synchronize only on one variable at a time, so two threads won't block each other while accessing different variables, you have synchronize on them separately in synchronized () blocks. If a and b were object references you would use:

public void addA() {
    synchronized( a ) {
        a++;
    }
}

public void addB() {
    synchronized( b ) {
        b++;
    }
}

But since they're primitives you can't do this.

I would suggest you to use AtomicInteger instead:

import java.util.concurrent.atomic.AtomicInteger;

class X {

    AtomicInteger a;
    AtomicInteger b;

    public void addA(){
        a.incrementAndGet();
    }

    public void addB(){ 
        b.incrementAndGet();
    }
}

How to extract duration time from ffmpeg output?

If you want to retrieve the length (and possibly all other metadata) from your media file with ffmpeg by using a python script you could try this:

import subprocess
import json

input_file  = "< path to your input file here >"

metadata = subprocess.check_output(f"ffprobe -i {input_file} -v quiet -print_format json -show_format -hide_banner".split(" "))

metadata = json.loads(metadata)
print(f"Length of file is: {float(metadata['format']['duration'])}")
print(metadata)

Output:

Length of file is: 7579.977143

{
  "streams": [
    {
      "index": 0,
      "codec_name": "mp3",
      "codec_long_name": "MP3 (MPEG audio layer 3)",
      "codec_type": "audio",
      "codec_time_base": "1/44100",
      "codec_tag_string": "[0][0][0][0]",
      "codec_tag": "0x0000",
      "sample_fmt": "fltp",
      "sample_rate": "44100",
      "channels": 2,
      "channel_layout": "stereo",
      "bits_per_sample": 0,
      "r_frame_rate": "0/0",
      "avg_frame_rate": "0/0",
      "time_base": "1/14112000",
      "start_pts": 353600,
      "start_time": "0.025057",
      "duration_ts": 106968637440,
      "duration": "7579.977143",
      "bit_rate": "320000",
      ...
      ...

How to Read and Write from the Serial Port

I spent a lot of time to use SerialPort class and has concluded to use SerialPort.BaseStream class instead. You can see source code: SerialPort-source and SerialPort.BaseStream-source for deep understanding. I created and use code that shown below.

  • The core function public int Recv(byte[] buffer, int maxLen) has name and works like "well known" socket's recv().

  • It means that

    • in one hand it has timeout for no any data and throws TimeoutException.
    • In other hand, when any data has received,
      • it receives data either until maxLen bytes
      • or short timeout (theoretical 6 ms) in UART data flow

.

public class Uart : SerialPort

    {
        private int _receiveTimeout;

        public int ReceiveTimeout { get => _receiveTimeout; set => _receiveTimeout = value; }

        static private string ComPortName = "";

        /// <summary>
        /// It builds PortName using ComPortNum parameter and opens SerialPort.
        /// </summary>
        /// <param name="ComPortNum"></param>
        public Uart(int ComPortNum) : base()
        {
            base.BaudRate = 115200; // default value           
            _receiveTimeout = 2000;
            ComPortName = "COM" + ComPortNum;

            try
            {
                base.PortName = ComPortName;
                base.Open();
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Error: Port {0} is in use", ComPortName);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Uart exception: " + ex);
            }
        } //Uart()

        /// <summary>
        /// Private property returning positive only Environment.TickCount
        /// </summary>
        private int _tickCount { get => Environment.TickCount & Int32.MaxValue; }


        /// <summary>
        /// It uses SerialPort.BaseStream rather SerialPort functionality .
        /// It Receives up to maxLen number bytes of data, 
        /// Or throws TimeoutException if no any data arrived during ReceiveTimeout. 
        /// It works likes socket-recv routine (explanation in body).
        /// Returns:
        ///    totalReceived - bytes, 
        ///    TimeoutException,
        ///    -1 in non-ComPortNum Exception  
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="maxLen"></param>
        /// <returns></returns>
        public int Recv(byte[] buffer, int maxLen)
        {
            /// The routine works in "pseudo-blocking" mode. It cycles up to first 
            /// data received using BaseStream.ReadTimeout = TimeOutSpan (2 ms).
            /// If no any message received during ReceiveTimeout property, 
            /// the routine throws TimeoutException 
            /// In other hand, if any data has received, first no-data cycle
            /// causes to exit from routine.

            int TimeOutSpan = 2;
            // counts delay in TimeOutSpan-s after end of data to break receive
            int EndOfDataCnt;
            // pseudo-blocking timeout counter
            int TimeOutCnt = _tickCount + _receiveTimeout; 
            //number of currently received data bytes
            int justReceived = 0;
            //number of total received data bytes
            int totalReceived = 0;

            BaseStream.ReadTimeout = TimeOutSpan;
            //causes (2+1)*TimeOutSpan delay after end of data in UART stream
            EndOfDataCnt = 2;
            while (_tickCount < TimeOutCnt && EndOfDataCnt > 0)
            {
                try
                {
                    justReceived = 0; 
                    justReceived = base.BaseStream.Read(buffer, totalReceived, maxLen - totalReceived);
                    totalReceived += justReceived;

                    if (totalReceived >= maxLen)
                        break;
                }
                catch (TimeoutException)
                {
                    if (totalReceived > 0) 
                        EndOfDataCnt--;
                }
                catch (Exception ex)
                {                   
                    totalReceived = -1;
                    base.Close();
                    Console.WriteLine("Recv exception: " + ex);
                    break;
                }

            } //while
            if (totalReceived == 0)
            {              
                throw new TimeoutException();
            }
            else
            {               
                return totalReceived;
            }
        } // Recv()            
    } // Uart

Provisioning Profiles menu item missing from Xcode 5

Provisioning files are located in:

/Users/${USER}/Library/MobileDevice/Provisioning Profiles/

Just remove the out-of-date files.

Lodash remove duplicates from array

_.unique no longer works for the current version of Lodash as version 4.0.0 has this breaking change. The functionality of _.unique was splitted into _.uniq, _.sortedUniq, _.sortedUniqBy, and _.uniqBy.

You could use _.uniqBy like this:

_.uniqBy(data, function (e) {
  return e.id;
});

...or like this:

_.uniqBy(data, 'id');

Documentation: https://lodash.com/docs#uniqBy


For older versions of Lodash (< 4.0.0 ):

Assuming that the data should be uniqued by each object's id property and your data is stored in data variable, you can use the _.unique() function like this:

_.unique(data, function (e) {
  return e.id;
});

Or simply like this:

_.uniq(data, 'id');

Sonar properties files

Do the build job on Jenkins first without Sonar configured. Then add Sonar, and run a build job again. Should fix the problem

When do I need a fb:app_id or fb:admins?

To use the Like Button and have the Open Graph inspect your website, you need an application.

So you need to associate the Like Button with a fb:app_id

If you want other users to see the administration page for your website on Facebook you add fb:admins. So if you are the developer of the application and the website owner there is no need to add fb:admins

Setting Elastic search limit to "unlimited"

From the docs, "Note that from + size can not be more than the index.max_result_window index setting which defaults to 10,000". So my admittedly very ad-hoc solution is to just pass size: 10000 or 10,000 minus from if I use the from argument.

Note that following Matt's comment below, the proper way to do this if you have a larger amount of documents is to use the scroll api. I have used this successfully, but only with the python interface.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

If you're looking to paginate results, use the integrated paginator, it works great!

$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages

Add line break within tooltips

So if you are using bootstrap4 then this will work.

<style>
   .tooltip-inner {
    white-space: pre-wrap;
   }

</style>

<script> 
    $(function () {
      $('[data-toggle="tooltip"]').tooltip()
    })
</script>

<a data-toggle="tooltip" data-placement="auto" title=" first line &#010; next line" href= ""> Hover me </a>

If you are using in Django project then we can also display dynamic data in tooltips like:

<a class="black-text pb-2 pt-1" data-toggle="tooltip" data-placement="auto"  title="{{ post.location }} &#010; {{ post.updated_on }}" href= "{% url 'blog:get_user_profile' post.author.id %}">{{ post.author }}</a>

How to define an enum with string value?

It works for me..

   public class ShapeTypes
    {
        private ShapeTypes() { }
        public static string OVAL
        {
            get
            {
                return "ov";
            }
            private set { }
        }

        public static string SQUARE
        {
            get
            {
                return "sq";
            }
            private set { }
        }

        public static string RECTANGLE
        {
            get
            {
                return "rec";
            }
            private set { }
        }
    }

Get current cursor position in a textbox

Here's one possible method.

function isMouseInBox(e) {
  var textbox = document.getElementById('textbox');

  // Box position & sizes
  var boxX = textbox.offsetLeft;
  var boxY = textbox.offsetTop;
  var boxWidth = textbox.offsetWidth;
  var boxHeight = textbox.offsetHeight;

  // Mouse position comes from the 'mousemove' event
  var mouseX = e.pageX;
  var mouseY = e.pageY;
  if(mouseX>=boxX && mouseX<=boxX+boxWidth) {
    if(mouseY>=boxY && mouseY<=boxY+boxHeight){
       // Mouse is in the box
       return true;
    }
  }
}

document.addEventListener('mousemove', function(e){
    isMouseInBox(e);
})

Android: How to stretch an image to the screen width while maintaining aspect ratio?

Everyone is doing this programmily so I thought this answer would fit perfectly here. This code worked for my in the xml. Im NOT thinking about ratio yet, but still wanted to place this answer if it would help anyone.

android:adjustViewBounds="true"

Cheers..

Insert all data of a datagridview to database at once

I think the best way is by using TableAdapters rather than using Commands objects, its Update method sends all changes mades (Updates,Inserts and Deletes) inside a Dataset or DataTable straight TO the database. Usually when using a DataGridView you bind to a BindingSource which lets you interact with a DataSource such as Datatables or Datasets.

If you work like this, then on your bounded DataGridView you can just do:

this.customersBindingSource.EndEdit();
this.myTableAdapter.Update(this.myDataSet.Customers);

The 'customersBindingSource' is the DataSource of the DataGridView.

The adapter's Update method will update a single data table and execute the correct command (INSERT, UPDATE, or DELETE) based on the RowState of each data row in the table.

From: https://msdn.microsoft.com/en-us/library/ms171933.aspx

So any changes made inside the DatagridView will be reflected on the Database when using the Update method.

More about TableAdapters: https://msdn.microsoft.com/en-us/library/bz9tthwx.aspx

Javascript close alert box

The only real alternative here is to use some sort of custom widget with a modal option. Have a look at jQuery UI for an example of a dialog with these features. Similar things exist in just about every JS framework you can mention.

Python + Django page redirect

Beware. I did this on a development server and wanted to change it later.

I had to clear my caches to change it. In order to avoid this head-scratching in the future, I was able to make it temporary like so:

from django.views.generic import RedirectView

url(r'^source$', RedirectView.as_view(permanent=False, 
                                      url='/dest/')),

How to get file_get_contents() to work with HTTPS?

Try the following.

function getSslPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

Note: This disables SSL verification, meaning the security offered by HTTPS is lost. Only use this code for testing / local development, never on the internet or other public-facing networks. If this code works, it means the SSL certificate isn't trusted or can't be verified, which you should look into fixing as a separate issue.

How to add number of days in postgresql datetime

For me I had to put the whole interval in single quotes not just the value of the interval.

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

Instead of

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres Date/Time Functions

Update query PHP MySQL

First, you should define "doesn't work".
Second, I assume that your table field 'content' is varchar/text, so you need to enclose it in quotes. content = '{$content}'
And last but not least: use echo mysql_error() directly after a query to debug.

Facebook Callback appends '#_=_' to Return URL

For me, i make JavaScript redirection to another page to get rid of #_=_. The ideas below should work. :)

function redirect($url){
    echo "<script>window.location.href='{$url}?{$_SERVER["QUERY_STRING"]}'</script>";        
}

How do I convert between big-endian and little-endian values in C++?

i like this one, just for style :-)

long swap(long i) {
    char *c = (char *) &i;
    return * (long *) (char[]) {c[3], c[2], c[1], c[0] };
}

How to specify test directory for mocha?

Use this:

mocha server-test

Or if you have subdirectories use this:

mocha "server-test/**/*.js"

Note the use of double quotes. If you omit them you may not be able to run tests in subdirectories.

Dynamically display a CSV file as an HTML table on a web page

Does it work if you escape the quoted commas with \ ?

Name, Age, Sex

"Cantor\, Georg", 163,M

Most delimited formats require that their delimiter be escaped in order to properly parse.


A rough Java example:

import java.util.Iterator;

public class CsvTest {

    public static void main(String[] args) {
        String[] lines = { "Name, Age, Sex", "\"Cantor, Georg\", 163, M" };

        StringBuilder result = new StringBuilder();

        for (String head : iterator(lines[0])) {
            result.append(String.format("<tr>%s</tr>\n", head));
        }

        for (int i=1; i < lines.length; i++) {
            for (String row : iterator(lines[i])) {
                result.append(String.format("<td>%s</td>\n", row));
            }
        }

        System.out.println(String.format("<table>\n%s</table>", result.toString()));
    }

    public static Iterable<String> iterator(final String line) {
        return new Iterable<String>() {
            public Iterator<String> iterator() {
                return new Iterator<String>() {
                    private int position = 0;

                    public boolean hasNext() {
                        return position < line.length();
                    }

                    public String next() {
                        boolean inquote = false;
                        StringBuilder buffer = new StringBuilder();
                        for (; position < line.length(); position++) {
                            char c = line.charAt(position);
                            if (c == '"') {
                                inquote = !inquote;
                            }
                            if (c == ',' && !inquote) {
                                position++;
                                break;
                            } else {
                                buffer.append(c);
                            }
                        }
                        return buffer.toString().trim();
                    }

                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                };
            }
        };
    }
}

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.

How do I override nested NPM dependency versions?

For those using yarn.

I tried using npm shrinkwrap until I discovered the yarn cli ignored my npm-shrinkwrap.json file.

Yarn has https://yarnpkg.com/lang/en/docs/selective-version-resolutions/ for this. Neat.

Check out this answer too: https://stackoverflow.com/a/41082766/3051080

Android: keep Service running when app is killed

inside onstart command put START_STICKY... This service won't kill unless it is doing too much task and kernel wants to kill it for it...

@Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.i("LocalService", "Received start id " + startId + ": " + intent);
            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            return START_STICKY;
        }

How to force input to only allow Alpha Letters?

Nice one-liner HTML only:

 <input type="text" id='nameInput' onkeypress='return ((event.charCode >= 65 && event.charCode <= 90) || (event.charCode >= 97 && event.charCode <= 122) || (event.charCode == 32))'>

Flutter - Wrap text on overflow, like insert ellipsis or fade

Depending on your situation, I think this is the best approach below.

final maxWidth = MediaQuery.of(context).size.width * 0.4;
Container(
        textAlign: TextAlign.center),
        child: Text('This is long text',
        constraints: BoxConstraints(maxWidth: maxWidth),
),

How do you find the current user in a Windows environment?

%USERNAME% will get you the username of the currently running process. Depending on how you are running your batch file, this is not necessarily the same as the name of the current user. For example, you might be running your batch file through a scheduled task, from a service, etc.

Here is a more sure way of getting the username of the currently logged on user by scraping the name of the user that started the explorer.exe task:

for /f "TOKENS=1,2,*" %%a in ('tasklist /FI "IMAGENAME eq explorer.exe" /FO LIST /V') do if /i "%%a %%b"=="User Name:" set _currdomain_user=%%c
for /f "TOKENS=1,2 DELIMS=\" %%a in ("%_currdomain_user%") do set _currdomain=%%a & set _curruser=%%b

Unable to set default python version to python3 in ubuntu

This is a simple way that works for me.

sudo ln -s /usr/bin/python3 /usr/bin/python

You could change /usr/bin/python3 for your path to python3 (or the version you want).

But keep in mind that update-alternatives is probably the best choice.

Force download a pdf link using javascript/ajax/jquery

If htaccess is an option this will make all PDF links download instead of opening in browser

<FilesMatch "\.(?i:pdf)$">
  ForceType application/octet-stream
  Header set Content-Disposition attachment
</FilesMatch>

How to get today's Date?

If you want midnight (0:00am) for the current date, you can just use the default constructor and zero out the time portions:

Date today = new Date();
today.setHours(0); today.setMinutes(0); today.setSeconds(0);

edit: update with Calendar since those methods are deprecated

Calendar today = Calendar.getInstance();
today.clear(Calendar.HOUR); today.clear(Calendar.MINUTE); today.clear(Calendar.SECOND);
Date todayDate = today.getTime();

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

How can I detect when an Android application is running in the emulator?

I've collected all the answers on this question and came up with function to detect if Android is running on a vm/emulator:

public boolean isvm(){


        StringBuilder deviceInfo = new StringBuilder();
        deviceInfo.append("Build.PRODUCT " +Build.PRODUCT +"\n");
        deviceInfo.append("Build.FINGERPRINT " +Build.FINGERPRINT+"\n");
        deviceInfo.append("Build.MANUFACTURER " +Build.MANUFACTURER+"\n");
        deviceInfo.append("Build.MODEL " +Build.MODEL+"\n");
        deviceInfo.append("Build.BRAND " +Build.BRAND+"\n");
        deviceInfo.append("Build.DEVICE " +Build.DEVICE+"\n");
        String info = deviceInfo.toString();


        Log.i("LOB", info);


        Boolean isvm = false;
        if(
                "google_sdk".equals(Build.PRODUCT) ||
                "sdk_google_phone_x86".equals(Build.PRODUCT) ||
                "sdk".equals(Build.PRODUCT) ||
                "sdk_x86".equals(Build.PRODUCT) ||
                "vbox86p".equals(Build.PRODUCT) ||
                Build.FINGERPRINT.contains("generic") ||
                Build.MANUFACTURER.contains("Genymotion") ||
                Build.MODEL.contains("Emulator") ||
                Build.MODEL.contains("Android SDK built for x86")
                ){
            isvm =  true;
        }


        if(Build.BRAND.contains("generic")&&Build.DEVICE.contains("generic")){
            isvm =  true;
        }

        return isvm;
    }

Tested on Emulator, Genymotion and Bluestacks (1 October 2015).

What is the role of "Flatten" in Keras?

I came across this recently, it certainly helped me understand: https://www.cs.ryerson.ca/~aharley/vis/conv/

So there's an input, a Conv2D, MaxPooling2D etc, the Flatten layers are at the end and show exactly how they are formed and how they go on to define the final classifications (0-9).

Converting two lists into a matrix

The standard numpy function for what you want is np.column_stack:

>>> np.column_stack(([1, 2, 3], [4, 5, 6]))
array([[1, 4],
       [2, 5],
       [3, 6]])

So with your portfolio and index arrays, doing

np.column_stack((portfolio, index))

would yield something like:

[[portfolio_value1, index_value1],
 [portfolio_value2, index_value2],
 [portfolio_value3, index_value3],
 ...]

Show div when radio button selected

I would handle it like so:

$(document).ready(function() {
   $('input[type="radio"]').click(function() {
       if($(this).attr('id') == 'watch-me') {
            $('#show-me').show();           
       }

       else {
            $('#show-me').hide();   
       }
   });
});

How Should I Set Default Python Version In Windows?

This worked for me:

Go to

Control Panel\System and Security\System

select

Advanced system settings from the left panel
from Advanced tab click on Environment Variables

In the System variables section search for (create if doesn't exist)

PYTHONPATH

and set

C:\Python27\;C:\Python27\Scripts;

or your desired version

You need to restart CMD.

In case it still doesn't work you might want to leave in the PATH variable only your desired version.

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

Remove a prefix from a string

I think you can use methods of the str type to do this. There's no need for regular expressions:

def remove_prefix(text, prefix):
    if text.startswith(prefix): # only modify the text if it starts with the prefix
         text = text.replace(prefix, "", 1) # remove one instance of prefix
    return text

operator << must take exactly one argument

A friend function is not a member function, so the problem is that you declare operator<< as a friend of A:

 friend ostream& operator<<(ostream&, A&);

then try to define it as a member function of the class logic

 ostream& logic::operator<<(ostream& os, A& a)
          ^^^^^^^

Are you confused about whether logic is a class or a namespace?

The error is because you've tried to define a member operator<< taking two arguments, which means it takes three arguments including the implicit this parameter. The operator can only take two arguments, so that when you write a << b the two arguments are a and b.

You want to define ostream& operator<<(ostream&, const A&) as a non-member function, definitely not as a member of logic since it has nothing to do with that class!

std::ostream& operator<<(std::ostream& os, const A& a)
{
  return os << a.number;
}

Why does range(start, end) not include end?

Because it's more common to call range(0, 10) which returns [0,1,2,3,4,5,6,7,8,9] which contains 10 elements which equals len(range(0, 10)). Remember that programmers prefer 0-based indexing.

Also, consider the following common code snippet:

for i in range(len(li)):
    pass

Could you see that if range() went up to exactly len(li) that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++) over for(int i = 0; i <= 9; i++).

If you are calling range with a start of 1 frequently, you might want to define your own function:

>>> def range1(start, end):
...     return range(start, end+1)
...
>>> range1(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

ES6 export all values from object

export const a = 1;
export const b = 2;
export const c = 3;

This will work w/ Babel transforms today and should take advantage of all the benefits of ES2016 modules whenever that feature actually lands in a browser.

You can also add export default {a, b, c}; which will allow you to import all the values as an object w/o the * as, i.e. import myModule from 'my-module';

Sources:

How to change menu item text dynamically in Android

You better use the override onPrepareOptionsMenu

menu.Clear ();
   if (TabActual == TabSelec.Anuncio)
   {
       menu.Add(10, 11, 0, "Crear anuncio");
       menu.Add(10, 12, 1, "Modificar anuncio");
       menu.Add(10, 13, 2, "Eliminar anuncio");
       menu.Add(10, 14, 3, "Actualizar");
   }
   if (TabActual == TabSelec.Fotos)
   {
       menu.Add(20, 21, 0, "Subir foto");
       menu.Add(20, 22, 1, "Actualizar");
   }
   if (TabActual == TabSelec.Comentarios)
   {
       menu.Add(30, 31, 0, "Actualizar");
   }

Here an example

With MySQL, how can I generate a column containing the record index in a table?

You can also use

SELECT @curRow := ifnull(@curRow,0) + 1 Row, ...

to initialise the counter variable.

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

How to iterate over a TreeMap?

    //create TreeMap instance
    TreeMap treeMap = new TreeMap();

    //add key value pairs to TreeMap
    treeMap.put("1","One");
    treeMap.put("2","Two");
    treeMap.put("3","Three");

    /*
      get Collection of values contained in TreeMap using
      Collection values()        
    */
    Collection c = treeMap.values();

    //obtain an Iterator for Collection
    Iterator itr = c.iterator();

    //iterate through TreeMap values iterator
    while(itr.hasNext())
      System.out.println(itr.next());

or:

   for (Map.Entry<K,V> entry : treeMap.entrySet()) {
        V value = entry.getValue();
        K key = entry.getKey();
   }

or:

   // Use iterator to display the keys and associated values
   System.out.println("Map Values Before: ");
   Set keys = map.keySet();
   for (Iterator i = keys.iterator(); i.hasNext();) {
     Integer key = (Integer) i.next();
     String value = (String) map.get(key);
     System.out.println(key + " = " + value);
   }

Why am I getting a " Traceback (most recent call last):" error?

I don't know which version of Python you are using but I tried this in Python 3 and made a few changes and it looks like it works. The raw_input function seems to be the issue here. I changed all the raw_input functions to "input()" and I also made minor changes to the printing to be compatible with Python 3. AJ Uppal is correct when he says that you shouldn't name a variable and a function with the same name. See here for reference:

TypeError: 'int' object is not callable

My code for Python 3 is as follows:

# https://stackoverflow.com/questions/27097039/why-am-i-getting-a-traceback-most-recent-call-last-error

raw_input = 0
M = 1.6
# Miles to Kilometers
# Celsius Celsius = (var1 - 32) * 5/9
# Gallons to liters Gallons = 3.6
# Pounds to kilograms Pounds = 0.45
# Inches to centimete Inches = 2.54


def intro():
    print("Welcome! This program will convert measures for you.")
    main()

def main():
    print("Select operation.")
    print("1.Miles to Kilometers")
    print("2.Fahrenheit to Celsius")
    print("3.Gallons to liters")
    print("4.Pounds to kilograms")
    print("5.Inches to centimeters")

    choice = input("Enter your choice by number: ")

    if choice == '1':
        convertMK()

    elif choice == '2':
        converCF()

    elif choice == '3':
        convertGL()

    elif choice == '4':
        convertPK()

    elif choice == '5':
        convertPK()

    else:
        print("Error")


def convertMK():
    input_M = float(input(("Miles: ")))
    M_conv = (M) * input_M
    print("Kilometers: {M_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def converCF():
    input_F = float(input(("Fahrenheit: ")))
    F_conv = (input_F - 32) * 5/9
    print("Celcius: {F_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print("I didn't quite understand that answer. Terminating.")
        main()

def convertGL():
    input_G = float(input(("Gallons: ")))
    G_conv = input_G * 3.6
    print("Centimeters: {G_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def convertIC():
    input_cm = float(input(("Inches: ")))
    inches_conv = input_cm * 2.54
    print("Centimeters: {inches_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

def end():
    print("This program will close.")
    exit()

intro()

I noticed a small bug in your code as well. This function should ideally convert pounds to kilograms but it looks like when it prints, it is printing "Centimeters" instead of kilograms.

def convertPK():
    input_P = float(input(("Pounds: ")))
    P_conv = input_P * 0.45
    # Printing error in the line below
    print("Centimeters: {P_conv}\n")
    restart = str(input("Do you wish to make another conversion? [y]Yes or [n]no: "))
    if restart == 'y':
        main()
    elif restart == 'n':
        end()
    else:
        print ("I didn't quite understand that answer. Terminating.")
        main()

I hope this helps.

Android - drawable with rounded corners at the top only

In my case below code

    <?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:top="10dp" android:bottom="-10dp"
        >

        <shape android:shape="rectangle">
            <solid android:color="@color/maincolor" />

            <corners
                android:topLeftRadius="10dp"
                android:topRightRadius="10dp"
                android:bottomLeftRadius="0dp"
                android:bottomRightRadius="0dp"
            />
        </shape>

    </item>
    </layer-list>

How do I install Python libraries in wheel format?

If you want to be relax for installing libraries for python.

You should using pip, that is python installer package.

To install pip:

  1. Download ez_setup.py and then run:

    python ez_setup.py
    
  2. Then download get-pip.py and run:

    python get-pip.py
    
  3. upgrade installed setuptools by pip:

    pip install setuptools --upgrade
    

    If you got this error:

    Wheel installs require setuptools >= 0.8 for dist-info support.
    pip's wheel support requires setuptools >= 0.8 for dist-info support.
    

    Add --no-use-wheel to above cmd:

    pip install setuptools --no-use-wheel --upgrade
    

Now, you can install libraries for python, just by:

pip install library_name

For example:

pip install requests

Note that to install some library may they need to compile, so you need to have compiler.

On windows there is a site for Unofficial Windows Binaries for Python Extension Packages that have huge python packages and complied python packages for windows.

For example to install pip using this site, just download and install setuptools and pip installer from that.

How can I set the value of a DropDownList using jQuery?

There are many ways to do it. here are some of them:

$("._statusDDL").val('2');

OR

$('select').prop('selectedIndex', 3);

AddTransient, AddScoped and AddSingleton Services Differences

Which one to use

Transient

  • since they are created every time they will use more memory & Resources and can have the negative impact on performance
  • use this for the lightweight service with little or no state.

Scoped

  • better option when you want to maintain state within a request.

Singleton

  • memory leaks in these services will build up over time.
  • also memory efficient as they are created once reused everywhere.

Use Singletons where you need to maintain application wide state. Application configuration or parameters, Logging Service, caching of data is some of the examples where you can use singletons.

Injecting service with different lifetimes into another

  1. Never inject Scoped & Transient services into Singleton service. ( This effectively converts the transient or scoped service into the singleton.)
  2. Never inject Transient services into scoped service ( This converts the transient service into the scoped. )

How to start a Process as administrator mode in C#

 Process proc = new Process();                                                              
                   ProcessStartInfo info = 
                   new ProcessStartInfo("Your Process name".exe, "Arguments");
                   info.WindowStyle = ProcessWindowStyle.Hidden;
                   info.UseShellExecute =true;
                   info.Verb ="runas";
                   proc.StartInfo = info;
                   proc.Start();

How to clean old dependencies from maven repositories?

You need to copy the dependency you need for project. Having these in hand please clear all the <dependency> tag embedded into <dependencies> tag from POM.XML file in your project.

After saving the file you will not see Maven Dependencies in your Libraries. Then please paste those <dependency> you have copied earlier.

The required jars will be automatically downloaded by Maven, you can see that too in the generated Maven Dependencies Libraries after saving the file.

Thanks.