Programs & Examples On #File globs

IN-clause in HQL or Java Persistence Query Language

Are you using Hibernate's Query object, or JPA? For JPA, it should work fine:

String jpql = "from A where name in (:names)";
Query q = em.createQuery(jpql);
q.setParameter("names", l);

For Hibernate's, you'll need to use the setParameterList:

String hql = "from A where name in (:names)";
Query q = s.createQuery(hql);
q.setParameterList("names", l);

Error: "setFile(null,false) call failed" when using log4j

Have a look at the error - 'log4j:ERROR setFile(null,false) call failed. java.io.FileNotFoundException: logs (Access is denied)'

It seems there's a log file named as 'logs' to which access is denied i.e it is not having sufficient permissions to write logs. Try by giving write permissions to the 'logs' log file. Hope it helps.

Find the version of an installed npm package

If you'd like to check for a particular module installed globally, on *nix systems use:

npm list -g --depth=0 | grep <module_name>

Generating all permutations of a given string

Let's use input abc as an example.

Start off with just the last element (c) in a set (["c"]), then add the second last element (b) to its front, end and every possible positions in the middle, making it ["bc", "cb"] and then in the same manner it will add the next element from the back (a) to each string in the set making it:

"a" + "bc" = ["abc", "bac", "bca"]  and  "a" + "cb" = ["acb" ,"cab", "cba"] 

Thus entire permutation:

["abc", "bac", "bca","acb" ,"cab", "cba"]

Code:

public class Test 
{
    static Set<String> permutations;
    static Set<String> result = new HashSet<String>();

    public static Set<String> permutation(String string) {
        permutations = new HashSet<String>();

        int n = string.length();
        for (int i = n - 1; i >= 0; i--) 
        {
            shuffle(string.charAt(i));
        }
        return permutations;
    }

    private static void shuffle(char c) {
        if (permutations.size() == 0) {
            permutations.add(String.valueOf(c));
        } else {
            Iterator<String> it = permutations.iterator();
            for (int i = 0; i < permutations.size(); i++) {

                String temp1;
                for (; it.hasNext();) {
                    temp1 = it.next();
                    for (int k = 0; k < temp1.length() + 1; k += 1) {
                        StringBuilder sb = new StringBuilder(temp1);

                        sb.insert(k, c);

                        result.add(sb.toString());
                    }
                }
            }
            permutations = result;
            //'result' has to be refreshed so that in next run it doesn't contain stale values.
            result = new HashSet<String>();
        }
    }

    public static void main(String[] args) {
        Set<String> result = permutation("abc");

        System.out.println("\nThere are total of " + result.size() + " permutations:");
        Iterator<String> it = result.iterator();
        while (it.hasNext()) {
            System.out.println(it.next());
        }
    }
}

Hex to ascii string conversion

you need to take 2 (hex) chars at the same time... then calculate the int value and after that make the char conversion like...

char d = (char)intValue;

do this for every 2chars in the hex string

this works if the string chars are only 0-9A-F:

#include <stdio.h>
#include <string.h>

int hex_to_int(char c){
        int first = c / 16 - 3;
        int second = c % 16;
        int result = first*10 + second;
        if(result > 9) result--;
        return result;
}

int hex_to_ascii(char c, char d){
        int high = hex_to_int(c) * 16;
        int low = hex_to_int(d);
        return high+low;
}

int main(){
        const char* st = "48656C6C6F3B";
        int length = strlen(st);
        int i;
        char buf = 0;
        for(i = 0; i < length; i++){
                if(i % 2 != 0){
                        printf("%c", hex_to_ascii(buf, st[i]));
                }else{
                        buf = st[i];
                }
        }
}

Business logic in MVC

A1: Business Logic goes to Model part in MVC. Role of Model is to contain data and business logic. Controller on the other hand is responsible to receive user input and decide what to do.

A2: A Business Rule is part of Business Logic. They have a has a relationship. Business Logic has Business Rules.

Take a look at Wikipedia entry for MVC. Go to Overview where it mentions the flow of MVC pattern.

Also look at Wikipedia entry for Business Logic. It is mentioned that Business Logic is comprised of Business Rules and Workflow.

Retrieving a property of a JSON object by index?

My solution:

Object.prototype.__index=function(index)
                         {var i=-1;
                          for (var key in this)
                              {if (this.hasOwnProperty(key) && typeof(this[key])!=='function')
                                  {++i;
                                  }
                               if (i>=index)
                                  {return this[key];
                                  }
                              }
                          return null;
                         }
aObj={'jack':3, 'peter':4, '5':'col', 'kk':function(){alert('hell');}, 'till':'ding'};
alert(aObj.__index(4));

Environment variables in Eclipse

You can set the Hadoop home directory by sending a -Dhadoop.home.dir to the VM. To send this parameters to all your application that you execute inside eclipse, you can set them in Window->Preferences->Java->Installed JREs-> (select your JRE installation) -> Edit.. -> (set the value in the "Default VM arguments:" textbox). You can replace ${HADOOP_HOME} with the path to your Hadoop installation.

Select the JRE you use for running programs in Eclipse

Sending the value for hadoop.home.dir property as a VM argument

Play audio with Python

It's Simple. I did it this way.

For a wav file

from IPython.display import Audio
from scipy.io.wavfile import read

fs, data = read('StarWars60.wav', mmap=True)  # fs - sampling frequency
data = data.reshape(-1, 1)
Audio(data = data[:, 0], rate = fs)

For mp3 file

import IPython.display import Audio

Audio('audio_file_name.mp3')

How to get the new value of an HTML input after a keypress has modified it?

You can try this code (requires jQuery):

<html>
<head>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#foo').keyup(function(e) {
                var v = $('#foo').val();
                $('#debug').val(v);
            })
        });
    </script>
</head>
<body>
    <form>
        <input type="text" id="foo" value="bar"><br>
        <textarea id="debug"></textarea>
    </form>
</body>
</html>

java create date object using a value string

FIRST OF ALL KNOW THE REASON WHY ECLIPSE IS DOING SO.

Date has only one constructor Date(long date) which asks for date in long data type.

The constructor you are using

Date(String s) Deprecated. As of JDK version 1.1, replaced by DateFormat.parse(String s).

Thats why eclipse tells that this function is not good.

See this official docs

http://docs.oracle.com/javase/6/docs/api/java/util/Date.html


Deprecated methods from your context -- Source -- http://www.coderanch.com/t/378728/java/java/Deprecated-methods

There are a number of reasons why a method or class may become deprecated. An API may not be easily extensible without breaking backwards compatibility, and thus be superseded by a more powerful API (e.g., java.util.Date has been deprecated in favor of Calendar, or the Java 1.0 event model). It may also simply not work or produce incorrect results under certain circumstances (e.g., some of the java.io stream classes do not work properly with some encodings). Sometimes an API is just ill-conceived (SingleThreadModel in the servlet API), and gets replaced by nothing. And some of the early calls have been replaced by "Java Bean"-compatible methods (size by getSize, bounds by getBounds etc.)


SEVRAL SOLUTIONS ARE THERE JUST GOOGLE IT--

You can use date(long date) By converting your date String into long milliseconds and stackoverflow has so many post for that purpose.

converting a date string into milliseconds in java

Styling multi-line conditions in 'if' statements?

This doesn't improve so much but...

allCondsAreOK = (cond1 == 'val1' and cond2 == 'val2' and
                 cond3 == 'val3' and cond4 == 'val4')

if allCondsAreOK:
   do_something

git: Switch branch and ignore any changes without committing

To switch to other branch without committing the changes when git stash doesn't work. You can use the below command:

git checkout -f branch-name

Can I rollback a transaction I've already committed? (data loss)

No, you can't undo, rollback or reverse a commit.

STOP THE DATABASE!

(Note: if you deleted the data directory off the filesystem, do NOT stop the database. The following advice applies to an accidental commit of a DELETE or similar, not an rm -rf /data/directory scenario).

If this data was important, STOP YOUR DATABASE NOW and do not restart it. Use pg_ctl stop -m immediate so that no checkpoint is run on shutdown.

You cannot roll back a transaction once it has commited. You will need to restore the data from backups, or use point-in-time recovery, which must have been set up before the accident happened.

If you didn't have any PITR / WAL archiving set up and don't have backups, you're in real trouble.

Urgent mitigation

Once your database is stopped, you should make a file system level copy of the whole data directory - the folder that contains base, pg_clog, etc. Copy all of it to a new location. Do not do anything to the copy in the new location, it is your only hope of recovering your data if you do not have backups. Make another copy on some removable storage if you can, and then unplug that storage from the computer. Remember, you need absolutely every part of the data directory, including pg_xlog etc. No part is unimportant.

Exactly how to make the copy depends on which operating system you're running. Where the data dir is depends on which OS you're running and how you installed PostgreSQL.

Ways some data could've survived

If you stop your DB quickly enough you might have a hope of recovering some data from the tables. That's because PostgreSQL uses multi-version concurrency control (MVCC) to manage concurrent access to its storage. Sometimes it will write new versions of the rows you update to the table, leaving the old ones in place but marked as "deleted". After a while autovaccum comes along and marks the rows as free space, so they can be overwritten by a later INSERT or UPDATE. Thus, the old versions of the UPDATEd rows might still be lying around, present but inaccessible.

Additionally, Pg writes in two phases. First data is written to the write-ahead log (WAL). Only once it's been written to the WAL and hit disk, it's then copied to the "heap" (the main tables), possibly overwriting old data that was there. The WAL content is copied to the main heap by the bgwriter and by periodic checkpoints. By default checkpoints happen every 5 minutes. If you manage to stop the database before a checkpoint has happened and stopped it by hard-killing it, pulling the plug on the machine, or using pg_ctl in immediate mode you might've captured the data from before the checkpoint happened, so your old data is more likely to still be in the heap.

Now that you have made a complete file-system-level copy of the data dir you can start your database back up if you really need to; the data will still be gone, but you've done what you can to give yourself some hope of maybe recovering it. Given the choice I'd probably keep the DB shut down just to be safe.

Recovery

You may now need to hire an expert in PostgreSQL's innards to assist you in a data recovery attempt. Be prepared to pay a professional for their time, possibly quite a bit of time.

I posted about this on the Pg mailing list, and ?????? ?????? linked to depesz's post on pg_dirtyread, which looks like just what you want, though it doesn't recover TOASTed data so it's of limited utility. Give it a try, if you're lucky it might work.

See: pg_dirtyread on GitHub.

I've removed what I'd written in this section as it's obsoleted by that tool.

See also PostgreSQL row storage fundamentals

Prevention

See my blog entry Preventing PostgreSQL database corruption.


On a semi-related side-note, if you were using two phase commit you could ROLLBACK PREPARED for a transction that was prepared for commit but not fully commited. That's about the closest you get to rolling back an already-committed transaction, and does not apply to your situation.

How to get the focused element with jQuery?

If you want to confirm if focus is with an element then

if ($('#inputId').is(':focus')) {
    //your code
}

Switch: Multiple values in one case?

In C# 7 it's possible to use a when clause in a case statement.

int age = 12;
switch (age) 
{
  case int i when i >=1 && i <= 8:
    System.Console.WriteLine("You are only " + age + " years old. You must be kidding right. Please fill in your *real* age.");
    break;
  case int i when i >=9 && i <= 15:
    System.Console.WriteLine("You are only " + age + " years old. That's too young!");
    break;
  case int i when i >=16 && i <= 100:
    System.Console.WriteLine("You are " + age + " years old. Perfect.");
    break;
  default:
    System.Console.WriteLine("You an old person.");
    break;
}

Update .NET web service to use TLS 1.2

PowerBI Embedded requires TLS 1.2.

The answer above by Etienne Faucher is your solution. quick link to above answer... quick link to above answer... ( https://stackoverflow.com/a/45442874 )

PowerBI Requires TLS 1.2 June 2020 - This Is your Answer - Consider Forcing your IIS runtime to get up to 4.6 to force the default TLS 1.2 behavior you are looking for from the framework. The above answer gives you a config change only solution.

Symptoms: Forced Closed Rejected TCP/IP Connection to Microsoft PowerBI Embedded that just shows up all of a sudden across your systems.

These PowerBI Calls just stop working with a Hard TCP/IP Close error like a firewall would block a connection. Usually the auth steps work - it is when you hit the service for specific workspace and report id's that it fails.

This is the 2020 note from Microsoft PowerBI about TLS 1.2 required

PowerBIClient

methods that show this problem

GetReportsInGroupAsync GetReportsInGroupAsAdminAsync GetReportsAsync GetReportsAsAdminAsync Microsoft.PowerBI.Api HttpClientHandler Force TLS 1.1 TLS 1.2

Search Error Terms to help people find this: System.Net.Http.HttpRequestException: An error occurred while sending the request System.Net.WebException: The underlying connection was closed: An unexpected error occurred on a send. System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host.

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

Simple division in Java - is this a bug or a feature?

You're using integer division.

Try 7.0/10 instead.

Place cursor at the end of text in EditText

If your EditText is not clear:

editText.setText("");
editText.append("New text");

or

editText.setText(null);
editText.append("New text");

C - The %x format specifier

Break-down:

  • 8 says that you want to show 8 digits
  • 0 that you want to prefix with 0's instead of just blank spaces
  • x that you want to print in lower-case hexadecimal.

Quick example (thanks to Grijesh Chauhan):

#include <stdio.h>
int main() {
    int data = 29;
    printf("%x\n", data);    // just print data
    printf("%0x\n", data);   // just print data ('0' on its own has no effect)
    printf("%8x\n", data);   // print in 8 width and pad with blank spaces
    printf("%08x\n", data);  // print in 8 width and pad with 0's

    return 0;
}

Output:

1d
1d
      1d
0000001d

Also see http://www.cplusplus.com/reference/cstdio/printf/ for reference.

Getting the last n elements of a vector. Is there a better way than using the length() function?

I just add here something related. I was wanted to access a vector with backend indices, ie writting something like tail(x, i) but to return x[length(x) - i + 1] and not the whole tail.

Following commentaries I benchmarked two solutions:

accessRevTail <- function(x, n) {
    tail(x,n)[1]
}

accessRevLen <- function(x, n) {
  x[length(x) - n + 1]
}

microbenchmark::microbenchmark(accessRevLen(1:100, 87), accessRevTail(1:100, 87))
Unit: microseconds
                     expr    min      lq     mean median      uq     max neval
  accessRevLen(1:100, 87)  1.860  2.3775  2.84976  2.803  3.2740   6.755   100
 accessRevTail(1:100, 87) 22.214 23.5295 28.54027 25.112 28.4705 110.833   100

So it appears in this case that even for small vectors, tail is very slow comparing to direct access

Could not find main class HelloWorld

I have also faced same problem....

Actually this problem is raised due to the fact that your program .class files are not saved in that directory. Remove your CLASSPATH from your environment variable (you do no need to set classpath for simple Java programs) and reopen cmd prompt, then compile and execute.

If you observe carefully your .class file will save in the same location. (I am not an expert, I am also basic programer if there is any mistake in my sentences please ignore it :-))

Angular.js ng-repeat filter by property having one of multiple values (OR of values)

For me, it worked as given below:

<div ng-repeat="product in products | filter: { color: 'red'||'blue' }">

<div ng-repeat="product in products | filter: { color: 'red'} | filter: { color:'blue' }">

Excel VBA date formats

Use value(cellref) on the side to evaluate the cells. Strings will produce the "#Value" error, but dates resolve to a number (e.g. 43173).

How to quit a java app from within the program

Runtime.getCurrentRumtime().halt(0);

How to refer environment variable in POM.xml?

Check out the Maven Properties Guide...

As Seshagiri pointed out in the comments, ${env.VARIABLE_NAME} will do what you want.

I will add a word of warning and say that a pom.xml should completely describe your project so please use environment variables judiciously. If you make your builds dependent on your environment, they are harder to reproduce

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

*args and **kwargs: allow you to pass a variable number of arguments to a function.

*args: is used to send a non-keyworded variable length argument list to the function:

def args(normal_arg, *argv):
    print("normal argument:", normal_arg)

    for arg in argv:
        print("Argument in list of arguments from *argv:", arg)

args('animals', 'fish', 'duck', 'bird')

Will produce:

normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird

**kwargs*

**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.

def who(**kwargs):
    if kwargs is not None:
        for key, value in kwargs.items():
            print("Your %s is %s." % (key, value))

who(name="Nikola", last_name="Tesla", birthday="7.10.1856", birthplace="Croatia")  

Will produce:

Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.

Spring @Transactional read-only propagation

Calling readOnly=false from readOnly=true doesn't work since the previous transaction continues.

In your example, the handle() method on your service layer is starting a new read-write transaction. If the handle method in turn calls service methods that annotated read-only, the read-only will take no effect as they will participate in the existing read-write transaction instead.

If it is essential for those methods to be read-only, then you can annotate them with Propagation.REQUIRES_NEW, and they will then start a new read-only transaction rather than participate in the existing read-write transaction.

Here is a worked example, CircuitStateRepository is a spring-data JPA repository.

BeanS calls a transactional=read-only Bean1, which does a lookup and calls transactional=read-write Bean2 which saves a new object.

  • Bean1 starts a read-only tx.

31 09:39:44.199 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''

  • Bean 2 pariticipates in it.

    31 09:39:44.230 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Participating in existing transaction

    Nothing is committed to the database.

Now change Bean2 @Transactional annotation to add propagation=Propagation.REQUIRES_NEW

  • Bean1 starts a read-only tx.

    31 09:31:36.418 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Creating new transaction with name [nz.co.vodafone.wcim.business.Bean1.startSomething]: PROPAGATION_REQUIRED,ISOLATION_DEFAULT,readOnly; ''

  • Bean2 starts a new read-write tx

    31 09:31:36.449 [pool-1-thread-1] DEBUG o.s.orm.jpa.JpaTransactionManager - Suspending current transaction, creating new transaction with name [nz.co.vodafone.wcim.business.Bean2.createSomething]

And the changes made by Bean2 are now committed to the database.

Here's the example, tested with spring-data, hibernate and oracle.

@Named
public class BeanS {    
    @Inject
    Bean1 bean1;

    @Scheduled(fixedRate = 20000)
    public void runSomething() {
        bean1.startSomething();
    }
}

@Named
@Transactional(readOnly = true)
public class Bean1 {    
    Logger log = LoggerFactory.getLogger(Bean1.class);

    @Inject
    private CircuitStateRepository csr;

    @Inject
    private Bean2 bean2;

    public void startSomething() {    
        Iterable<CircuitState> s = csr.findAll();
        CircuitState c = s.iterator().next();
        log.info("GOT CIRCUIT {}", c.getCircuitId());
        bean2.createSomething(c.getCircuitId());    
    }
}

@Named
@Transactional(readOnly = false)
public class Bean2 {    
    @Inject
    CircuitStateRepository csr;

    public void createSomething(String circuitId) {
        CircuitState c = new CircuitState(circuitId + "-New-" + new DateTime().toString("hhmmss"), new DateTime());

        csr.save(c);
     }
}

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

If java 8 or above is used then the problem is the libraries we use are incompatible with java 8. So to solve this add these two lines to build.gradle of your app and all sub modules if any. (Android studio clearly show how to do this in error message)

targetCompatibility = '1.7' sourceCompatibility = '1.7'

Array versus List<T>: When to use which?

If I know exactly how many elements I'm going to need, say I need 5 elements and only ever 5 elements then I use an array. Otherwise I just use a List<T>.

jQuery find events handlers registered with an object

I've combined both solutions from @jps to one function:

jQuery.fn.getEvents = function() {
    if (typeof(jQuery._data) === 'function') {
        return jQuery._data(this.get(0), 'events') || {};
    }

    // jQuery version < 1.7.?
    if (typeof(this.data) === 'function') {
        return this.data('events') || {};
    }

    return {};
};

But beware, this function can only return events that were set using jQuery itself.

ASP MVC href to a controller/view

Try the following:

<a asp-controller="Users" asp-action="Index"></a>

(Valid for ASP.NET 5 and MVC 6)

json call with C#

Here's a variation of Shiv Kumar's answer, using Newtonsoft.Json (aka Json.NET):

public static bool SendAnSMSMessage(string message)
{
    var httpWebRequest = (HttpWebRequest)WebRequest.Create("http://api.pennysms.com/jsonrpc");
    httpWebRequest.ContentType = "text/json";
    httpWebRequest.Method = "POST";

    var serializer = new Newtonsoft.Json.JsonSerializer();
    using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
    {
        using (var tw = new Newtonsoft.Json.JsonTextWriter(streamWriter))
        {
             serializer.Serialize(tw, 
                 new {method= "send",
                      @params = new string[]{
                          "IPutAGuidHere", 
                          "[email protected]",
                          "MyTenDigitNumberWasHere",
                          message
                      }});
        }
    }
    var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
    using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
    {
        var responseText = streamReader.ReadToEnd();
        //Now you have your response.
        //or false depending on information in the response
        return true;        
    }
}

Android: Expand/collapse animation

I was trying to do what I believe was a very similar animation and found an elegant solution. This code assumes that you are always going from 0->h or h->0 (h being the maximum height). The three constructor parameters are view = the view to be animated (in my case, a webview), targetHeight = the maximum height of the view, and down = a boolean which specifies the direction (true = expanding, false = collapsing).

public class DropDownAnim extends Animation {
    private final int targetHeight;
    private final View view;
    private final boolean down;

    public DropDownAnim(View view, int targetHeight, boolean down) {
        this.view = view;
        this.targetHeight = targetHeight;
        this.down = down;
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        int newHeight;
        if (down) {
            newHeight = (int) (targetHeight * interpolatedTime);
        } else {
            newHeight = (int) (targetHeight * (1 - interpolatedTime));
        }
        view.getLayoutParams().height = newHeight;
        view.requestLayout();
    }

    @Override
    public void initialize(int width, int height, int parentWidth,
            int parentHeight) {
        super.initialize(width, height, parentWidth, parentHeight);
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

Get the latest date from grouped MySQL data

Are you looking for the max date for each model?

SELECT model, max(date) FROM doc
GROUP BY model

If you're looking for all models matching the max date of the entire table...

SELECT model, date FROM doc
WHERE date IN (SELECT max(date) FROM doc)

[--- Added ---]

For those who want to display details from every record matching the latest date within each model group (not summary data, as asked for in the OP):

SELECT d.model, d.date, d.color, d.etc FROM doc d
WHERE d.date IN (SELECT max(d2.date) FROM doc d2 WHERE d2.model=d.model)

MySQL 8.0 and newer supports the OVER clause, producing the same results a bit faster for larger data sets.

SELECT model, date, color, etc FROM (SELECT model, date, color, etc, 
  max(date) OVER (PARTITION BY model) max_date FROM doc) predoc 
WHERE date=max_date;

How can I generate a 6 digit unique number?

If you want it to start at 000001 and go to 999999:

$num_str = sprintf("%06d", mt_rand(1, 999999));

Mind you, it's stored as a string.

make div's height expand with its content

If you are using jQuery UI, they already have a class the works just a charm add a <div> at the bottom inside the div that you want expand with height:auto; then add a class name ui-helper-clearfix or use this style attribute and add just like below:

<div style=" clear:both; overflow:hidden; height:1%; "></div>

add jQuery UI class to the clear div, not the div the you want to expand.

Failed to allocate memory: 8

Looks like there are a thousand different fixes for this...none of the above worked for me, but what worked was to launch the AVD from the command line emulator-arm.exe @AVD-NAME

Somehow if launched with only emulator.exe, I would get the same error message than when trying to launch via Eclipse.

Initialization of all elements of an array to one default value in C++?

Using the syntax that you used,

int array[100] = {-1};

says "set the first element to -1 and the rest to 0" since all omitted elements are set to 0.

In C++, to set them all to -1, you can use something like std::fill_n (from <algorithm>):

std::fill_n(array, 100, -1);

In portable C, you have to roll your own loop. There are compiler-extensions or you can depend on implementation-defined behavior as a shortcut if that's acceptable.

How to add Headers on RESTful call using Jersey Client API

I use the header(name, value) method and give the return to webResource var:

Client client = Client.create();
WebResource webResource = client.resource("uri");

MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add("json", js); //set parametes for request

appKey = "Bearer " + appKey; // appKey is unique number

//Get response from RESTful Server get(ClientResponse.class);
ClientResponse response = webResource.queryParams(queryParams)
    .header("Content-Type", "application/json;charset=UTF-8")
    .header("Authorization", appKey)
    .get(ClientResponse.class);

String jsonStr = response.getEntity(String.class);

How to create an object property from a variable value in JavaScript?

As $scope is an object, you can try with JavaScript by:

$scope['something'] = 'hey'

It is equal to:

$scope.something = 'hey'

I created a fiddle to test.

How to concat two ArrayLists?

If you want to do it one line and you do not want to change list1 or list2 you can do it using stream

List<String> list1 = Arrays.asList("London", "Paris");
List<String> list2 = Arrays.asList("Moscow", "Tver");

List<String> list = Stream.concat(list1.stream(),list2.stream()).collect(Collectors.toList());

Data binding for TextBox

You need a bindingsource object to act as an intermediary and assist in the binding. Then instead of updating the user interface, update the underlining model.

var model = (Fruit) bindingSource1.DataSource;

model.FruitType = "oranges";

bindingSource.ResetBindings();

Read up on BindingSource and simple data binding for Windows Forms.

Django Server Error: port is already in use

Type 'fg' as command after that ctl-c.
Command:
Fg will show which is running on background. After that ctl-c will stop it.

fg
ctl-c

How to do HTTP authentication in android?

For my Android projects I've used the Base64 library from here:

http://iharder.net/base64

It's a very extensive library and so far I've had no problems with it.

How to set default values in Go structs

One problem with option 1 in answer from Victor Zamanian is that if the type isn't exported then users of your package can't declare it as the type for function parameters etc. One way around this would be to export an interface instead of the struct e.g.

package candidate
// Exporting interface instead of struct
type Candidate interface {}
// Struct is not exported
type candidate struct {
    Name string
    Votes uint32 // Defaults to 0
}
// We are forced to call the constructor to get an instance of candidate
func New(name string) Candidate {
    return candidate{name, 0}  // enforce the default value here
}

Which lets us declare function parameter types using the exported Candidate interface. The only disadvantage I can see from this solution is that all our methods need to be declared in the interface definition, but you could argue that that is good practice anyway.

Check if url contains string with JQuery

use href with indexof

<script type="text/javascript">
 $(document).ready(function () {
   if(window.location.href.indexOf("added-to-cart=555") > -1) {
   alert("your url contains the added-to-cart=555");
  }
});
</script>

Can you pass parameters to an AngularJS controller on creation?

Notes:

This answer is old. This is just a proof of concept on how the desired outcome can be achieved. However, it may not be the best solution as per some comments below. I don't have any documentation to support or reject the following approach. Please refer to some of the comments below for further discussion on this topic.

Original Answer:

I answered this to Yes you absolutely can do so using ng-init and a simple init function.

Here is the example of it on plunker

HTML

<!DOCTYPE html>
<html ng-app="angularjs-starter">
  <head lang="en">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.3/angular.min.js"></script>
    <script src="app.js"></script>
  </head>  
  <body ng-controller="MainCtrl" ng-init="init('James Bond','007')">
    <h1>I am  {{name}} {{id}}</h1>
  </body>
</html>

JavaScript

var app = angular.module('angularjs-starter', []);

app.controller('MainCtrl', function($scope) {

  $scope.init = function(name, id)
  {
    //This function is sort of private constructor for controller
    $scope.id = id;
    $scope.name = name; 
    //Based on passed argument you can make a call to resource
    //and initialize more objects
    //$resource.getMeBond(007)
  };


});

What exactly is "exit" in PowerShell?

It's a reserved keyword (like return, filter, function, break).

Reference

Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:

But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.

Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:

PS C:\> function ex{exit}
PS C:\> new-alias ^D ex

Twitter Bootstrap - add top space between rows

There is a trick for adding margin automatically only for the 2nd+ row in the container.

.container-row-margin .row + .row {
    margin-top: 1rem;
}

Adding the .container-row-margin to the container, results in:

enter image description here

Complete HTML:

<div class="bg-secondary text-white">
    div outside of the container.
</div>
<div class="container container-row-margin">
    <div class="row">
        <div class="col col-4 bg-warning">
            Row without top margin
        </div>
    </div>
    <div class="row">
        <div class="col col-4 bg-primary text-white">
            Row with top margin
        </div>
    </div>
    <div class="row">
        <div class="col col-4 bg-primary text-white">
            Row with top margin
        </div>
    </div>
</div>
<div class="bg-secondary text-white">
    div outside of the container.
</div>

Taken from official samples.

How should I validate an e-mail address?

There is a Patterns class in package android.util which is beneficial here. Below is the method I always use for validating email and many other stuffs

private boolean isEmailValid(String email) {
    return !TextUtils.isEmpty(email) && Patterns.EMAIL_ADDRESS.matcher(email).matches();
}

Read all contacts' phone numbers in android

Here's how to use ContentsContract API to fetch your contacts in your Phone Book. You'll need to add these permissions in your AndroidManifest.xml

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

Then, you can run this method to loop through all your contacts.

Here's an example to query fields like Name and Phone Number, you can configure yourself to use CommonDataKinds, it query other fields in your Contact.

https://developer.android.com/reference/android/provider/ContactsContract.CommonDataKinds

private fun readContactsOnDevice() {
    val context = requireContext()
    if (ContextCompat.checkSelfPermission(
            context, Manifest.permission.WRITE_CONTACTS
        ) != PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(
            context, Manifest.permission.READ_CONTACTS
        ) != PackageManager.PERMISSION_GRANTED
    ) {
        requestPermissions(
            arrayOf(Manifest.permission.READ_CONTACTS, Manifest.permission.WRITE_CONTACTS), 1
        )
        return
    }

    val contentResolver = context.contentResolver
    val contacts = contentResolver.query(
        ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
        null, null, null, null
    )

    while (contacts?.moveToNext() == true) {
        val name = contacts.getString(
            contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)
        )
        val phoneNumber = contacts.getString(
            contacts.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)
        )
        Timber.i("Name: $name, Phone Number: $phoneNumber")
    }
}

Free tool to Create/Edit PNG Images?

Paint.NET will create and edit PNGs with gusto. It's an excellent program in many respects. It's free as in beer and speech.

Extract only right most n letters from a string

Use this:

string mystr = "PER 343573"; int number = Convert.ToInt32(mystr.Replace("PER ",""));

CSS3 transition events

Just for fun, don't do this!

$.fn.transitiondone = function () {
  return this.each(function () {
    var $this = $(this);
    setTimeout(function () {
      $this.trigger('transitiondone');
    }, (parseFloat($this.css('transitionDelay')) + parseFloat($this.css('transitionDuration'))) * 1000);
  });
};


$('div').on('mousedown', function (e) {
  $(this).addClass('bounce').transitiondone();
});

$('div').on('transitiondone', function () {
  $(this).removeClass('bounce');
});

logout and redirecting session in php

<?php
session_start();
session_destroy();
header("Location: home.php");
?>

Waiting until two async blocks are executed before starting another block

With Swift 5.1, Grand Central Dispatch offers many ways to solve your problem. According to your needs, you may choose one of the seven patterns shown in the following Playground snippets.


#1. Using DispatchGroup, DispatchGroup's notify(qos:flags:queue:execute:) and DispatchQueue's async(group:qos:flags:execute:)

The Apple Developer Concurrency Programming Guide states about DispatchGroup:

Dispatch groups are a way to block a thread until one or more tasks finish executing. You can use this behavior in places where you cannot make progress until all of the specified tasks are complete. For example, after dispatching several tasks to compute some data, you might use a group to wait on those tasks and then process the results when they are done.

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)
let group = DispatchGroup()

queue.async(group: group) {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

queue.async(group: group) {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

group.notify(queue: queue) {
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

#2. Using DispatchGroup, DispatchGroup's wait(), DispatchGroup's enter() and DispatchGroup's leave()

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)
let group = DispatchGroup()

group.enter()
queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
    group.leave()
}

group.enter()
queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
    group.leave()
}

queue.async {
    group.wait()
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

Note that you can also mix DispatchGroup wait() with DispatchQueue async(group:qos:flags:execute:) or mix DispatchGroup enter() and DispatchGroup leave() with DispatchGroup notify(qos:flags:queue:execute:).


#3. Using Dispatch?Work?Item?Flags barrier and DispatchQueue's async(group:qos:flags:execute:)

Grand Central Dispatch Tutorial for Swift 4: Part 1/2 article from Raywenderlich.com gives a definition for barriers:

Dispatch barriers are a group of functions acting as a serial-style bottleneck when working with concurrent queues. When you submit a DispatchWorkItem to a dispatch queue you can set flags to indicate that it should be the only item executed on the specified queue for that particular time. This means that all items submitted to the queue prior to the dispatch barrier must complete before the DispatchWorkItem will execute.

Usage:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)

queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

queue.async(flags: .barrier) {
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

#4. Using DispatchWorkItem, Dispatch?Work?Item?Flags's barrier and DispatchQueue's async(execute:)

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)

queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

let dispatchWorkItem = DispatchWorkItem(qos: .default, flags: .barrier) {
    print("#3 finished")
}

queue.async(execute: dispatchWorkItem)

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

#5. Using DispatchSemaphore, DispatchSemaphore's wait() and DispatchSemaphore's signal()

Soroush Khanlou wrote the following lines in The GCD Handbook blog post:

Using a semaphore, we can block a thread for an arbitrary amount of time, until a signal from another thread is sent. Semaphores, like the rest of GCD, are thread-safe, and they can be triggered from anywhere. Semaphores can be used when there’s an asynchronous API that you need to make synchronous, but you can’t modify it.

Apple Developer API Reference also gives the following discussion for DispatchSemaphore init(value:?) initializer:

Passing zero for the value is useful for when two threads need to reconcile the completion of a particular event. Passing a value greater than zero is useful for managing a finite pool of resources, where the pool size is equal to the value.

Usage:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let queue = DispatchQueue(label: "com.company.app.queue", attributes: .concurrent)
let semaphore = DispatchSemaphore(value: 0)

queue.async {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
    semaphore.signal()
}

queue.async {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
    semaphore.signal()
}

queue.async {
    semaphore.wait()
    semaphore.wait()    
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 */

#6. Using OperationQueue and Operation's addDependency(_:)

The Apple Developer API Reference states about Operation?Queue:

Operation queues use the libdispatch library (also known as Grand Central Dispatch) to initiate the execution of their operations.

Usage:

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let operationQueue = OperationQueue()

let blockOne = BlockOperation {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

let blockTwo = BlockOperation {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

let blockThree = BlockOperation {
    print("#3 finished")
}

blockThree.addDependency(blockOne)
blockThree.addDependency(blockTwo)

operationQueue.addOperations([blockThree, blockTwo, blockOne], waitUntilFinished: false)

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 or
 #2 started
 #1 started
 #2 finished
 #1 finished
 #3 finished
 */

#7. Using OperationQueue and OperationQueue's addBarrierBlock(_:) (requires iOS 13)

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let operationQueue = OperationQueue()

let blockOne = BlockOperation {
    print("#1 started")
    Thread.sleep(forTimeInterval: 5)
    print("#1 finished")
}

let blockTwo = BlockOperation {
    print("#2 started")
    Thread.sleep(forTimeInterval: 2)
    print("#2 finished")
}

operationQueue.addOperations([blockTwo, blockOne], waitUntilFinished: false)
operationQueue.addBarrierBlock {
    print("#3 finished")
}

/*
 prints:
 #1 started
 #2 started
 #2 finished
 #1 finished
 #3 finished
 or
 #2 started
 #1 started
 #2 finished
 #1 finished
 #3 finished
 */

Using 24 hour time in bootstrap timepicker

//Timepicker
$(".timepicker").timepicker({
  showInputs: false,
  showMeridian: false //24hr mode 
});

What's the difference between .so, .la and .a library files?

.so files are dynamic libraries. The suffix stands for "shared object", because all the applications that are linked with the library use the same file, rather than making a copy in the resulting executable.

.a files are static libraries. The suffix stands for "archive", because they're actually just an archive (made with the ar command -- a predecessor of tar that's now just used for making libraries) of the original .o object files.

.la files are text files used by the GNU "libtools" package to describe the files that make up the corresponding library. You can find more information about them in this question: What are libtool's .la file for?

Static and dynamic libraries each have pros and cons.

Static pro: The user always uses the version of the library that you've tested with your application, so there shouldn't be any surprising compatibility problems.

Static con: If a problem is fixed in a library, you need to redistribute your application to take advantage of it. However, unless it's a library that users are likely to update on their own, you'd might need to do this anyway.

Dynamic pro: Your process's memory footprint is smaller, because the memory used for the library is amortized among all the processes using the library.

Dynamic pro: Libraries can be loaded on demand at run time; this is good for plugins, so you don't have to choose the plugins to be used when compiling and installing the software. New plugins can be added on the fly.

Dynamic con: The library might not exist on the system where someone is trying to install the application, or they might have a version that's not compatible with the application. To mitigate this, the application package might need to include a copy of the library, so it can install it if necessary. This is also often mitigated by package managers, which can download and install any necessary dependencies.

Dynamic con: Link-Time Optimization is generally not possible, so there could possibly be efficiency implications in high-performance applications. See the Wikipedia discussion of WPO and LTO.

Dynamic libraries are especially useful for system libraries, like libc. These libraries often need to include code that's dependent on the specific OS and version, because kernel interfaces have changed. If you link a program with a static system library, it will only run on the version of the OS that this library version was written for. But if you use a dynamic library, it will automatically pick up the library that's installed on the system you run on.

Find stored procedure by name

You can use this query:

SELECT 
    ROUTINE_CATALOG AS DatabaseName ,
    ROUTINE_SCHEMA AS SchemaName,
    SPECIFIC_NAME AS SPName ,
    ROUTINE_DEFINITION AS SPBody ,
    CREATED AS CreatedDate,
    LAST_ALTERED AS LastModificationDate
FROM INFORMATION_SCHEMA.ROUTINES
WHERE 
    (ROUTINE_DEFINITION LIKE '%%')
    AND 
    (ROUTINE_TYPE='PROCEDURE')
    AND
    (SPECIFIC_NAME LIKE '%AssessmentToolDegreeDel')

As you can see, you can do search inside the body of Stored Procedure also.

Where can I find Android's default icons?

\path-to-your-android-sdk-folder\platforms\android-xx\data\res

IOError: [Errno 32] Broken pipe: Python

I feel obliged to point out that the method using

signal(SIGPIPE, SIG_DFL) 

is indeed dangerous (as already suggested by David Bennet in the comments) and in my case led to platform-dependent funny business when combined with multiprocessing.Manager (because the standard library relies on BrokenPipeError being raised in several places). To make a long and painful story short, this is how I fixed it:

First, you need to catch the IOError (Python 2) or BrokenPipeError (Python 3). Depending on your program you can try to exit early at that point or just ignore the exception:

from errno import EPIPE

try:
    broken_pipe_exception = BrokenPipeError
except NameError:  # Python 2
    broken_pipe_exception = IOError

try:
    YOUR CODE GOES HERE
except broken_pipe_exception as exc:
    if broken_pipe_exception == IOError:
        if exc.errno != EPIPE:
            raise

However, this isn't enough. Python 3 may still print a message like this:

Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

Unfortunately getting rid of that message is not straightforward, but I finally found http://bugs.python.org/issue11380 where Robert Collins suggests this workaround that I turned into a decorator you can wrap your main function with (yes, that's some crazy indentation):

from functools import wraps
from sys import exit, stderr, stdout
from traceback import print_exc


def suppress_broken_pipe_msg(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except SystemExit:
            raise
        except:
            print_exc()
            exit(1)
        finally:
            try:
                stdout.flush()
            finally:
                try:
                    stdout.close()
                finally:
                    try:
                        stderr.flush()
                    finally:
                        stderr.close()
    return wrapper


@suppress_broken_pipe_msg
def main():
    YOUR CODE GOES HERE

How to add dll in c# project

The DLL must be present at all times - as the name indicates, a reference only tells VS that you're trying to use stuff from the DLL. In the project file, VS stores the actual path and file name of the referenced DLL. If you move or delete it, VS is not able to find it anymore.

I usually create a libs folder within my project's folder where I copy DLLs that are not installed to the GAC. Then, I actually add this folder to my project in VS (show hidden files in VS, then right-click and "Include in project"). I then reference the DLLs from the folder, so when checking into source control, the library is also checked in. This makes it much easier when more than one developer will have to change the project.

(Please make sure to set the build type to "none" and "don't copy to output folder" for the DLL in your project.)

PS: I use a German Visual Studio, so the captions I quoted may not exactly match the English version...

How to print to console using swift playground?

for displaying variables only in playground, just mention the variable name without anything

let stat = 100

stat // this outputs the value of stat on playground right window

Enter key press in C#

private void Input_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.Key == Key.Return)
        {
            MessageBox.Show("Enter pressed");
        }
    }

This worked for me.

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

If you are using 11G XE with Windows, along with tns listener restart, make sure Windows Event Log service is started.

Processing $http response in service

I had the same problem, but when I was surfing on the internet I understood that $http return back by default a promise, then I could use it with "then" after return the "data". look at the code:

 app.service('myService', function($http) {
       this.getData = function(){
         var myResponseData = $http.get('test.json').then(function (response) {
            console.log(response);.
            return response.data;
          });
         return myResponseData;

       }
});    
 app.controller('MainCtrl', function( myService, $scope) {
      // Call the getData and set the response "data" in your scope.  
      myService.getData.then(function(myReponseData) {
        $scope.data = myReponseData;
      });
 });

Node.js client for a socket.io server

Client side code: I had a requirement where my nodejs webserver should work as both server as well as client, so i added below code when i need it as client, It should work fine, i am using it and working fine for me!!!

const socket = require('socket.io-client')('http://192.168.0.8:5000', {
            reconnection: true,
            reconnectionDelay: 10000
          });
    
        socket.on('connect', (data) => {
            console.log('Connected to Socket');
        });
        
        socket.on('event_name', (data) => {
            console.log("-----------------received event data from the socket io server");
        });
    
        //either 'io server disconnect' or 'io client disconnect'
        socket.on('disconnect', (reason) => {
            console.log("client disconnected");
            if (reason === 'io server disconnect') {
              // the disconnection was initiated by the server, you need to reconnect manually
              console.log("server disconnected the client, trying to reconnect");
              socket.connect();
            }else{
                console.log("trying to reconnect again with server");
            }
            // else the socket will automatically try to reconnect
          });
    
        socket.on('error', (error) => {
            console.log(error);
        });

laravel-5 passing variable to JavaScript

$langs = Language::all()->toArray();
return View::make('NAATIMockTest.Admin.Language.index', [
    'langs' => $langs
]);

then in view

<script type="text/javascript">
    var langs = {{json_encode($langs)}};
    console.log(langs);
</script>

Its not pretty tho

reading text file with utf-8 encoding using java

Use

    import java.io.BufferedReader;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.io.UnsupportedEncodingException;     
    public class test {
    public static void main(String[] args){

    try {
        File fileDir = new File("PATH_TO_FILE");

        BufferedReader in = new BufferedReader(
           new InputStreamReader(new FileInputStream(fileDir), "UTF-8"));

        String str;

        while ((str = in.readLine()) != null) {
            System.out.println(str);
        }

                in.close();
        } 
        catch (UnsupportedEncodingException e) 
        {
            System.out.println(e.getMessage());
        } 
        catch (IOException e) 
        {
            System.out.println(e.getMessage());
        }
        catch (Exception e)
        {
            System.out.println(e.getMessage());
        }
    }
}

You need to put UTF-8 in quotes

Possible cases for Javascript error: "Expected identifier, string or number"

As noted previously, having an extra comma threw an error.

Also in IE 7.0, not having a semicolon at the end of a line caused an error. It works fine in Safari and Chrome (with no errors in console).

What is the easiest way to ignore a JPA field during persistence?

None of the above answers worked for me using Hibernate 5.2.10, Jersey 2.25.1 and Jackson 2.8.9. I finally found the answer (sort of, they reference hibernate4module but it works for 5 too) here. None of the Json annotations worked at all with @Transient. Apparently Jackson2 is 'smart' enough to kindly ignore stuff marked with @Transient unless you explicitly tell it not to. The key was to add the hibernate5 module (which I was using to deal with other Hibernate annotations) and disable the USE_TRANSIENT_ANNOTATION feature in my Jersey Application:

ObjectMapper jacksonObjectMapper = new ObjectMapper();
Hibernate5Module jacksonHibernateModule = new Hibernate5Module();
jacksonHibernateModule.disable(Hibernate5Module.Feature.USE_TRANSIENT_ANNOTATION);
jacksonObjectMapper.registerModule(jacksonHibernateModule);  

Here is the dependency for the Hibernate5Module:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-hibernate5</artifactId>
    <version>2.8.9</version>
</dependency>

What is the scope of variables in JavaScript?

Variables declared globally have a global scope. Variables declared within a function are scoped to that function, and shadow global variables of the same name.

(I'm sure there are many subtleties that real JavaScript programmers will be able to point out in other answers. In particular I came across this page about what exactly this means at any time. Hopefully this more introductory link is enough to get you started though.)

ASP.NET Core Web API Authentication

ASP.NET Core 2.0 with Angular

https://fullstackmark.com/post/13/jwt-authentication-with-aspnet-core-2-web-api-angular-5-net-core-identity-and-facebook-login

Make sure to use type of authentication filter

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

What is the Swift equivalent of respondsToSelector?

If the method you are testing for is defined as an optional method in a @objc protocol (which sounds like your case), then use the optional chaining pattern as:

if let result = object.method?(args) {
  /* method exists, result assigned, use result */
}
else { ... }

When the method is declare as returning Void, simply use:

if object.method?(args) { ... }

See:

“Calling Methods Through Optional Chaining”
Excerpt From: Apple Inc. “The Swift Programming Language.”
iBooks. https://itun.es/us/jEUH0.l

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

.nextInt() gets the next int, but doesn't read the new line character. This means that when you ask it to read the "next line", you read til the end of the new line character from the first time.

You can insert another .nextLine() after you get the int to fix this. Or (I prefer this way), read the int in as a string, and parse it to an int.

CSS3 Transition not working

For me, it was having display: none;

#spinner-success-text {
    display: none;
    transition: all 1s ease-in;
}

#spinner-success-text.show {
    display: block;
}

Removing it, and using opacity instead, fixed the issue.

#spinner-success-text {
    opacity: 0;
    transition: all 1s ease-in;
}

#spinner-success-text.show {
    opacity: 1;
}

Parse an URL in JavaScript

This should fix a few edge-cases in kobe's answer:

function getQueryParam(url, key) {
  var queryStartPos = url.indexOf('?');
  if (queryStartPos === -1) {
    return;
  }
  var params = url.substring(queryStartPos + 1).split('&');
  for (var i = 0; i < params.length; i++) {
    var pairs = params[i].split('=');
    if (decodeURIComponent(pairs.shift()) == key) {
      return decodeURIComponent(pairs.join('='));
    }
  }
}

getQueryParam('http://example.com/form_image_edit.php?img_id=33', 'img_id');
// outputs "33"

Convert the first element of an array to a string in PHP

Is there any other way to convert that array into string ?

You don't want to convert the array to a string, you want to get the value of the array's sole element, if I read it correctly.

<?php
  $foo = array( 18 => 'Something' );
  $value = array_shift( $foo );
  echo $value; // 'Something'.

?>

Using array_shift you don't have to worry about the index.

EDIT: Mind you, array_shift is not the only function that will return a single value. array_pop( ), current( ), end( ), reset( ), they will all return that one single element. All of the posted solutions work. Using array shift though, you can be sure that you'll only ever get the first value of the array, even when there are multiple.

MySQL: #1075 - Incorrect table definition; autoincrement vs another key?

Identified this solution while reading this thread. Figured id post this for the next guy possibly.

When dealing with Laravel migration file from a package, I Ran into this issue.

My old value was

$table->increments('id');

My new

$table->integer('id')->autoIncrement();

Can't stop rails server

Step 1: find what are the items are consuming 3000 port.

lsof -i:3000

step 2 : Find the process named

For Mac

ruby      TCP localhost:hbci (LISTEN)

For Ubuntu

ruby      TCP *:3000 (LISTEN)

Step 3: Find the PID of the process and kill it.

kill -9 PID

req.query and req.param in ExpressJS

I would suggest using following

req.param('<param_name>')

req.param("") works as following

Lookup is performed in the following order:

req.params
req.body
req.query

Direct access to req.body, req.params, and req.query should be favoured for clarity - unless you truly accept input from each object.

Ref:http://expressjs.com/4x/api.html#req.param

Find the files existing in one directory but not in the other

This answer optimizes one of the suggestions from @Adail-Junior by adding the -D option, which is helpful when neither of the directories being compared are git repositories:

git diff -D --no-index dir1/ dir2/

If you use -D then you won't see comparisons to /dev/null: text Binary files a/whatever and /dev/null differ

Set default syntax to different filetype in Sublime Text 2

In ST2 there's a package you can install called Default FileType which does just that.

More info here.

How does origin/HEAD get set?

It is your setting as the owner of your local repo. Change it like this:

git remote set-head origin some_branch

And origin/HEAD will point to your branch instead of master. This would then apply to your repo only and not for others. By default, it will point to master, unless something else has been configured on the remote repo.

Manual entry for remote set-head provides some good information on this.

Edit: to emphasize: without you telling it to, the only way it would "move" would be a case like renaming the master branch, which I don't think is considered "organic". So, I would say organically it does not move.

What does LINQ return when the results are empty

It won't throw exception, you'll get an empty list.

Convert JavaScript string in dot notation into an object reference

If you want to do this in the fastest possible way, while at the same time handling any issues with the path parsing or property resolution, check out path-value.

const {resolveValue} = require('path-value');

const value = resolveValue(obj, 'a.b.c');

The library is 100% TypeScript, works in NodeJS + all web browsers. And it is fully extendible, you can use lower-level resolvePath, and handle errors your own way, if you want.

const {resolvePath} = require('path-value');

const res = resolvePath(obj, 'a.b.c'); //=> low-level parsing result descriptor

How to trigger Jenkins builds remotely and to pass parameters

In your Jenkins job configuration, tick the box named "This build is parameterized", click the "Add Parameter" button and select the "String Parameter" drop down value.

Now define your parameter - example:

Enter image description here

Now you can use your parameter in your job / build pipeline, example:

Enter image description here

Next to trigger the build with own/custom parameter, invoke the following URL (using either POST or GET):

http://JENKINS_SERVER_ADDRESS/job/YOUR_JOB_NAME/buildWithParameters?myparam=myparam_value

How to set the size of button in HTML

button { 
  width:1000px; 
} 

or even

 button { 
    width:1000px !important
 } 

If thats what you mean

What's the -practical- difference between a Bare and non-Bare repository?

A default/non-bare Git repo contains two pieces of state:

  1. A snapshot of all of the files in the repository (this is what "working tree" means in Git jargon)
  2. A history of all changes made to all the files that have ever been in the repository (there doesn't seem to be a concise piece of Git jargon that encompasses all of this)

The snapshot is what you probably think of as your project: your code files, build files, helper scripts, and anything else you version with Git.

The history is the state that allows you to check out a different commit and get a complete snapshot of what the files in your repository looked like when that commit was added. It consists of a bunch of data structures that are internal to Git that you've probably never interacted with directly. Importantly, the history doesn't just store metadata (e.g. "User U added this many lines to File F at Time T as part of Commit C"), it also stores data (e.g. "User U added these exact lines to File F").

The key idea of a bare repository is that you don't actually need to have the snapshot. Git keeps the snapshot around because it's convenient for humans and other non-Git processes that want to interact with your code, but the snapshot is just duplicating state that's already in the history.

A bare repository is a Git repository that does not have a snapshot. It just stores the history.

Why would you want this? Well, if you're only going to interact with your files using Git (that is, you're not going to edit your files directly or use them to build an executable), you can save space by not keeping around the snapshot. In particular, if you're maintaining a centralized version of your repo on a server somewhere (i.e. you're basically hosting your own GitHub), that server should probably have a bare repo (you would still use a non-bare repo on your local machine though, since you'll presumably want to edit your snapshot).

If you want a more in-depth explanation of bare repos and another example use case, I wrote up a blog post here: https://stegosaurusdormant.com/bare-git-repo/

Git diff --name-only and copy that list

Try the following command, which I have tested:

$ cp -pv --parents $(git diff --name-only) DESTINATION-DIRECTORY

ViewPager PagerAdapter not updating the View

ViewPager was not designed to support dynamic view change.

I had confirmation of this while looking for another bug related to this one https://issuetracker.google.com/issues/36956111 and in particular https://issuetracker.google.com/issues/36956111#comment56

This question is a bit old, but Google recently solved this problem with ViewPager2 . It will allow to replace handmade (unmaintained and potentially buggy) solutions by a standard one. It also prevents recreating views needlessly as some answers do.

For ViewPager2 examples, you can check https://github.com/googlesamples/android-viewpager2

If you want to use ViewPager2, you will need to add the following dependency in your build.gradle file :

  dependencies {
     implementation 'androidx.viewpager2:viewpager2:1.0.0-beta02'
  }

Then you can replace your ViewPager in your xml file with :

    <androidx.viewpager2.widget.ViewPager2
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1" />

After that, you will need to replace ViewPager by ViewPager2 in your activity

ViewPager2 needs either a RecyclerView.Adapter, or a FragmentStateAdapter, in your case it can be a RecyclerView.Adapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {

    private Context context;
    private ArrayList<String> arrayList = new ArrayList<>();

    public MyAdapter(Context context, ArrayList<String> arrayList) {
        this.context = context;
        this.arrayList = arrayList;
    }

    @NonNull
    @Override
    public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(context).inflate(R.layout.list_item, parent, false);
        return new MyViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
        holder.tvName.setText(arrayList.get(position));
    }

    @Override
    public int getItemCount() {
        return arrayList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        TextView tvName;

        public MyViewHolder(@NonNull View itemView) {
            super(itemView);
            tvName = itemView.findViewById(R.id.tvName);
        }
    }
} 

In the case you were using a TabLayout, you can use a TabLayoutMediator :

        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager, true, new TabLayoutMediator.OnConfigureTabCallback() {
            @Override
            public void onConfigureTab(@NotNull TabLayout.Tab tab, int position) {
                // configure your tab here
                tab.setText(tabs.get(position).getTitle());
            }
        });

        tabLayoutMediator.attach();

Then you will be able to refresh your views by modifying your adapter's data and calling notifyDataSetChanged method

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

How to create a file name with the current date & time in Python?

Change this line

filename1 = datetime.now().strftime("%Y%m%d-%H%M%S")

To

filename1 = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")

Note the extra datetime. Alternatively, change your import datetime to from datetime import datetime

Force "portrait" orientation mode

I think android:screenOrientation="portrait" can be used for individual activities. So use that attribute in <activity> tag like :

<activity android:name=".<Activity Name>"
    android:label="@string/app_name" 
    android:screenOrientation="portrait">
   ...         
</activity>

How to sort a list of lists by a specific index of the inner list?

Sorting a Multidimensional Array execute here

arr=[[2,1],[1,2],[3,5],[4,5],[3,1],[5,2],[3,8],[1,9],[1,3]]



arr.sort(key=lambda x:x[0])
la=set([i[0] for i in Points])

for i in la:
    tempres=list()
    for j in arr:
        if j[0]==i:
            tempres.append(j[1])

    for j in sorted(tempres,reverse=True):
        print(i,j)

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

What's the difference between an argument and a parameter?

I thought it through and realized my previous answer was wrong. Here's a much better definition

{Imagine a carton of eggs: A pack of sausage links: And a maid } These represent elements of a Function needed for preparation called : (use any name: Lets say Cooking is the name of my function).

A Maid is a method .

( You must __call_ or ask this method to make breakfast)(The act of making breakfast is a Function called Cooking)_

Eggs and sausages are Parameters :

(because the number of eggs and the number of sausages you want to eat is __variable_ .)_

Your decision is an Argument :

It represents the __Value_ of the chosen number of eggs and/or sausages you are Cooking ._

{Mnemonic}

_" When you call the maid and ask her to make breakfast, she __argues_ with you about how many eggs and sausages you should eating. She's concerned about your cholesterol" __

( Arguments , then, are the values for the combination of Parameters you have declared and decided to pass to your Function )

disabling spring security in spring boot app

I think you must also remove security auto config from your @SpringBootApplication annotated class:

@EnableAutoConfiguration(exclude = {
    org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration.class,
    org.springframework.boot.actuate.autoconfigure.ManagementSecurityAutoConfiguration.class})

Get list from pandas DataFrame column headers

If the DataFrame happens to have an Index or MultiIndex and you want those included as column names too:

names = list(filter(None, df.index.names + df.columns.values.tolist()))

It avoids calling reset_index() which has an unnecessary performance hit for such a simple operation.

I've run into needing this more often because I'm shuttling data from databases where the dataframe index maps to a primary/unique key, but is really just another "column" to me. It would probably make sense for pandas to have a built-in method for something like this (totally possible I've missed it).

How to form a correct MySQL connection string?

try creating connection string this way:

MySqlConnectionStringBuilder conn_string = new MySqlConnectionStringBuilder();
conn_string.Server = "mysql7.000webhost.com";
conn_string.UserID = "a455555_test";
conn_string.Password = "a455555_me";
conn_string.Database = "xxxxxxxx";

using (MySqlConnection conn = new MySqlConnection(conn_string.ToString()))
using (MySqlCommand cmd = conn.CreateCommand())
{    //watch out for this SQL injection vulnerability below
     cmd.CommandText = string.Format("INSERT Test (lat, long) VALUES ({0},{1})",
                                    OSGconv.deciLat, OSGconv.deciLon);
     conn.Open();
     cmd.ExecuteNonQuery();
}

How to split CSV files as per number of rows specified?

Use the Linux split command:

split -l 20 file.txt new    

Split the file "file.txt" into files beginning with the name "new" each containing 20 lines of text each.

Type man split at the Unix prompt for more information. However you will have to first remove the header from file.txt (using the tail command, for example) and then add it back on to each of the split files.

Sorting std::map using value

U can consider using boost::bimap that might gave you a feeling that map is sorted by key and by values simultaneously (this is not what really happens, though)

Combating AngularJS executing controller twice

Just adding my case here as well:

I was using angular-ui-router with $state.go('new_state', {foo: "foo@bar"})

Once I added encodeURIComponent to the parameter, the problem was gone: $state.go('new_state', {foo: encodeURIComponent("foo@bar")}).

What happened? The character "@" in the parameter value is not allowed in URLs. As a consequence, angular-ui-router created my controller twice: during first creation it passed the original "foo@bar", during second creation it would pass the encoded version "foo%40bar". Once I explicitly encoded the parameter as shown above, the problem went away.

How to use QueryPerformanceCounter?

Assuming you're on Windows (if so you should tag your question as such!), on this MSDN page you can find the source for a simple, useful HRTimer C++ class that wraps the needed system calls to do something very close to what you require (it would be easy to add a GetTicks() method to it, in particular, to do exactly what you require).

On non-Windows platforms, there's no QueryPerformanceCounter function, so the solution won't be directly portable. However, if you do wrap it in a class such as the above-mentioned HRTimer, it will be easier to change the class's implementation to use what the current platform is indeed able to offer (maybe via Boost or whatever!).

Copy Paste in Bash on Ubuntu on Windows

you might have bash but it is still a windows window manager. Highlite some text in the bash terminal window. Right click on the title bar, select "Edit", select "Copy", Now Right Click again on the Title bar, select "Edit" , Select "Paste", Done. You should be able to Highlite text, hit "Enter" then Control V but this seems to be broken

Java :Add scroll into text area

Try adding these two lines to your code. I hope it will work. It worked for me :)

display.setLineWrap(true);
display.setWrapStyleWord(true);

Picture of output is shown below

enter image description here

Split string with string as delimiter

Try this:

for /F "tokens=1,3 delims=. " %%a in ("%string%") do (
   echo %%a
   echo %%b
)

that is, take the first and third tokens delimited by space or point...

Pandas "Can only compare identically-labeled DataFrame objects" error

At the time when this question was asked there wasn't another function in Pandas to test equality, but it has been added a while ago: pandas.equals

You use it like this:

df1.equals(df2)

Some differenes to == are:

  • You don't get the error described in the question
  • It returns a simple boolean.
  • NaN values in the same location are considered equal
  • 2 DataFrames need to have the same dtype to be considered equal, see this stackoverflow question

How to properly -filter multiple strings in a PowerShell copy script

-Filter only accepts a single string. -Include accepts multiple values, but qualifies the -Path argument. The trick is to append \* to the end of the path, and then use -Include to select multiple extensions. BTW, quoting strings is unnecessary in cmdlet arguments unless they contain spaces or shell special characters.

Get-ChildItem $originalPath\* -Include *.gif, *.jpg, *.xls*, *.doc*, *.pdf*, *.wav*, .ppt*

Note that this will work regardless of whether $originalPath ends in a backslash, because multiple consecutive backslashes are interpreted as a single path separator. For example, try:

Get-ChildItem C:\\\\\Windows

How to access component methods from “outside” in ReactJS?

As mentioned in some of the comments, ReactDOM.render no longer returns the component instance. You can pass a ref callback in when rendering the root of the component to get the instance, like so:

// React code (jsx)
function MyWidget(el, refCb) {
    ReactDOM.render(<MyComponent ref={refCb} />, el);
}
export default MyWidget;

and:

// vanilla javascript code
var global_widget_instance;

MyApp.MyWidget(document.getElementById('my_container'), function(widget) {
    global_widget_instance = widget;
});

global_widget_instance.myCoolMethod();

How To Use DateTimePicker In WPF?

There is a DateTimePicker available in the Extended Toolkit.

File to import not found or unreadable: compass

In short, if you've installed the gem the run:

compass compile

in your rails root dir

Xcode Product -> Archive disabled

You've changed your scheme destination to a simulator instead of Generic iOS Device.

That's why it is greyed out.

Change from a simulator to Generic iOS Device

How to AUTO_INCREMENT in db2?

Added a few optional parameters for creating "future safe" sequences.

CREATE SEQUENCE <NAME>
  START WITH 1
  INCREMENT BY 1
  NO MAXVALUE
  NO CYCLE
  CACHE 10;

How to programmatically turn off WiFi on Android device?

You need the following permissions in your manifest file:

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

Then you can use the following in your activity class:

WifiManager wifiManager = (WifiManager) this.getApplicationContext().getSystemService(Context.WIFI_SERVICE); 
wifiManager.setWifiEnabled(true);
wifiManager.setWifiEnabled(false);

Use the following to check if it's enabled or not

boolean wifiEnabled = wifiManager.isWifiEnabled()

You'll find a nice tutorial on the subject on this site.

Cannot enqueue Handshake after invoking quit

inplace of connection.connect(); use -

if(!connection._connectCalled ) 
{
connection.connect();
}

if it is already called then connection._connectCalled =true,
& it will not execute connection.connect();

note - don't use connection.end();

SQL TRUNCATE DATABASE ? How to TRUNCATE ALL TABLES

As my purpose is to get an empty version of the test database to import data from an external previous current active source (Access database) once all is fine tuned. I found that using DBCC CloneDatabase with Verify_CloneDB option fits perfectly.

python: iterate a specific range in a list

You want to use slicing.

for item in listOfStuff[1:3]:
    print item

Filter array to have unique values

This is for es2015 and above as far as I know. There are 'cleaner' options with ES6 but this a great way to do it (with TypeScript).

let values: any[] = [];
const distinct = (value: any, index: any, self: any) => {
    return self.indexOf(value) === index;
};
values = values.filter(distinct);

How to list active connections on PostgreSQL?

SELECT * FROM pg_stat_activity WHERE datname = 'dbname' and state = 'active';

Since pg_stat_activity contains connection statistics of all databases having any state, either idle or active, database name and connection state should be included in the query to get the desired output.

Anaconda vs. miniconda

Miniconda gives you the Python interpreter itself, along with a command-line tool called conda which operates as a cross-platform package manager geared toward Python packages, similar in spirit to the apt or yum tools that Linux users might be familiar with.

Anaconda includes both Python and conda, and additionally bundles a suite of other pre-installed packages geared toward scientific computing. Because of the size of this bundle, expect the installation to consume several gigabytes of disk space.

Source: Jake VanderPlas's Python Data Science Handbook

Converting Stream to String and back...what are we missing?

I want to serialize objects to strings, and back.

Different from the other answers, but the most straightforward way to do exactly that for most object types is XmlSerializer:

        Subject subject = new Subject();
        XmlSerializer serializer = new XmlSerializer(typeof(Subject));
        using (Stream stream = new MemoryStream())
        {
            serializer.Serialize(stream, subject);
            // do something with stream
            Subject subject2 = (Subject)serializer.Deserialize(stream);
            // do something with subject2
        }

All your public properties of supported types will be serialized. Even some collection structures are supported, and will tunnel down to sub-object properties. You can control how the serialization works with attributes on your properties.

This does not work with all object types, some data types are not supported for serialization, but overall it is pretty powerful, and you don't have to worry about encoding.

How to create an array of 20 random bytes?

Create a Random object with a seed and get the array random by doing:

public static final int ARRAY_LENGTH = 20;

byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);

Retrieve specific commit from a remote Git repository

I think 'git ls-remote' ( http://git-scm.com/docs/git-ls-remote ) should do what you want. Without force fetch or pull.

Move the mouse pointer to a specific position?

Great question. This is really something missing from the Javascript browser API. I'm also working on a WebGL game with my team, and we need this feature. I opened an issue on Firefox's bugzilla so that we can start talking about the possibility of having an API to allow for mouse locking. This is going to be useful for all HTML5/WebGL game developers out there.

If you like, come over and leave a comment with your feedback, and upvote the issue:

https://bugzilla.mozilla.org/show_bug.cgi?id=630979

Thanks!

VueJS conditionally add an attribute for an element

It's notable to understand that if you'd like to conditionally add attributes you can also add a dynamic declaration:

<input v-bind="attrs" />

where attrs is declared as an object:

data() {
    return {
        attrs: {
            required: true,
            type: "text"
        }
    }
}

Which will result in:

<input required type="text"/>

Ideal in cases with multiple attributes.

AngularJS access scope from outside js function

I'm newbie, so sorry if is a bad practice. Based on the chosen answer, I did this function:

function x_apply(selector, variable, value) {
    var scope = angular.element( $(selector) ).scope();
    scope.$apply(function(){
        scope[variable] = value;
    });
}

I'm using it this way:

x_apply('#fileuploader', 'thereisfiles', true);

By the way, sorry for my english

Improve subplot size/spacing with many subplots in matplotlib

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,60))
plt.subplots_adjust( ... )

The plt.subplots_adjust method:

def subplots_adjust(*args, **kwargs):
    """
    call signature::

      subplots_adjust(left=None, bottom=None, right=None, top=None,
                      wspace=None, hspace=None)

    Tune the subplot layout via the
    :class:`matplotlib.figure.SubplotParams` mechanism.  The parameter
    meanings (and suggested defaults) are::

      left  = 0.125  # the left side of the subplots of the figure
      right = 0.9    # the right side of the subplots of the figure
      bottom = 0.1   # the bottom of the subplots of the figure
      top = 0.9      # the top of the subplots of the figure
      wspace = 0.2   # the amount of width reserved for blank space between subplots
      hspace = 0.2   # the amount of height reserved for white space between subplots

    The actual defaults are controlled by the rc file
    """
    fig = gcf()
    fig.subplots_adjust(*args, **kwargs)
    draw_if_interactive()

or

fig = plt.figure(figsize=(10,60))
fig.subplots_adjust( ... )

The size of the picture matters.

"I've tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem."

Thus to make more white space and keep the sub plot size the total image needs to be bigger.

how to use Blob datatype in Postgres

I think this is the most comprehensive answer on the PostgreSQL wiki itself: https://wiki.postgresql.org/wiki/BinaryFilesInDB

Read the part with the title 'What is the best way to store the files in the Database?'

How can I provide multiple conditions for data trigger in WPF?

THIS ANSWER IS FOR ANIMATIONS ONLY


If you wanna implement the AND logic, you should use MultiTrigger, here is an example:

Suppose we want to do some actions if the property Text="" (empty string) AND IsKeyboardFocused="False", then your code should look like the following:

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
        <MultiTrigger.EnterActions>
            <!-- Your actions here -->
        </MultiTrigger.EnterActions>
</MultiTrigger>

If you wanna implement the OR logic, there are couple of ways, and it depends on what you try to do:

The first option is to use multiple Triggers.
So, suppose you wanna do something if either Text="" OR IsKeyboardFocused="False",
then your code should look something like this:

<Trigger Property="IsEnabled" Value="false">
    <Setter Property="Opacity" TargetName="border" Value="0.56"/>
</Trigger>
<Trigger Property="IsMouseOver" Value="true">
    <Setter Property="BorderBrush" TargetName="border" 
            Value="{StaticResource TextBox.MouseOver.Border}"/>
</Trigger>


But the problem in this is what will I do if i wanna do something if either Text ISN'T null OR IsKeyboard="True"? This can be achieved by the second approach:
Recall De Morgan's rule, that says !(!x && !y) = x || y.
So we'll use it to solve the previous problem, by writing a multi trigger that it's triggered when Text="" and IsKeyboard="True", and we'll do our actions in EXIT ACTIONS, like this:

<MultiTrigger>
    <MultiTrigger.Conditions>
        <Condition Property="Text" Value="" />
        <Condition Property="IsKeyboardFocused" Value="False" />
    </MultiTrigger.Conditions>
    <MultiTrigger.ExitActions>
        <!-- Do something here -->
    </MultiTrigger.ExitActions>
</MultiTrigger>

How to make an alert dialog fill 90% of screen size?

Here is my variant for custom dialog's width:

DisplayMetrics displaymetrics = new DisplayMetrics();
mActivity.getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = (int) (displaymetrics.widthPixels * (ThemeHelper.isPortrait(mContext) ? 0.95 : 0.65));

WindowManager.LayoutParams params = getWindow().getAttributes();
params.width = width;
getWindow().setAttributes(params);

So depending on device orientation (ThemeHelper.isPortrait(mContext)) dialog's width will be either 95% (for portrait mode) or 65% (for landscape). It's a little more that the author asked but it could be useful to someone.

You need to create a class that extends from Dialog and put this code into your onCreate(Bundle savedInstanceState) method.

For dialog's height the code should be similar to this.

Using Selenium Web Driver to retrieve value of a HTML input

You can do like this :

webelement time=driver.findElement(By.id("input_name")).getAttribute("value");

this will give you the time displaying on the webpage.

Save text file UTF-8 encoded with VBA

I looked into the answer from Máta whose name hints at encoding qualifications and experience. The VBA docs say CreateTextFile(filename, [overwrite [, unicode]]) creates a file "as a Unicode or ASCII file. The value is True if the file is created as a Unicode file; False if it's created as an ASCII file. If omitted, an ASCII file is assumed." It's fine that a file stores unicode characters, but in what encoding? Unencoded unicode can't be represented in a file.

The VBA doc page for OpenTextFile(filename[, iomode[, create[, format]]]) offers a third option for the format:

  • TriStateDefault 2 "opens the file using the system default."
  • TriStateTrue 1 "opens the file as Unicode."
  • TriStateFalse 0 "opens the file as ASCII."

Máta passes -1 for this argument.

Judging from VB.NET documentation (not VBA but I think reflects realities about how underlying Windows OS represents unicode strings and echoes up into MS Office, I don't know) the system default is an encoding using 1 byte/unicode character using an ANSI code page for the locale. UnicodeEncoding is UTF-16. The docs also describe UTF-8 is also a "Unicode encoding," which makes sense to me. But I don't yet know how to specify UTF-8 for VBA output nor be confident that the data I write to disk with the OpenTextFile(,,,1) is UTF-16 encoded. Tamalek's post is helpful.

How to make child process die after parent exits?

If you send a signal to the pid 0, using for instance

kill(0, 2); /* SIGINT */

that signal is sent to the entire process group, thus effectively killing the child.

You can test it easily with something like:

(cat && kill 0) | python

If you then press ^D, you'll see the text "Terminated" as an indication that the Python interpreter have indeed been killed, instead of just exited because of stdin being closed.

getDate with Jquery Datepicker

You can format the jquery date with this line:

moment($(elem).datepicker('getDate')).format("YYYY-MM-DD");

http://momentjs.com

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

Do you have multiple Radio Buttons on the page..

Because what I see is that you are assigning the events to all the radio button's on the page when you click on a radio button

Why binary_crossentropy and categorical_crossentropy give different performances for the same problem?

I came across an "inverted" issue — I was getting good results with categorical_crossentropy (with 2 classes) and poor with binary_crossentropy. It seems that problem was with wrong activation function. The correct settings were:

  • for binary_crossentropy: sigmoid activation, scalar target
  • for categorical_crossentropy: softmax activation, one-hot encoded target

Read response body in JAX-RS client from a post request

I just found a solution for jaxrs-ri-2.16 - simply use

String output = response.readEntity(String.class)

this delivers the content as expected.

In Java, how do I call a base class's method from the overriding method in a derived class?

class test
{
    void message()
    {
        System.out.println("super class");
    }
}

class demo extends test
{
    int z;
    demo(int y)
    {
        super.message();
        z=y;
        System.out.println("re:"+z);
    }
}
class free{
    public static void main(String ar[]){
        demo d=new demo(6);
    }
}

How can I clone a JavaScript object except for one key?

I use this ESNext one liner

_x000D_
_x000D_
const obj = { a: 1, b: 2, c: 3, d: 4 }_x000D_
const clone = (({ b, c, ...o }) => o)(obj) // remove b and c_x000D_
console.log(clone)
_x000D_
_x000D_
_x000D_


If you need a general purpose function :

_x000D_
_x000D_
function omit(obj, props) {_x000D_
  props = props instanceof Array ? props : [props]_x000D_
  return eval(`(({${props.join(',')}, ...o}) => o)(obj)`)_x000D_
}_x000D_
_x000D_
// usage_x000D_
const obj = { a: 1, b: 2, c: 3, d: 4 }_x000D_
const clone = omit(obj, ['b', 'c'])_x000D_
console.log(clone)
_x000D_
_x000D_
_x000D_

Python - Create list with numbers between 2 values?

assuming you want to have a range between x to y

range(x,y+1)

>>> range(11,17)
[11, 12, 13, 14, 15, 16]
>>>

use list for 3.x support

Python script to copy text to clipboard

I try this clipboard 0.0.4 and it works well.

https://pypi.python.org/pypi/clipboard/0.0.4

import clipboard
clipboard.copy("abc")  # now the clipboard content will be string "abc"
text = clipboard.paste()  # text will have the content of clipboard

How to insert an image in python

Install PIL(Python Image Library) :

then:

from PIL import Image
myImage = Image.open("your_image_here");
myImage.show();

Converting a char to ASCII?

A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

Easiest way to ignore blank lines when reading a file in Python

I guess there is a simple solution which I recently used after going through so many answers here.

with open(file_name) as f_in:   
    for line in f_in:
        if len(line.split()) == 0:
            continue

This just does the same work, ignoring all empty line.

How can you represent inheritance in a database?

Alternatively, consider using a document databases (such as MongoDB) which natively support rich data structures and nesting.

MySQL - UPDATE query based on SELECT Query

You can use:

UPDATE Station AS st1, StationOld AS st2
   SET st1.already_used = 1
 WHERE st1.code = st2.code

socket.error:[errno 99] cannot assign requested address and namespace in python

This error will also appear if you try to connect to an exposed port from within a Docker container, when nothing is actively serving the port.

On a host where nothing is listening/bound to that port you'd get a No connection could be made because the target machine actively refused it error instead when making a request to a local URL that is not served, eg: localhost:5000. However, if you start a container that binds to the port, but there is no server running inside of it actually serving the port, any requests to that port on localhost will result in:

  • [Errno 99] Cannot assign requested address (if called from within the container), or
  • [Errno 0] Error (if called from outside of the container).

You can reproduce this error and the behaviour described above as follows:

Start a dummy container (note: this will pull the python image if not found locally):

docker run --name serv1 -p 5000:5000 -dit python

Then for [Errno 0] Error enter a Python console on host, while for [Errno 99] Cannot assign requested address access a Python console on the container by calling:

docker exec -it -u 0 serv1 python

And then in either case call:

import urllib.request
urllib.request.urlopen('https://localhost:5000')

I concluded with treating either of these errors as equivalent to No connection could be made because the target machine actively refused it rather than trying to fix their cause - although please advise if that's a bad idea.


I've spent over a day figuring this one out, given that all resources and answers I could find on the [Errno 99] Cannot assign requested address point in the direction of binding to an occupied port, connecting to an invalid IP, sysctl conflicts, docker network issues, TIME_WAIT being incorrect, and many more things. Therefore I wanted to leave this answer here, despite not being a direct answer to the question at hand, given that it can be a common cause for the error described in this question.

How to set a string's color

for linux (bash) following code works for me:

System.out.print("\033[31mERROR  \033[0m");

the \033[31m will switch the color to red and \033[0m will switch it back to normal.

DateTime2 vs DateTime in SQL Server

while there is increased precision with datetime2, some clients doesn't support date, time, or datetime2 and force you to convert to a string literal. Specifically Microsoft mentions "down level" ODBC, OLE DB, JDBC, and SqlClient issues with these data types and has a chart showing how each can map the type.

If value compatability over precision, use datetime

Difference between View and ViewGroup in Android

ViewGroup is itself a View that works as a container for other views. It extends the functionality of View class in order to provide efficient ways to layout the child views.

For example, LinearLayout is a ViewGroup that lets you define the orientation in which you want child views to be laid, that's all you need to do and LinearLayout will take care of the rest.

Spring not autowiring in unit tests with JUnit

I'm using JUnit 5 and for me the problem was that I had imported Test from the wrong package:

import org.junit.Test;

Replacing it with the following worked for me:

import org.junit.jupiter.api.Test;

How can I access an internal class from an external assembly?

I see only one case that you would allow exposure to your internal members to another assembly and that is for testing purposes.

Saying that there is a way to allow "Friend" assemblies access to internals:

In the AssemblyInfo.cs file of the project you add a line for each assembly.

[assembly: InternalsVisibleTo("name of assembly here")]

this info is available here.

Hope this helps.

Using event.target with React components

First argument in update method is SyntheticEvent object that contains common properties and methods to any event, it is not reference to React component where there is property props.

if you need pass argument to update method you can do it like this

onClick={ (e) => this.props.onClick(e, 'home', 'Home') }

and get these arguments inside update method

update(e, space, txt){
   console.log(e.target, space, txt);
}

Example


event.target gives you the native DOMNode, then you need to use the regular DOM APIs to access attributes. For instance getAttribute or dataset

<button 
  data-space="home" 
  className="home" 
  data-txt="Home" 
  onClick={ this.props.onClick } 
/> 
  Button
</button>

onClick(e) {
   console.log(e.target.dataset.txt, e.target.dataset.space);
}

Example

How to convert a "dd/mm/yyyy" string to datetime in SQL Server?

SELECT convert(varchar(10), '23/07/2009', 111)

Can I replace groups in Java regex?

Use $n (where n is a digit) to refer to captured subsequences in replaceFirst(...). I'm assuming you wanted to replace the first group with the literal string "number" and the second group with the value of the first group.

Pattern p = Pattern.compile("(\\d)(.*)(\\d)");
String input = "6 example input 4";
Matcher m = p.matcher(input);
if (m.find()) {
    // replace first number with "number" and second number with the first
    String output = m.replaceFirst("number $3$1");  // number 46
}

Consider (\D+) for the second group instead of (.*). * is a greedy matcher, and will at first consume the last digit. The matcher will then have to backtrack when it realizes the final (\d) has nothing to match, before it can match to the final digit.

Converting Epoch time into the datetime

If you have epoch in milliseconds a possible solution is convert to seconds:

import time
time.ctime(milliseconds/1000)

For more time functions: https://docs.python.org/3/library/time.html#functions

CSV file written with Python has blank lines between each row

Note: It seems this is not the preferred solution because of how the extra line was being added on a Windows system. As stated in the python document:

If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.

Windows is one such platform where that makes a difference. While changing the line terminator as I described below may have fixed the problem, the problem could be avoided altogether by opening the file in binary mode. One might say this solution is more "elegent". "Fiddling" with the line terminator would have likely resulted in unportable code between systems in this case, where opening a file in binary mode on a unix system results in no effect. ie. it results in cross system compatible code.

From Python Docs:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Original:

As part of optional paramaters for the csv.writer if you are getting extra blank lines you may have to change the lineterminator (info here). Example below adapated from the python page csv docs. Change it from '\n' to whatever it should be. As this is just a stab in the dark at the problem this may or may not work, but it's my best guess.

>>> import csv
>>> spamWriter = csv.writer(open('eggs.csv', 'w'), lineterminator='\n')
>>> spamWriter.writerow(['Spam'] * 5 + ['Baked Beans'])
>>> spamWriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])

A connection was successfully established with the server, but then an error occurred during the pre-login handshake

I was getting the exact same problem with no chnges to the code base or servers. It turned out to be that the DB server was running at 100% CPU and SQL Server was being starved of any CPU time, which caused the timeout.

The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

Use string instead of string? in all places in your code.

The Nullable<T> type requires that T is a non-nullable value type, for example int or DateTime. Reference types like string can already be null. There would be no point in allowing things like Nullable<string> so it is disallowed.

Also if you are using C# 3.0 or later you can simplify your code by using auto-implemented properties:

public class WordAndMeaning
{
    public string Word { get; set; }
    public string Meaning { get; set; }
}

Jquery assiging class to th in a table

You had thead in your selector, but there is no thead in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr class to the th, not vice-versa (although your comment seems to contradict what you wrote up above).

$('tr th').each(function(index){     if($('tr td').eq(index).attr('class') != ''){         // get the class of the td         var tdClass = $('tr td').eq(index).attr('class');         // add it to this th         $(this).addClass(tdClass );     } }); 

Fiddle

disable past dates on datepicker

Note: This scripts works when you're using the daterangepicker library. If you want to disable the Sat or Sunday date on daterangepicker then put this line of code.

        $("#event_start").daterangepicker({
            // minDate: new Date(),
            minYear: 2000,
            showDropdowns: true,
            singleDatePicker: true,
            timePicker: true,
            timePicker24Hour: false,
            timePickerIncrement: 15,
            drops:"up",
            isInvalidDate: function(date) {
                //return true if date is sunday or saturday
                return (date.day() == 0 || date.day() == 6);
            },
            locale: {
                format: 'MM/DD/YYYY hh:mm A'
            }
        });

OR if you want to disable the previous date also with sat and sun then uncomment the this line minDate: new Date()

How do you check if a string is not equal to an object or other string value in java?

you'll want to use && to see that it is not equal to "AM" AND not equal to "PM"

if(!TimeOfDayStringQ.equals("AM") && !TimeOfDayStringQ.equals("PM")) {
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to be clear you can also do

if(!(TimeOfDayStringQ.equals("AM") || TimeOfDayStringQ.equals("PM"))){
    System.out.println("Sorry, incorrect input.");
    System.exit(1);
}

to have the not (one or the other) phrase in the code (remember the (silent) brackets)

How can I include a YAML file inside another?

The YML standard does not specify a way to do this. And this problem does not limit itself to YML. JSON has the same limitations.

Many applications which use YML or JSON based configurations run into this problem eventually. And when that happens, they make up their own convention.

e.g. for swagger API definitions:

$ref: 'file.yml'

e.g. for docker compose configurations:

services:
  app:
    extends:
      file: docker-compose.base.yml

Alternatively, if you want to split up the content of a yml file in multiple files, like a tree of content, you can define your own folder-structure convention and use an (existing) merge script.

ASP.NET MVC Page Won't Load and says "The resource cannot be found"

Make sure you're not telling IIS to check and see if a file exists before serving it up. This one has bitten me a couple times. Do the following:

Open IIS manager. Right click on your MVC website and click properties. Open the Virtual Directory tab. Click the Configuration... button. Under Wildcard application maps, make sure you have a mapping to c:\windows\microsoft.net\framework\v2.0.50727\aspnet_isapi.dll. MAKE SURE "Verify the file exists" IS NOT CHECKED!

TensorFlow: "Attempting to use uninitialized value" in variable initialization

There is another the error happening which related to the order when calling initializing global variables. I've had the sample of code has similar error FailedPreconditionError (see above for traceback): Attempting to use uninitialized value W

def linear(X, n_input, n_output, activation = None):
    W = tf.Variable(tf.random_normal([n_input, n_output], stddev=0.1), name='W')
    b = tf.Variable(tf.constant(0, dtype=tf.float32, shape=[n_output]), name='b')
    if activation != None:
        h = tf.nn.tanh(tf.add(tf.matmul(X, W),b), name='h')
    else:
        h = tf.add(tf.matmul(X, W),b, name='h')
    return h

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as sess:
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    # But W hasn't in the graph yet so not know to initialize 
    # EVAL then error
    print(linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3).eval())

You should change to following

from tensorflow.python.framework import ops
ops.reset_default_graph()
g = tf.get_default_graph()
print([op.name for op in g.get_operations()])
with tf.Session() as 
    # NOT RUNNING BUT ASSIGN
    l = linear(np.array([[1.0,2.0,3.0]]).astype(np.float32), 3, 3)
    # RUN INIT
    sess.run(tf.global_variables_initializer())
    print([op.name for op in g.get_operations()])
    # ONLY EVAL AFTER INIT
    print(l.eval(session=sess))

Granting Rights on Stored Procedure to another user of Oracle

SQL> grant create any procedure to testdb;

This is a command when we want to give create privilege to "testdb" user.

Java system properties and environment variables

How do I capture the output of a script if it is being ran by the task scheduler?

You can have a debug.cmd that calls yourscript.cmd

yourscript.cmd > logall.txt

you schedule debug.cmd instead of yourscript.cmd

PHP order array by date?

Use usort:

usort($array, function($a1, $a2) {
   $v1 = strtotime($a1['date']);
   $v2 = strtotime($a2['date']);
   return $v1 - $v2; // $v2 - $v1 to reverse direction
});

How to define an optional field in protobuf 3

Another way is that you can use bitmask for each optional field. and set those bits if values are set and reset those bits which values are not set

enum bitsV {
    baz_present = 1; // 0x01
    baz1_present = 2; // 0x02

}
message Foo {
    uint32 bitMask;
    required int32 bar = 1;
    optional int32 baz = 2;
    optional int32 baz1 = 3;
}

On parsing check for value of bitMask.

if (bitMask & baz_present)
    baz is present

if (bitMask & baz1_present)
    baz1 is present

mysqli_fetch_array while loop columns

This one was your solution.

$x = 0;
while($row = mysqli_fetch_array($result)) {             
    $posts[$x]['post_id'] = $row['post_id'];
    $posts[$x]['post_title'] = $row['post_title'];
    $posts[$x]['type'] = $row['type'];
    $posts[$x]['author'] = $row['author'];
    $x++;
}

keycode and charcode

keyCode and which represent the actual keyboard key pressed in the form of a numeric value. The reason both exist is that keyCode is available within Internet Explorer while which is available in W3C browsers like FireFox.

charCode is similar, but in this case you retrieve the Unicode value of the character pressed. For example, the letter "A."

The JavaScript expression:

var keyCode = e.keyCode ? e.keyCode : e.charCode;

Essentially says the following:

If the e.keyCode property exists, set variable keyCode to its value. Otherwise, set variable keyCode to the value of the e.charCode property.

Note that retrieving the keyCode or charCode properties typically involve figuring out differences between the event models in IE and in W3C. Some entails writing code like the following:

/*
 get the event object: either window.event for IE 
 or the parameter e for other browsers
*/
var evt = window.event ? window.event : e;
/*
 get the numeric value of the key pressed: either 
 event.keyCode for IE for e.which for other browsers
*/
var keyCode = evt.keyCode ? evt.keyCode : e.which;

EDIT: Corrections to my explanation of charCode as per Tor Haugen's comments.

Set Matplotlib colorbar size to match graph

You can do this easily with a matplotlib AxisDivider.

The example from the linked page also works without using subplots:

import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np

plt.figure()
ax = plt.gca()
im = ax.imshow(np.arange(100).reshape((10,10)))

# create an axes on the right side of ax. The width of cax will be 5%
# of ax and the padding between cax and ax will be fixed at 0.05 inch.
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)

plt.colorbar(im, cax=cax)

enter image description here

Vector of structs initialization

If you want to use the new current standard, you can do so:

sub.emplace_back ("Math", 70, 0);

or

sub.push_back ({"Math", 70, 0});

These don't require default construction of subject.

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

my problem with getting this error was resolved by using the full URL "qatest.ourCompany.com/webService" instead of just "qatest/webService". Reason was that our security certificate had a wildcard i.e. "*.ourCompany.com". Once I put in the full address the exception went away. Hope this helps.

Using async/await for multiple tasks

Parallel.ForEach requires a list of user-defined workers and a non-async Action to perform with each worker.

Task.WaitAll and Task.WhenAll require a List<Task>, which are by definition asynchronous.

I found RiaanDP's response very useful to understand the difference, but it needs a correction for Parallel.ForEach. Not enough reputation to respond to his comment, thus my own response.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;

namespace AsyncTest
{
    class Program
    {
        class Worker
        {
            public int Id;
            public int SleepTimeout;

            public void DoWork(DateTime testStart)
            {
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
                Thread.Sleep(SleepTimeout);
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
            }

            public async Task DoWorkAsync(DateTime testStart)
            {
                var workerStart = DateTime.Now;
                Console.WriteLine("Worker {0} started on thread {1}, beginning {2} seconds after test start.",
                    Id, Thread.CurrentThread.ManagedThreadId, (workerStart - testStart).TotalSeconds.ToString("F2"));
                await Task.Run(() => Thread.Sleep(SleepTimeout));
                var workerEnd = DateTime.Now;
                Console.WriteLine("Worker {0} stopped; the worker took {1} seconds, and it finished {2} seconds after the test start.",
                   Id, (workerEnd - workerStart).TotalSeconds.ToString("F2"), (workerEnd - testStart).TotalSeconds.ToString("F2"));
            }
        }

        static void Main(string[] args)
        {
            var workers = new List<Worker>
            {
                new Worker { Id = 1, SleepTimeout = 1000 },
                new Worker { Id = 2, SleepTimeout = 2000 },
                new Worker { Id = 3, SleepTimeout = 3000 },
                new Worker { Id = 4, SleepTimeout = 4000 },
                new Worker { Id = 5, SleepTimeout = 5000 },
            };

            var startTime = DateTime.Now;
            Console.WriteLine("Starting test: Parallel.ForEach...");
            PerformTest_ParallelForEach(workers, startTime);
            var endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WaitAll...");
            PerformTest_TaskWaitAll(workers, startTime);
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            startTime = DateTime.Now;
            Console.WriteLine("Starting test: Task.WhenAll...");
            var task = PerformTest_TaskWhenAll(workers, startTime);
            task.Wait();
            endTime = DateTime.Now;
            Console.WriteLine("Test finished after {0} seconds.\n",
                (endTime - startTime).TotalSeconds.ToString("F2"));

            Console.ReadKey();
        }

        static void PerformTest_ParallelForEach(List<Worker> workers, DateTime testStart)
        {
            Parallel.ForEach(workers, worker => worker.DoWork(testStart));
        }

        static void PerformTest_TaskWaitAll(List<Worker> workers, DateTime testStart)
        {
            Task.WaitAll(workers.Select(worker => worker.DoWorkAsync(testStart)).ToArray());
        }

        static Task PerformTest_TaskWhenAll(List<Worker> workers, DateTime testStart)
        {
            return Task.WhenAll(workers.Select(worker => worker.DoWorkAsync(testStart)));
        }
    }
}

The resulting output is below. Execution times are comparable. I ran this test while my computer was doing the weekly anti virus scan. Changing the order of the tests did change the execution times on them.

Starting test: Parallel.ForEach...
Worker 1 started on thread 9, beginning 0.02 seconds after test start.
Worker 2 started on thread 10, beginning 0.02 seconds after test start.
Worker 3 started on thread 11, beginning 0.02 seconds after test start.
Worker 4 started on thread 13, beginning 0.03 seconds after test start.
Worker 5 started on thread 14, beginning 0.03 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.02 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.02 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.03 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.03 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.03 seconds after the test start.
Test finished after 5.03 seconds.

Starting test: Task.WaitAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.01 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.01 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.01 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.01 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.01 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Starting test: Task.WhenAll...
Worker 1 started on thread 9, beginning 0.00 seconds after test start.
Worker 2 started on thread 9, beginning 0.00 seconds after test start.
Worker 3 started on thread 9, beginning 0.00 seconds after test start.
Worker 4 started on thread 9, beginning 0.00 seconds after test start.
Worker 5 started on thread 9, beginning 0.00 seconds after test start.
Worker 1 stopped; the worker took 1.00 seconds, and it finished 1.00 seconds after the test start.
Worker 2 stopped; the worker took 2.00 seconds, and it finished 2.00 seconds after the test start.
Worker 3 stopped; the worker took 3.00 seconds, and it finished 3.00 seconds after the test start.
Worker 4 stopped; the worker took 4.00 seconds, and it finished 4.00 seconds after the test start.
Worker 5 stopped; the worker took 5.00 seconds, and it finished 5.01 seconds after the test start.
Test finished after 5.01 seconds.

Sites not accepting wget user agent header

I created a ~/.wgetrc file with the following content (obtained from askapache.com but with a newer user agent, because otherwise it didn’t work always):

header = Accept-Language: en-us,en;q=0.5
header = Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
header = Connection: keep-alive
user_agent = Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:40.0) Gecko/20100101 Firefox/40.0
referer = /
robots = off

Now I’m able to download from most (all?) file-sharing (streaming video) sites.

Xampp MySQL not starting - "Attempting to start MySQL service..."

Had this problem today, on a Windows 10 machine. Opened C:\xampp\data\mysql_error.log and looked for lines containing [ERROR].

Last error line was:

... [ERROR] InnoDB: File (unknown): 'close' returned OS error 206. Cannot continue operation

Important note: if your error is different, google it (you'll likely find a fix).

Searching for the above error, found this thread on Apache Friends Support Forum, which led me to the fix:

  1. Open C:\xampp\mysql\bin\my.ini and add the following line towards the end of [mysqld] section (above the line containing ## UTF 8 Settings):
innodb_flush_method=normal
  1. Restart MySQL service. Should run just fine.

Vue v-on:click does not work on component

If you want to listen to a native event on the root element of a component, you have to use the .native modifier for v-on, like following:

<template>
  <div id="app">
    <test v-on:click.native="testFunction"></test>
  </div>
</template>

or in shorthand, as suggested in comment, you can as well do:

<template>
  <div id="app">
    <test @click.native="testFunction"></test>
  </div>
</template>

How to enable directory listing in apache web server

I solved the problem by enabling the mod_autoindex from Apache. It was disabled by default.

sudo a2enmod autoindex

$rootScope.$broadcast vs. $scope.$emit

I made the following graphic out of the following link: https://toddmotto.com/all-about-angulars-emit-broadcast-on-publish-subscribing/

Scope, rootScope, emit, broadcast

As you can see, $rootScope.$broadcast hits a lot more listeners than $scope.$emit.

Also, $scope.$emit's bubbling effect can be cancelled, whereas $rootScope.$broadcast cannot.

Remove Backslashes from Json Data in JavaScript

try this

var finalData = str.replace(/\\/g, '');

When and where to use GetType() or typeof()?

typeOf is a C# keyword that is used when you have the name of the class. It is calculated at compile time and thus cannot be used on an instance, which is created at runtime. GetType is a method of the object class that can be used on an instance.

Understanding typedefs for function pointers in C

cdecl is a great tool for deciphering weird syntax like function pointer declarations. You can use it to generate them as well.

As far as tips for making complicated declarations easier to parse for future maintenance (by yourself or others), I recommend making typedefs of small chunks and using those small pieces as building blocks for larger and more complicated expressions. For example:

typedef int (*FUNC_TYPE_1)(void);
typedef double (*FUNC_TYPE_2)(void);
typedef FUNC_TYPE_1 (*FUNC_TYPE_3)(FUNC_TYPE_2);

rather than:

typedef int (*(*FUNC_TYPE_3)(double (*)(void)))(void);

cdecl can help you out with this stuff:

cdecl> explain int (*FUNC_TYPE_1)(void)
declare FUNC_TYPE_1 as pointer to function (void) returning int
cdecl> explain double (*FUNC_TYPE_2)(void)
declare FUNC_TYPE_2 as pointer to function (void) returning double
cdecl> declare FUNC_TYPE_3 as pointer to function (pointer to function (void) returning double) returning pointer to function (void) returning int
int (*(*FUNC_TYPE_3)(double (*)(void )))(void )

And is (in fact) exactly how I generated that crazy mess above.

When is del useful in Python?

When is del useful in python?

You can use it to remove a single element of an array instead of the slice syntax x[i:i+1]=[]. This may be useful if for example you are in os.walk and wish to delete an element in the directory. I would not consider a keyword useful for this though, since one could just make a [].remove(index) method (the .remove method is actually search-and-remove-first-instance-of-value).

How to remove a build from itunes connect?

I had this problem. I'll share my ride on the learning curve.

First, I couldn't find how to reject the binary but remembered seeing it earlier today in the iTunesConnect App. So using the App I rejected the binary.

If you "mouse over" the rejected binary under the "Build" section you'll notice that a red circle icon with a - (i.e. a delete button) appears. Tap on this and then hit the save button at the top of the screen. Submitted binary is now gone.

You should now get all the notifications for the app being in state "Prepare for Upload" (email, App notification etc).

Xcode organiser was still giving me "Redundant Binary". After a bit of research I now understand the difference between "Version" & "Build". Version is what iTunes displays and the user sees. Build is just the internal tracking number. I had both at 2.3.0, I changed build to 2.3.0.1 and re-Archive. Now it validates and I can upload the new binary and re-submit. Hope that helps others!

"message failed to fetch from registry" while trying to install any module

One thing that has worked for me with random npm install errors (where the package that errors out is different under different times (but same environment) is to use this:

npm cache clean

And then repeat the process. Then the process seems to go smoother and the real problem and error message will emerge, where you can fix it and then proceed.

This is based on experience of running npm install of a whole bunch of packages under a pretty bare Ubuntu installation inside a Docker instance. Sometimes there are build/make tools missing from the Ubuntu and the npm errors will not show the real problem until you clean the cache for some reason.

Why are exclamation marks used in Ruby methods?

Bottom line: ! methods just change the value of the object they are called upon, whereas a method without ! returns a manipulated value without writing over the object the method was called upon.

Only use ! if you do not plan on needing the original value stored at the variable you called the method on.

I prefer to do something like:

foo = "word"
bar = foo.capitalize
puts bar

OR

foo = "word"
puts foo.capitalize

Instead of

foo = "word"
foo.capitalize!
puts foo

Just in case I would like to access the original value again.

Website screenshots

There is a lot of options and they all have their pros and cons. Here is list of options ordered by implementation difficulty.

Option 1: Use an API (the easiest)

Pros

  • Execute Javascript
  • Near perfect rendering
  • Fast when caching options are correctly used
  • Scale is handled by the APIs
  • Precise timing, viewport, ...
  • Most of the time they offer a free plan

Cons

  • Not free if you plan to use them a lot

Option 2: Use one of the many available libraries

Pros

  • Conversion is quite fast most of the time

Cons

  • Bad rendering
  • Does not execute javascript
  • No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, HTML5 tags...)
  • Sometimes not so easy to install
  • Complicated to scale

Option 3: Use PhantomJs and maybe a wrapper library

Pros

  • Execute Javascript
  • Quite fast

Cons

  • Bad rendering
  • PhantomJs has been deprecated and is not maintained anymore.
  • No support for recent web features (FlexBox, Advanced Selectors, Webfonts, Box Sizing, Media Queries, HTML5 tags...)
  • Complicated to scale
  • Not so easy to make it work if there is images to be loaded ...

Option 4: Use Chrome Headless and maybe a wrapper library

Pros

  • Execute Javascript
  • Near perfect rendering

Cons

  • Not so easy to have exactly the wanted result regarding:
    • page load timing
    • proxy integration
    • auto scrolling
    • ...
  • Complicated to scale
  • Quite slow and even slower if the html contains external links

Disclaimer: I'm the founder of ApiFlash. I did my best to provide an honest and useful answer.

How do I change the figure size for a seaborn plot?

You can also set figure size by passing dictionary to rc parameter with key 'figure.figsize' in seaborn set method:

import seaborn as sns

sns.set(rc={'figure.figsize':(11.7,8.27)})

Other alternative may be to use figure.figsize of rcParams to set figure size as below:

from matplotlib import rcParams

# figure size in inches
rcParams['figure.figsize'] = 11.7,8.27

More details can be found in matplotlib documentation

Is Laravel really this slow?

Laravel is not actually that slow. 500-1000ms is absurd; I got it down to 20ms in debug mode.

The problem was Vagrant/VirtualBox + shared folders. I didn't realize they incurred such a performance hit. I guess because Laravel has so many dependencies (loads ~280 files) and each of those file reads is slow, it adds up really quick.

kreeves pointed me in the right direction, this blog post describes a new feature in Vagrant 1.5 that lets you rsync your files into the VM rather than using a shared folder.

There's no native rsync client on Windows, so you'll have to use cygwin. Install it, and make sure to check off Net/rsync. Add C:\cygwin64\bin to your paths. [Or you can install it on Win10/Bash]

Vagrant introduces the new feature. I'm using Puphet, so my Vagrantfile looks a bit funny. I had to tweak it to look like this:

  data['vm']['synced_folder'].each do |i, folder|
    if folder['source'] != '' && folder['target'] != '' && folder['id'] != ''
      config.vm.synced_folder "#{folder['source']}", "#{folder['target']}", 
        id: "#{folder['id']}", 
        type: "rsync",
        rsync__auto: "true",
        rsync__exclude: ".hg/"
    end
  end

Once you're all set up, try vagrant up. If everything goes smoothly your machine should boot up and it should copy all the files over. You'll need to run vagrant rsync-auto in a terminal to keep the files up to date. You'll pay a little bit in latency, but for 30x faster page loads, it's worth it!


If you're using PhpStorm, it's auto-upload feature works even better than rsync. PhpStorm creates a lot of temporary files which can trip up file watchers, but if you let it handle the uploads itself, it works nicely.


One more option is to use lsyncd. I've had great success using this on Ubuntu host -> FreeBSD guest. I haven't tried it on a Windows host yet.

How to change the default charset of a MySQL table?

If you want to change the table default character set and all character columns to a new character set, use a statement like this:

ALTER TABLE tbl_name CONVERT TO CHARACTER SET charset_name;

So query will be:

ALTER TABLE etape_prospection CONVERT TO CHARACTER SET utf8;

convert streamed buffers to utf8-string

var fs = require("fs");

function readFileLineByLine(filename, processline) {
    var stream = fs.createReadStream(filename);
    var s = "";
    stream.on("data", function(data) {
        s += data.toString('utf8');
        var lines = s.split("\n");
        for (var i = 0; i < lines.length - 1; i++)
            processline(lines[i]);
        s = lines[lines.length - 1];
    });

    stream.on("end",function() {
        var lines = s.split("\n");
        for (var i = 0; i < lines.length; i++)
            processline(lines[i]);
    });
}

var linenumber = 0;
readFileLineByLine(filename, function(line) {
    console.log(++linenumber + " -- " + line);
});

JavaScript/jQuery - "$ is not defined- $function()" error

Try:

(function($) {
    $(function() {
        $('.update').live('change', function() {
            formObject.run($(this));
        });
    });
})(jQuery);

By using this way you ensure the global variable jQuery will be bound to the "$" inside the closure. Just make sure jQuery is properly loaded into the page by inserting:

<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

Replace "http://code.jquery.com/jquery-1.7.1.min.js" to the path where your jQuery source is located within the page context.