Programs & Examples On #Agents

0

Android Room - simple select query - Cannot access database on the main thread

You have to execute request in background. A simple way could be using an Executors :

Executors.newSingleThreadExecutor().execute { 
   yourDb.yourDao.yourRequest() //Replace this by your request
}

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

UMD/AMD solution

For those guys, who are doing it through UMD, and compile via require.js, there is a laconic solution.

In the module, which requires tether as the dependency, which loads Tooltip as UMD, in front of module definition, just put short snippet on definition of Tether:

// First load the UMD module dependency and attach to global scope
require(['tether'], function(Tether) {
    // @todo: make it properly when boostrap will fix loading of UMD, instead of using globals
    window.Tether = Tether; // attach to global scope
});

// then goes your regular module definition
define([
    'jquery',
    'tooltip',
    'popover'
], function($, Tooltip, Popover){
    "use strict";
    //...
    /*
        by this time, you'll have window.Tether global variable defined,
        and UMD module Tooltip will not throw the exception
    */
    //...
});

This short snippet at the very beginning, actually may be put on any higher level of your application, the most important thing - to invoke it before actual usage of bootstrap components with Tether dependency.

// ===== file: tetherWrapper.js =====
require(['./tether'], function(Tether) {
    window.Tether = Tether; // attach to global scope
    // it's important to have this, to keep original module definition approach
    return Tether;
});

// ===== your MAIN configuration file, and dependencies definition =====
paths: {
    jquery: '/vendor/jquery',
    // tether: '/vendor/tether'
    tether: '/vendor/tetherWrapper'  // @todo original Tether is replaced with our wrapper around original
    // ...
},
shim: { 
     'bootstrap': ['tether', 'jquery']       
}

UPD: In Boostrap 4.1 Stable they replaced Tether, with Popper.js, see the documentation on usage.

Docker: Copying files from Docker container to host

Another good option is first build the container and then run it using the -c flag with the shell interpreter to execute some commads

docker run --rm -i -v <host_path>:<container_path> <mydockerimage> /bin/sh -c "cp -r /tmp/homework/* <container_path>"

The above command does this:

-i = run the container in interactive mode

--rm = removed the container after the execution.

-v = shared a folder as volume from your host path to the container path.

Finally, the /bin/sh -c lets you introduce a command as a parameter and that command will copy your homework files to the container path.

I hope this additional answer may help you

Hamcrest compare collections

If you want to assert that the two lists are identical, don't complicate things with Hamcrest:

assertEquals(expectedList, actual.getList());

If you really intend to perform an order-insensitive comparison, you can call the containsInAnyOrder varargs method and provide values directly:

assertThat(actual.getList(), containsInAnyOrder("item1", "item2"));

(Assuming that your list is of String, rather than Agent, for this example.)

If you really want to call that same method with the contents of a List:

assertThat(actual.getList(), containsInAnyOrder(expectedList.toArray(new String[expectedList.size()]));

Without this, you're calling the method with a single argument and creating a Matcher that expects to match an Iterable where each element is a List. This can't be used to match a List.

That is, you can't match a List<Agent> with a Matcher<Iterable<List<Agent>>, which is what your code is attempting.

Difference between no-cache and must-revalidate

I think there is a difference between max-age=0, must-revalidate and no-cache:

In the must-revalidate case the client is allowed to send a If-Modified-Since request and serve the response from cache if 304 Not Modified is returned.

In the no-cache case, the client must not cache the response, so should not use If-Modified-Since.

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

Using Mockito to stub and execute methods for testing

You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.

Think of it like this…

  • I need to test a function of a class - let's call it myFunction
  • That function makes a call to a function on another class/service/database
  • That function also calls another method on the CUT

In the unit test

  • Should create a concrete CUT or @Spy on it
  • You can @Mock all of the other class/service/database (i.e. external dependencies)
  • You could stub the other function called in the CUT but it is not really how unit testing should be done

In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mocked.

In this very simple example, a function that creates an object will be difficult to test

public void doSomethingCool(String foo) {
    MyObject obj = new MyObject(foo);

    // can't do much with obj in a unit test unless it is returned
}

But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.

public void doSomethingCool(String foo) {
    MyObject obj = MyObjectService.getMeAnObject(foo);
}

as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.

How to get page content using cURL?

Try This:

$url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

Postgres could not connect to server

So i stubled upon this after the rails db:create command. Setting up the environment in a macOS Catalina 10.15.3.

First thing that i checked was the flow that got me here. After ensuring that that all things had went smoothly and there was no error that might had escaped my mind i tried the most popular solutions from here but none of the seemed to work.

So far the only error i was seeing was the

$ psql psql: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/tmp/.s.PGSQL.5432"?

So i needed some more specific information about what was happening. Due to that reason i decided to look at the postgres logfile which is located at

/usr/local/var/log/postgres.log

So after opening the log i saw this error

LOG: starting PostgreSQL 12.2 on x86_64-apple-darwin19.3.0, compiled by Apple clang version 11.0.0 (clang-1100.0.33.17), 64-bit LOG: could not translate host name "localhost", service "5432" to address: nodename nor servname provided, or not known WARNING: could not create listen socket for "localhost" FATAL: could not create any TCP/IP sockets LOG: database system is shut down

So this is a bit more explanatory and specific. The problem is something about that PostgreSQL cannot "see" and resolve the localhost server.

So next thing i did was to check the /etc/hosts file whose default contents should look like this:

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost
::1          localhost 

After comparing the above with mine i saw that in mine this line was different and commented (!).

#::1             localhost

So i removed the # symbol in front of the line saved the file and re run the

rails db:create 

and the database was succesfully initiated.

PostgreSQL error 'Could not connect to server: No such file or directory'

There might be different issues with running PostgreSQL locally. I would recommend to clean all versions of postgres installed and start fresh. Once you have it installed, it's very easy to recreate your database if you have your rails project with the up to date db/schema.rb

Here is how I usually install PostgreSQL on a Mac. If you're running your database under the root user locally, you might want to omit the last step that creates a todo user

Setting the User-Agent header for a WebClient request

You can also use that:

client.Headers.Add(HttpRequestHeader.UserAgent, "My app.");

Detecting a mobile browser

How about something like this?

if(
    (screen.width <= 640) || 
    (window.matchMedia && 
     window.matchMedia('only screen and (max-width: 640px)').matches
    )
  ){
   // Do the mobile thing
}

Difference between Pragma and Cache-Control headers?

Pragma is the HTTP/1.0 implementation and cache-control is the HTTP/1.1 implementation of the same concept. They both are meant to prevent the client from caching the response. Older clients may not support HTTP/1.1 which is why that header is still in use.

Fetching data from MySQL database to html dropdown list

# here database details      
mysql_connect('hostname', 'username', 'password');
mysql_select_db('database-name');

$sql = "SELECT username FROM userregistraton";
$result = mysql_query($sql);

echo "<select name='username'>";
while ($row = mysql_fetch_array($result)) {
    echo "<option value='" . $row['username'] ."'>" . $row['username'] ."</option>";
}
echo "</select>";

# here username is the column of my table(userregistration)
# it works perfectly

How to scroll table's "tbody" independent of "thead"?

mandatory parts:

tbody {
    overflow-y: scroll;  (could be: 'overflow: scroll' for the two axes)
    display: block;
    with: xxx (a number or 100%)
}

thead {
    display: inline-block;
}

Android read text raw resource file

Here is a simple method to read the text file from the raw folder:

public static String readTextFile(Context context,@RawRes int id){
    InputStream inputStream = context.getResources().openRawResource(id);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    byte buffer[] = new byte[1024];
    int size;
    try {
        while ((size = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, size);
        }
        outputStream.close();
        inputStream.close();
    } catch (IOException e) {

    }
    return outputStream.toString();
}

How to tell 'PowerShell' Copy-Item to unconditionally copy files

From the documentation (help copy-item -full):

-force <SwitchParameter>
    Allows cmdlet to override restrictions such as renaming existing files as long as security is not compromised.

    Required?                    false
    Position?                    named
    Default value                False
    Accept pipeline input?       false
    Accept wildcard characters?  false

HTTP POST with URL query parameters -- good idea or not?

If your action is not idempotent, then you MUST use POST. If you don't, you're just asking for trouble down the line. GET, PUT and DELETE methods are required to be idempotent. Imagine what would happen in your application if the client was pre-fetching every possible GET request for your service – if this would cause side effects visible to the client, then something's wrong.

I agree that sending a POST with a query string but without a body seems odd, but I think it can be appropriate in some situations.

Think of the query part of a URL as a command to the resource to limit the scope of the current request. Typically, query strings are used to sort or filter a GET request (like ?page=1&sort=title) but I suppose it makes sense on a POST to also limit the scope (perhaps like ?action=delete&id=5).

How can I convert an HTML element to a canvas element?

No such thing, sorry.

Though the spec states:

A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.

Which may be as close as you'll get.

A lot of people want a ctx.drawArbitraryHTML/Element kind of deal but there's nothing built in like that.

The only exception is Mozilla's exclusive drawWindow, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

As Simon mentioned, this is not possible in the new Facebook API. Pure technically speaking you can do it via browser automation.

  • this is against Facebook policy, so depending on the country where you live, this may not be legal
  • you'll have to use your credentials / ask user for credentials and possibly store them (storing passwords even symmetrically encrypted is not a good idea)
  • when Facebook changes their API, you'll have to update the browser automation code as well (if you can't force updates of your application, you should put browser automation piece out as a webservice)
  • this is bypassing the OAuth concept
  • on the other hand, my feeling is that I'm owning my data including the list of my friends and Facebook shouldn't restrict me from accessing those via the API

Sample implementation using WatiN:

class FacebookUser
{
  public string Name { get; set; }
  public long Id { get; set; }
}

public IList<FacebookUser> GetFacebookFriends(string email, string password, int? maxTimeoutInMilliseconds)
{
  var users = new List<FacebookUser>();
  Settings.Instance.MakeNewIeInstanceVisible = false;
  using (var browser = new IE("https://www.facebook.com"))
  {
    try
    {
      browser.TextField(Find.ByName("email")).Value = email;
      browser.TextField(Find.ByName("pass")).Value = password;
      browser.Form(Find.ById("login_form")).Submit();
      browser.WaitForComplete();
    }
    catch (ElementNotFoundException)
    {
      // We're already logged in
    }
    browser.GoTo("https://www.facebook.com/friends");
    var watch = new Stopwatch();
    watch.Start();

    Link previousLastLink = null;
    while (maxTimeoutInMilliseconds.HasValue && watch.Elapsed.TotalMilliseconds < maxTimeoutInMilliseconds.Value)
    {
      var lastLink = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
                       && l.GetAttributeValue("data-hovercard").Contains("user.php")
                       && l.Text != null
                     ).LastOrDefault();

      if (lastLink == null || previousLastLink == lastLink)
      {
        break;
      }

      var ieElement = lastLink.NativeElement as IEElement;
      if (ieElement != null)
      {
        var htmlElement = ieElement.AsHtmlElement;
        htmlElement.scrollIntoView();
        browser.WaitForComplete();
      }

      previousLastLink = lastLink;
    }

    var links = browser.Links.Where(l => l.GetAttributeValue("data-hovercard") != null
      && l.GetAttributeValue("data-hovercard").Contains("user.php")
      && l.Text != null
    ).ToList();

    var idRegex = new Regex("id=(?<id>([0-9]+))");
    foreach (var link in links)
    {
      string hovercard = link.GetAttributeValue("data-hovercard");
      var match = idRegex.Match(hovercard);
      long id = 0;
      if (match.Success)
      {
        id = long.Parse(match.Groups["id"].Value);
      }
      users.Add(new FacebookUser
      {
        Name = link.Text,
        Id = id
      });
    }
  }
  return users;
}

Prototype with implementation of this approach (using C#/WatiN) see https://github.com/svejdo1/ShadowApi. It is also allowing dynamic update of Facebook connector that is retrieving a list of your contacts.

CSS hover vs. JavaScript mouseover

A very big difference is that ":hover" state is automatically deactivated when the mouse moves out of the element. As a result any styles that are applied on hover are automatically reversed. On the other hand, with the javascript approach, you would have to define both "onmouseover" and "onmouseout" events. If you only define "onmouseover" the styles that are applied "onmouseover" will persist even after you mouse out unless you have explicitly defined "onmouseout".

How do I access command line arguments in Python?

If you call it like this: $ python myfile.py var1 var2 var3

import sys

var1 = sys.argv[1]
var2 = sys.argv[2]
var3 = sys.argv[3]

Similar to arrays you also have sys.argv[0] which is always the current working directory.

Vagrant error : Failed to mount folders in Linux guest

In configuration where windows is a host, and linux is a guest I found solution of the same problem in other place.

So again, the error message was "Failed to mount folders in Linux guest. This is usually because the "vboxsf" file system is not available." (...)

This was caused because I have made mistake by doing symlink inside the guest system from /vagrant into /home/vagrant/vagrant. The point is, that the directory /vagrant is a normal linux directory that has a symlink (so all ok), but when booting up by "vagrant up", it tries to mount windows directory on that place, and windows directory cannot work as a symlink. Windows host does not support linux symlinks.

So what You can do then, is to ssh into guest, remove the symlink wherever You have it, and reload machine.

In my configuration it was: Vagrant 1.7.2, VBoxGuestAdditions 4.3.28 and VBox 4.3.28.

How to encrypt a large file in openssl using public key

You can't directly encrypt a large file using rsautl. instead, do something like the following:

  1. Generate a key using openssl rand, eg. openssl rand 32 -out keyfile
  2. Encrypt the key file using openssl rsautl
  3. Encrypt the data using openssl enc, using the generated key from step 1.
  4. Package the encrypted key file with the encrypted data. the recipient will need to decrypt the key with their private key, then decrypt the data with the resulting key.

Codeigniter $this->db->get(), how do I return values for a specific row?

Incase you are dynamically getting your data e.g When you need data based on the user logged in by their id use consider the following code example for a No Active Record:

 $this->db->query('SELECT * FROM my_users_table WHERE id = ?', $this->session->userdata('id'));

 return $query->row_array();

This will return a specific row based on your the set session data of user.

Email address validation in C# MVC 4 application: with or without using Regex

Don't.

Use a regex for a quick sanity check, something like .@.., but almost all langauges / frameworks have better methods for checking an e-mail address. Use that.

It is possible to validate an e-mail address with a regex, but it is a long regex. Very long.
And in the end you will be none the wiser. You'll only know that the format is valid, but you still don't know if it's an active e-mail address. The only way to find out, is by sending a confirmation e-mail.

How to get single value from this multi-dimensional PHP array

Use array_shift function

$myarray = array_shift($myarray);

This will move array elements one level up and you can access any array element without using [0] key

echo $myarray['email'];  

will show [email protected]

Propagation Delay vs Transmission delay

Because they're measuring different things.

Propagation delay is how long it takes one bit to travel from one end of the "wire" to the other (it's proportional to the length of the wire, crudely).

Transmission delay is how long it takes to get all the bits into the wire in the first place (it's packet_length/data_rate).

Why can't radio buttons be "readonly"?

I found that use onclick='this.checked = false;' worked to a certain extent. A radio button that was clicked would not be selected. However, if there was a radio button that was already selected (e.g., a default value), that radio button would become unselected.

<!-- didn't completely work -->
<input type="radio" name="r1" id="r1" value="N" checked="checked" onclick='this.checked = false;'>N</input>
<input type="radio" name="r1" id="r1" value="Y" onclick='this.checked = false;'>Y</input>

For this scenario, leaving the default value alone and disabling the other radio button(s) preserves the already selected radio button and prevents it from being unselected.

<!-- preserves pre-selected value -->
<input type="radio" name="r1" id="r1" value="N" checked="checked">N</input>
<input type="radio" name="r1" id="r1" value="Y" disabled>Y</input>

This solution is not the most elegant way of preventing the default value from being changed, but it will work whether or not javascript is enabled.

Windows 7, 64 bit, DLL problems

As mentioned, DCOMP is part of the VC++ redistributables (implementing the OpenMP runtime) and is the only truly missing component. All the rest are false reports.

Specifically API-MS-WIN-XXXX.DLL are API-sets - essentially, an extra level of call indirection introduced gradually since Windows 7. Dependency Walker development seemingly halted long before that, and it can't handle API sets properly.

So there is nothing to worry about there. You're not missing anything more.

A better alternative to find the truly needed DLL files that are missing (if that is indeed the problem) is to run Process Monitor and step backwards from the failure, searching for sequences of failed probes for a specific DLL file in all the system path.

How to combine two strings together in PHP?

$result = implode(' ', array($data1, $data2));

is more generic.

Iterating over dictionaries using 'for' loops

This is a very common looping idiom. in is an operator. For when to use for key in dict and when it must be for key in dict.keys() see David Goodger's Idiomatic Python article (archived copy).

How to determine if a number is positive or negative?

This solution uses no conditional operators, but relies on catching two excpetions.

A division error equates to the number originally being "negative". Alternatively, the number will eventually fall off the planet and throw a StackOverFlow exception if it is positive.

public static boolean isPositive( f)
       {
           int x;
           try {
               x = 1/((int)f + 1);
               return isPositive(x+1);
           } catch (StackOverFlow Error e) {
               return true;

           } catch (Zero Division Error e) {
               return false;
           }


   }

Read file-contents into a string in C++

Like this:

#include <fstream>
#include <string>

int main(int argc, char** argv)
{

  std::ifstream ifs("myfile.txt");
  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

  return 0;
}

The statement

  std::string content( (std::istreambuf_iterator<char>(ifs) ),
                       (std::istreambuf_iterator<char>()    ) );

can be split into

std::string content;
content.assign( (std::istreambuf_iterator<char>(ifs) ),
                (std::istreambuf_iterator<char>()    ) );

which is useful if you want to just overwrite the value of an existing std::string variable.

What is meant by immutable?

An immutable object is an object where the internal fields (or at least, all the internal fields that affect its external behavior) cannot be changed.

There are a lot of advantages to immutable strings:

Performance: Take the following operation:

String substring = fullstring.substring(x,y);

The underlying C for the substring() method is probably something like this:

// Assume string is stored like this:
struct String { char* characters; unsigned int length; };

// Passing pointers because Java is pass-by-reference
struct String* substring(struct String* in, unsigned int begin, unsigned int end)
{
    struct String* out = malloc(sizeof(struct String));
    out->characters = in->characters + begin;
    out->length = end - begin;
    return out;
}

Note that none of the characters have to be copied! If the String object were mutable (the characters could change later) then you would have to copy all the characters, otherwise changes to characters in the substring would be reflected in the other string later.

Concurrency: If the internal structure of an immutable object is valid, it will always be valid. There's no chance that different threads can create an invalid state within that object. Hence, immutable objects are Thread Safe.

Garbage collection: It's much easier for the garbage collector to make logical decisions about immutable objects.

However, there are also downsides to immutability:

Performance: Wait, I thought you said performance was an upside of immutability! Well, it is sometimes, but not always. Take the following code:

foo = foo.substring(0,4) + "a" + foo.substring(5);  // foo is a String
bar.replace(4,5,"a"); // bar is a StringBuilder

The two lines both replace the fourth character with the letter "a". Not only is the second piece of code more readable, it's faster. Look at how you would have to do the underlying code for foo. The substrings are easy, but now because there's already a character at space five and something else might be referencing foo, you can't just change it; you have to copy the whole string (of course some of this functionality is abstracted into functions in the real underlying C, but the point here is to show the code that gets executed all in one place).

struct String* concatenate(struct String* first, struct String* second)
{
    struct String* new = malloc(sizeof(struct String));
    new->length = first->length + second->length;

    new->characters = malloc(new->length);

    int i;

    for(i = 0; i < first->length; i++)
        new->characters[i] = first->characters[i];

    for(; i - first->length < second->length; i++)
        new->characters[i] = second->characters[i - first->length];

    return new;
}

// The code that executes
struct String* astring;
char a = 'a';
astring->characters = &a;
astring->length = 1;
foo = concatenate(concatenate(slice(foo,0,4),astring),slice(foo,5,foo->length));

Note that concatenate gets called twice meaning that the entire string has to be looped through! Compare this to the C code for the bar operation:

bar->characters[4] = 'a';

The mutable string operation is obviously much faster.

In Conclusion: In most cases, you want an immutable string. But if you need to do a lot of appending and inserting into a string, you need the mutability for speed. If you want the concurrency safety and garbage collection benefits with it the key is to keep your mutable objects local to a method:

// This will have awful performance if you don't use mutable strings
String join(String[] strings, String separator)
{
    StringBuilder mutable;
    boolean first = true;

    for(int i = 0; i < strings.length; i++)
    {
        if(!first) first = false;
        else mutable.append(separator);

        mutable.append(strings[i]);
    }

    return mutable.toString();
}

Since the mutable object is a local reference, you don't have to worry about concurrency safety (only one thread ever touches it). And since it isn't referenced anywhere else, it is only allocated on the stack, so it is deallocated as soon as the function call is finished (you don't have to worry about garbage collection). And you get all the performance benefits of both mutability and immutability.

How do I call a Django function on button click?

The following answer could be helpful for the first part of your question:

Django: How can I call a view function from template?

In Jinja2, how do you test if a variable is undefined?

In the Environment setup, we had undefined = StrictUndefined, which prevented undefined values from being set to anything. This fixed it:

from jinja2 import Undefined
JINJA2_ENVIRONMENT_OPTIONS = { 'undefined' : Undefined }

List of Timezone IDs for use with FindTimeZoneById() in C#?

You will find complete list of time zone with its GMToffsets here and you can use "Name of Time Zone" column value to find time zone by ID

e.g

TimeZoneInfo objTimeZoneInfo = TimeZoneInfo.FindTimeZoneById("Dateline Standard Time");

You will get time zone info class that contains dateline standard time time zone which is used for GMT-12:00.

How to find all the dependencies of a table in sql server

Query the sysdepends table:

SELECT distinct schema_name(dependentObject.uid) as schema, 
       dependentObject.*
 FROM sysdepends d 
INNER JOIN sysobjects o on d.id = o.id 
INNER JOIN sysobjects dependentObject on d.depid = dependentObject.id
WHERE o.name = 'TableName'

A way to look just for views/functions/triggers/procedures that reference the object (or any given text) by name is:

SELECT distinct schema_name(so.uid) + '.' + so.name 
  FROM syscomments sc 
 INNER JOIN  sysobjects so on sc.id = so.id 
 WHERE sc.text like '%Name%'

Is it possible to capture the stdout from the sh DSL command in the pipeline

You can try to use as well this functions to capture StdErr StdOut and return code.

def runShell(String command){
    def responseCode = sh returnStatus: true, script: "${command} &> tmp.txt" 
    def output =  readFile(file: "tmp.txt")

    if (responseCode != 0){
      println "[ERROR] ${output}"
      throw new Exception("${output}")
    }else{
      return "${output}"
    }
}

Notice:

&>name means 1>name 2>name -- redirect stdout and stderr to the file name

Best way to move files between S3 buckets?

To move/copy from one bucket to another or the same bucket I use s3cmd tool and works fine. For instance:

s3cmd cp --recursive s3://bucket1/directory1 s3://bucket2/directory1
s3cmd mv --recursive s3://bucket1/directory1 s3://bucket2/directory1

Background image jumps when address bar hides iOS/Android/Mobile Chrome

My solution involved a bit of javascript. Keep the 100% or 100vh on the div (this will avoid the div not appearing on initial page load). Then when the page loads, grab the window height and apply it to the element in question. Avoids the jump because now you have a static height on your div.

var $hero = $('#hero-wrapper'),
    h     = window.innerHeight;

$hero.css('height', h);

Rails - Could not find a JavaScript runtime?

sudo apt-get install nodejs does not work for me. In order to get it to work, I have to do the following:

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs

Hope this will help someone having the same problem as me.

Checking version of angular-cli that's installed?

ng version or ng --version or ng v OR ng -v

You can use this 4 commands to check the which version of angular-cli installed in your machine.

Export to CSV via PHP

Works with over 100 lines, if you specify the size of the file in the headers simple call the get() method in your own class

function setHeader($filename, $filesize)
{
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 01 Jan 2001 00:00:01 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download  
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");
    header('Content-Type: text/x-csv');

    // disposition / encoding on response body
    if (isset($filename) && strlen($filename) > 0)
        header("Content-Disposition: attachment;filename={$filename}");
    if (isset($filesize))
        header("Content-Length: ".$filesize);
    header("Content-Transfer-Encoding: binary");
    header("Connection: close");
}

function getSql()
{
    // return you own sql
    $sql = "SELECT id, date, params, value FROM sometable ORDER BY date;";
    return $sql;
}

function getExportData()
{
    $values = array();

    $sql = $this->getSql();
    if (strlen($sql) > 0)
    {
        $result = dbquery($sql); // opens the database and executes the sql ... make your own ;-) 
        $fromDb = mysql_fetch_assoc($result);
        if ($fromDb !== false)
        {
            while ($fromDb)
            {
                $values[] = $fromDb;
                $fromDb = mysql_fetch_assoc($result);
            }
        }
    }
    return $values;
}

function get()
{
    $values = $this->getExportData(); // values as array 
    $csv = tmpfile();

    $bFirstRowHeader = true;
    foreach ($values as $row) 
    {
        if ($bFirstRowHeader)
        {
            fputcsv($csv, array_keys($row));
            $bFirstRowHeader = false;
        }

        fputcsv($csv, array_values($row));
    }

    rewind($csv);

    $filename = "export_".date("Y-m-d").".csv";

    $fstat = fstat($csv);
    $this->setHeader($filename, $fstat['size']);

    fpassthru($csv);
    fclose($csv);
}

Why use the 'ref' keyword when passing an object?

Ref denotes whether the function can get its hands on the object itself, or only on its value.

Passing by reference is not bound to a language; it's a parameter binding strategy next to pass-by-value, pass by name, pass by need etc...

A sidenote: the class name TestRef is a hideously bad choice in this context ;).

Annotations from javax.validation.constraints not working

In my case, I was using spring boot version 2.3.0. When I changed my maven dependency to use 2.1.3 it worked.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.3.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<dependencies>
    <dependency>
        <groupId>javax.validation</groupId>
        <artifactId>validation-api</artifactId>
    </dependency>
</dependencies>

Heroku deployment error H10 (App crashed)

Be very cautious of copy and pasting code. Sometimes when you add a block into a file, it is formatted incorrectly and will yield an error.

I've had this problem before and got this error: unexpected tIDENTIFIER, expecting keyword_end

Convert JSON to Map

Using the GSON library:

import com.google.gson.Gson;
import com.google.common.reflect.TypeToken;
import java.lang.reclect.Type;

Use the following code:

Type mapType = new TypeToken<Map<String, Map>>(){}.getType();  
Map<String, String[]> son = new Gson().fromJson(easyString, mapType);

How to add a new column to an existing sheet and name it?

For your question as asked

Columns(3).Insert
Range("c1:c4") = Application.Transpose(Array("Loc", "uk", "us", "nj"))

If you had a way of automatically looking up the data (ie matching uk against employer id) then you could do that in VBA

How do I call a specific Java method on a click/submit event of a specific button in JSP?

Just give the individual button elements a unique name. When pressed, the button's name is available as a request parameter the usual way like as with input elements.

You only need to make sure that the button inputs have type="submit" as in <input type="submit"> and <button type="submit"> and not type="button", which only renders a "dead" button purely for onclick stuff and all.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <input type="submit" name="button1" value="Button 1" />
    <input type="submit" name="button2" value="Button 2" />
    <input type="submit" name="button3" value="Button 3" />
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();

        if (request.getParameter("button1") != null) {
            myClass.method1();
        } else if (request.getParameter("button2") != null) {
            myClass.method2();
        } else if (request.getParameter("button3") != null) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

Alternatively, use <button type="submit"> instead of <input type="submit">, then you can give them all the same name, but an unique value. The value of the <button> won't be used as label, you can just specify that yourself as child.

E.g.

<form action="${pageContext.request.contextPath}/myservlet" method="post">
    <button type="submit" name="button" value="button1">Button 1</button>
    <button type="submit" name="button" value="button2">Button 2</button>
    <button type="submit" name="button" value="button3">Button 3</button>
</form>

with

@WebServlet("/myservlet")
public class MyServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        MyClass myClass = new MyClass();
        String button = request.getParameter("button");

        if ("button1".equals(button)) {
            myClass.method1();
        } else if ("button2".equals(button)) {
            myClass.method2();
        } else if ("button3".equals(button)) {
            myClass.method3();
        } else {
            // ???
        }

        request.getRequestDispatcher("/WEB-INF/some-result.jsp").forward(request, response);
    }

}

See also:

Is it possible to simulate key press events programmatically?

just use CustomEvent

Node.prototype.fire=function(type,options){
     var event=new CustomEvent(type);
     for(var p in options){
         event[p]=options[p];
     }
     this.dispatchEvent(event);
}

4 ex want to simulate ctrl+z

window.addEventListener("keyup",function(ev){
     if(ev.ctrlKey && ev.keyCode === 90) console.log(ev); // or do smth
     })

 document.fire("keyup",{ctrlKey:true,keyCode:90,bubbles:true})

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

How can I download a specific Maven artifact in one command line?

one liner to download latest maven artifact without mvn:

curl -O -J -L  "https://repository.sonatype.org/service/local/artifact/maven/content?r=central-proxy&g=io.staticcdn.sdk&a=staticcdn-sdk-standalone-optimizer&e=zip&v=LATEST"

Find unused npm packages in package.json

As other answer mentioned depcheck is good for check unused dependecies in your porject. Use npm outdated command to check the outdated library.

enter image description here

Setting the zoom level for a MKMapView

I hope following code fragment would help you.

- (void)handleZoomOutAction:(id)sender {
    MKCoordinateRegion newRegion=MKCoordinateRegionMake(mapView.region.center,MKCoordinateSpanMake(mapView.region.s       pan.latitudeDelta/0.5, mapView.region.span.longitudeDelta/0.5));
    [mapView setRegion:newRegion];
}


- (void)handleZoomInAction:(id)sender {
    MKCoordinateRegion newRegion=MKCoordinateRegionMake(mapView.region.center,MKCoordinateSpanMake(mapView.region.span.latitudeDelta*0.5, mapView.region.span.longitudeDelta*0.5));
    [mapView setRegion:newRegion];
}

You can choose any value in stead of 0.5 to reduce or increase zoom level. I have used these methods on click of two buttons.

How to get the Development/Staging/production Hosting Environment in ConfigureServices

If you need to test this somewhere in your codebase that doesn't have easy access to the IHostingEnvironment, another easy way to do it is like this:

bool isDevelopment = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") == "Development";

creating array without declaring the size - java

Once the array size is fixed while running the program ,it's size can't be changed further. So better go for ArrayList while dealing with dynamic arrays.

How does one target IE7 and IE8 with valid CSS?

The answer to your question

A completely valid way to select all browsers but IE8 and below is using the :root selector. Since IE versions 8 and below do not support :root, selectors containing it are ignored. This means you could do something like this:

p {color:red;}
:root p {color:blue;}

This is still completely valid CSS, but it does cause IE8 and lower to render different styles.

Other tricks

Here's a list of all completely valid CSS browser-specific selectors I could find, except for some that seem quite redundant, such as ones that select for just 1 type of ancient browser (1, 2):

/******  First the hacks that target certain specific browsers  ******/
* html p                        {color:red;} /* IE 6- */
*+html p                        {color:red;} /* IE 7 only */
@media screen and (-webkit-min-device-pixel-ratio:0) {
    p                           {color:red;}
}                                            /* Chrome, Safari 3+ */
p, body:-moz-any-link           {color:red;} /* Firefox 1+ */
:-webkit-any(html) p            {color:red;} /* Chrome 12+, Safari 5.1.3+ */
:-moz-any(html) p               {color:red;} /* Firefox 4+ */

/****** And then the hacks that target all but certain browsers ******/
html> body p                  {color:green;} /* not: IE<7 */
head~body p                   {color:green;} /* not: IE<7, Opera<9, Safari<3 */
html:first-child p            {color:green;} /* not: IE<7, Opera<9.5, Safari&Chrome<4, FF<3 */
html>/**/body p               {color:green;} /* not: IE<8 */
body:first-of-type p          {color:green;} /* not: IE<9, Opera<9, Safari<3, FF<3.5 */
:not([ie8min]) p              {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */
body:not([oldbrowser]) p      {color:green;} /* not: IE<9, Opera<9.5, Safari<3.2 */

Credits & sources:

Store mysql query output into a shell variable

myvariable=$(mysql database -u $user -p$password | SELECT A, B, C FROM table_a)

without the blank space after -p. Its trivial, but without don't work.

How to get rows count of internal table in abap?

data: vcnt(4).

clear vcnt.

LOOP at itab WHERE value = '1'.
  add 1 to vcnt.
ENDLOOP.

The answer will be 3. (vcnt = 3).

How can I use numpy.correlate to do autocorrelation?

Auto-correlation comes in two versions: statistical and convolution. They both do the same, except for a little detail: The statistical version is normalized to be on the interval [-1,1]. Here is an example of how you do the statistical one:

def acf(x, length=20):
    return numpy.array([1]+[numpy.corrcoef(x[:-i], x[i:])[0,1]  \
        for i in range(1, length)])

Getting content/message from HttpResponseMessage

The quick answer I suggest is:

response.Result.Content.ReadAsStringAsync().Result

Escape a string in SQL Server so that it is safe to use in LIKE expression

To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)

For example this escapes the % symbol, using \ as the escape char:

select * from table where myfield like '%15\% off%' ESCAPE '\'

If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:

set @myString = replace( 
                replace( 
                replace( 
                replace( @myString
                ,    '\', '\\' )
                ,    '%', '\%' )
                ,    '_', '\_' )
                ,    '[', '\[' )

(Note that you have to escape your escape char too, and make sure that's the inner replace so you don't escape the ones added from the other replace statements). Then you can use something like this:

select * from table where myfield like '%' + @myString + '%' ESCAPE '\'

Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.

Recursive directory listing in DOS

You can use:

dir /s

If you need the list without all the header/footer information try this:

dir /s /b

(For sure this will work for DOS 6 and later; might have worked prior to that, but I can't recall.)

How do I prevent Eclipse from hanging on startup?

I just had problems with Eclipse starting up. It was fixed by deleting this file:

rm org.eclipse.core.resources.prefs

I found in .settings

not-null property references a null or transient value

I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)

how to download file in react js

React gives a security issue when using a tag with target="_blank".

I managed to get it working like that:

<a href={uploadedFileLink} target="_blank" rel="noopener noreferrer" download>
   <Button>
      <i className="fas fa-download"/>
      Download File
   </Button>
</a>

How to strip all whitespace from string

Taking advantage of str.split's behavior with no sep parameter:

>>> s = " \t foo \n bar "
>>> "".join(s.split())
'foobar'

If you just want to remove spaces instead of all whitespace:

>>> s.replace(" ", "")
'\tfoo\nbar'

Premature optimization

Even though efficiency isn't the primary goal—writing clear code is—here are some initial timings:

$ python -m timeit '"".join(" \t foo \n bar ".split())'
1000000 loops, best of 3: 1.38 usec per loop
$ python -m timeit -s 'import re' 're.sub(r"\s+", "", " \t foo \n bar ")'
100000 loops, best of 3: 15.6 usec per loop

Note the regex is cached, so it's not as slow as you'd imagine. Compiling it beforehand helps some, but would only matter in practice if you call this many times:

$ python -m timeit -s 'import re; e = re.compile(r"\s+")' 'e.sub("", " \t foo \n bar ")'
100000 loops, best of 3: 7.76 usec per loop

Even though re.sub is 11.3x slower, remember your bottlenecks are assuredly elsewhere. Most programs would not notice the difference between any of these 3 choices.

Importing data from a JSON file into R

First install the RJSONIO and RCurl package:

_x000D_
_x000D_
install.packages("RJSONIO")_x000D_
install.packages("(RCurl")
_x000D_
_x000D_
_x000D_

Try below code using RJSONIO in console

_x000D_
_x000D_
library(RJSONIO)_x000D_
library(RCurl)_x000D_
json_file = getURL("https://raw.githubusercontent.com/isrini/SI_IS607/master/books.json")_x000D_
json_file2 = RJSONIO::fromJSON(json_file)_x000D_
head(json_file2)
_x000D_
_x000D_
_x000D_

Count number of times value appears in particular column in MySQL

select email, count(*) as c FROM orders GROUP BY email

Binding a WPF ComboBox to a custom list

You set the DisplayMemberPath and the SelectedValuePath to "Name", so I assume that you have a class PhoneBookEntry with a public property Name.

Have you set the DataContext to your ConnectionViewModel object?

I copied you code and made some minor modifications, and it seems to work fine. I can set the viewmodels PhoneBookEnty property and the selected item in the combobox changes, and I can change the selected item in the combobox and the view models PhoneBookEntry property is set correctly.

Here is my XAML content:

<Window x:Class="WpfApplication6.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
<Grid>
    <StackPanel>
        <Button Click="Button_Click">asdf</Button>
        <ComboBox ItemsSource="{Binding Path=PhonebookEntries}"
                  DisplayMemberPath="Name"
                  SelectedValuePath="Name"
                  SelectedValue="{Binding Path=PhonebookEntry}" />
    </StackPanel>
</Grid>
</Window>

And here is my code-behind:

namespace WpfApplication6
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>
    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
            ConnectionViewModel vm = new ConnectionViewModel();
            DataContext = vm;
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            ((ConnectionViewModel)DataContext).PhonebookEntry = "test";
        }
    }

    public class PhoneBookEntry
    {
        public string Name { get; set; }

        public PhoneBookEntry(string name)
        {
            Name = name;
        }

        public override string ToString()
        {
            return Name;
        }
    }

    public class ConnectionViewModel : INotifyPropertyChanged
    {
        public ConnectionViewModel()
        {
            IList<PhoneBookEntry> list = new List<PhoneBookEntry>();
            list.Add(new PhoneBookEntry("test"));
            list.Add(new PhoneBookEntry("test2"));
            _phonebookEntries = new CollectionView(list);
        }

        private readonly CollectionView _phonebookEntries;
        private string _phonebookEntry;

        public CollectionView PhonebookEntries
        {
            get { return _phonebookEntries; }
        }

        public string PhonebookEntry
        {
            get { return _phonebookEntry; }
            set
            {
                if (_phonebookEntry == value) return;
                _phonebookEntry = value;
                OnPropertyChanged("PhonebookEntry");
            }
        }

        private void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Edit: Geoffs second example does not seem to work, which seems a bit odd to me. If I change the PhonebookEntries property on the ConnectionViewModel to be of type ReadOnlyCollection, the TwoWay binding of the SelectedValue property on the combobox works fine.

Maybe there is an issue with the CollectionView? I noticed a warning in the output console:

System.Windows.Data Warning: 50 : Using CollectionView directly is not fully supported. The basic features work, although with some inefficiencies, but advanced features may encounter known bugs. Consider using a derived class to avoid these problems.

Edit2 (.NET 4.5): The content of the DropDownList can be based on ToString() and not of DisplayMemberPath, while DisplayMemberPath specifies the member for the selected and displayed item only.

Reading/writing an INI file

This article on CodeProject "An INI file handling class using C#" should help.

The author created a C# class "Ini" which exposes two functions from KERNEL32.dll. These functions are: WritePrivateProfileString and GetPrivateProfileString. You will need two namespaces: System.Runtime.InteropServices and System.Text.

Steps to use the Ini class

In your project namespace definition add

using INI;

Create a INIFile like this

INIFile ini = new INIFile("C:\\test.ini");

Use IniWriteValue to write a new value to a specific key in a section or use IniReadValue to read a value FROM a key in a specific Section.

Note: if you're beginning from scratch, you could read this MSDN article: How to: Add Application Configuration Files to C# Projects. It's a better way for configuring your application.

Using jQuery to see if a div has a child with a certain class

You can use the find function:

if($('#popup').find('p.filled-text').length !== 0)
   // Do Stuff

java doesn't run if structure inside of onclick listener

both your conditions are the same:

if(s < f) {     calc = f - s;     n = s; }else if(f > s){     calc =  s - f;     n = f;  } 

so

if(s < f)   

and

}else if(f > s){ 

are the same

change to

}else if(f < s){ 

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

^([2][0]\d{2}\/([0]\d|[1][0-2])\/([0-2]\d|[3][0-1]))$|^([2][0]\d{2}\/([0]\d|[1][0-2])\/([0-2]\d|[3][0-1])\s([0-1]\d|[2][0-3])\:[0-5]\d\:[0-5]\d)$

Getting value from JQUERY datepicker

I needed to do this for a sales report that allows the user to choose a date range. The solution is similar to another answer, but I wanted to provide my example just to show you the practical real world use that I applied this to:

var reportHeader = `Product Sales History Report for ${$('#FromDate').val()} to ${$('#ToDate').val()}.` ;
```

How to add images in select list?

For a two color image, you can use Fontello, and import any custom glyph you want to use. Just make your image in Illustrator, save to SVG, and drop it onto the Fontello site, then download your custom font ready to import. No JavaScript!

"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

From find manual:

NON-BUGS         

   Operator precedence surprises
   The command find . -name afile -o -name bfile -print will never print
   afile because this is actually equivalent to find . -name afile -o \(
   -name bfile -a -print \).  Remember that the precedence of -a is
   higher than that of -o and when there is no operator specified
   between tests, -a is assumed.

   “paths must precede expression” error message
   $ find . -name *.c -print
   find: paths must precede expression
   Usage: find [-H] [-L] [-P] [-Olevel] [-D ... [path...] [expression]

   This happens because *.c has been expanded by the shell resulting in
   find actually receiving a command line like this:
   find . -name frcode.c locate.c word_io.c -print
   That command is of course not going to work.  Instead of doing things
   this way, you should enclose the pattern in quotes or escape the
   wildcard:
   $ find . -name '*.c' -print
   $ find . -name \*.c -print

VueJs get url query

You can also get them with pure javascript.

For example:

new URL(location.href).searchParams.get('page')

For this url: websitename.com/user/?page=1, it would return a value of 1

iPhone X / 8 / 8 Plus CSS media queries

It seems that the most accurate (and seamless) method of adding the padding for iPhone X/8 using env()...

padding: env(safe-area-inset-top) env(safe-area-inset-right) env(safe-area-inset-bottom) env(safe-area-inset-left);

Here's a link describing this:

https://css-tricks.com/the-notch-and-css/

Using async/await with a forEach loop

Instead of Promise.all in conjunction with Array.prototype.map (which does not guarantee the order in which the Promises are resolved), I use Array.prototype.reduce, starting with a resolved Promise:

async function printFiles () {
  const files = await getFilePaths();

  await files.reduce(async (promise, file) => {
    // This line will wait for the last async function to finish.
    // The first iteration uses an already resolved Promise
    // so, it will immediately continue.
    await promise;
    const contents = await fs.readFile(file, 'utf8');
    console.log(contents);
  }, Promise.resolve());
}

Add a reference column migration in Rails 4

[Using Rails 5]

Generate migration:

rails generate migration add_user_reference_to_uploads user:references

This will create the migration file:

class AddUserReferenceToUploads < ActiveRecord::Migration[5.1]
  def change
    add_reference :uploads, :user, foreign_key: true
  end
end

Now if you observe the schema file, you will see that the uploads table contains a new field. Something like: t.bigint "user_id" or t.integer "user_id".

Migrate database:

rails db:migrate

test attribute in JSTL <c:if> tag

<%=%> by itself will be sent to the output, in the context of the JSTL it will be evaluated to a string

std::enable_if to conditionally compile a member function

The boolean needs to depend on the template parameter being deduced. So an easy way to fix is to use a default boolean parameter:

template< class T >
class Y {

    public:
        template < bool EnableBool = true, typename = typename std::enable_if<( std::is_same<T, double>::value && EnableBool )>::type >
        T foo() {
            return 10;
        }

};

However, this won't work if you want to overload the member function. Instead, its best to use TICK_MEMBER_REQUIRES from the Tick library:

template< class T >
class Y {

    public:
        TICK_MEMBER_REQUIRES(std::is_same<T, double>::value)
        T foo() {
            return 10;
        }

        TICK_MEMBER_REQUIRES(!std::is_same<T, double>::value)
        T foo() {
            return 10;
        }

};

You can also implement your own member requires macro like this(just in case you don't want to use another library):

template<long N>
struct requires_enum
{
    enum class type
    {
        none,
        all       
    };
};


#define MEMBER_REQUIRES(...) \
typename requires_enum<__LINE__>::type PrivateRequiresEnum ## __LINE__ = requires_enum<__LINE__>::type::none, \
class=typename std::enable_if<((PrivateRequiresEnum ## __LINE__ == requires_enum<__LINE__>::type::none) && (__VA_ARGS__))>::type

Using Ansible set_fact to create a dictionary from register results

I think I got there in the end.

The task is like this:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
  with_items: "{{ people.results }}"

It loops through each of the dicts (item) in the people.results array, each time creating a new dict like {Bob: "male"}, and combine()s that new dict in the genders array, which ends up like:

{
    "Bob": "male",
    "Thelma": "female"
}

It assumes the keys (the name in this case) will be unique.


I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items:

- name: Populate genders
  set_fact:
    genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
  with_items: "{{ people.results }}"

This keeps combining the existing list with a list containing a single dict. We end up with a genders array like this:

[
    {'name': 'Bob', 'gender': 'male'},
    {'name': 'Thelma', 'gender': 'female'}
]

rand() returns the same number each time the program is run

For what its worth you are also only generating numbers between 0 and 99 (inclusive). If you wanted to generate values between 0 and 100 you would need.

rand() % 101

in addition to calling srand() as mentioned by others.

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties

I have the same issue with Entity Framework 6.1.3

But with different scenario. My model property is of type nullable DateTime

DateTime? CreatedDate { get; set; }

So I need to query on today's date to check all the record, so this what works for me. Which means I need to truncate both records to get the proper query on DbContext:

Where(w => DbFunctions.TruncateTime(w.CreatedDate) == DbFunctions.TruncateTime(DateTime.Now);

nginx: how to create an alias url route?

server {
  server_name example.com;
  root /path/to/root;
  location / {
    # bla bla
  }
  location /demo {
    alias /path/to/root/production/folder/here;
  }
}

If you need to use try_files inside /demo you'll need to replace alias with a root and do a rewrite because of the bug explained here

Find something in column A then show the value of B for that row in Excel 2010

I note you suggested this formula

=IF(ISNUMBER(FIND("RuhrP";F9));LOOKUP(A9;Ruhrpumpen!A$5:A$100;Ruhrpumpen!I$5:I$100);"")

.....but LOOKUP isn't appropriate here because I assume you want an exact match (LOOKUP won't guarantee that and also data in lookup range has to be sorted), so VLOOKUP or INDEX/MATCH would be better....and you can also use IFERROR to avoid the IF function, i.e

=IFERROR(VLOOKUP(A9;Ruhrpumpen!A$5:Z$100;9;0);"")

Note: VLOOKUP always looks up the lookup value (A9) in the first column of the "table array" and returns a value from the nth column of the "table array" where n is defined by col_index_num, in this case 9

INDEX/MATCH is sometimes more flexible because you can explicitly define the lookup column and the return column (and return column can be to the left of the lookup column which can't be the case in VLOOKUP), so that would look like this:

=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH(A9;Ruhrpumpen!A$5:A$100;0));"")

INDEX/MATCH also allows you to more easily return multiple values from different columns, e.g. by using $ signs in front of A9 and the lookup range Ruhrpumpen!A$5:A$100, i.e.

=IFERROR(INDEX(Ruhrpumpen!I$5:I$100;MATCH($A9;Ruhrpumpen!$A$5:$A$100;0));"")

this version can be dragged across to get successive values from column I, column J, column K etc.....

How to check certificate name and alias in keystore files?

In order to get all the details I had to add the -v option to romaintaz answer:

keytool -v -list -keystore <FileName>.keystore

How to recursively list all the files in a directory in C#?

Here is a version of B. Clay Shannon's code not static for excel-files:

class ExcelSearcher
{
    private List<string> _fileNames;

    public ExcelSearcher(List<string> filenames)
    {
        _fileNames = filenames;
    }
    public List<string> GetExcelFiles(string dir, List<string> filenames = null)
    {

        string dirName = dir;
        var dirNames = new List<string>();
        if (filenames != null)
        {
            _fileNames.Concat(filenames);
        }
        try
        {
            foreach (string f in Directory.GetFiles(dirName))
            {
                if (f.ToLower().EndsWith(".xls") || f.ToLower().EndsWith(".xlsx"))
                {
                    _fileNames.Add(f);
                }
            }
            dirNames = Directory.GetDirectories(dirName).ToList();
            foreach (string d in dirNames)
            {
                GetExcelFiles(d, _fileNames);
            }
        }
        catch (Exception ex)
        {
            //Bam
        }
        return _fileNames;
    }

How to trigger an event after using event.preventDefault()

Override the property isDefaultPrevented like this:

$('a').click(function(evt){
  evt.preventDefault();

  // in async handler (ajax/timer) do these actions:
  setTimeout(function(){
    // override prevented flag to prevent jquery from discarding event
    evt.isDefaultPrevented = function(){ return false; }
    // retrigger with the exactly same event data
    $(this).trigger(evt);
  }, 1000);
}

IMHO, this is most complete way of retriggering the event with the exactly same data.

Uninstalling an MSI file from the command line without using msiexec

wmic product get name

Just gets the cmd stuck... still flashing _ after a couple minutes

in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall, if you can find the folder with the software name you are trying to install (not the one named with ProductCode), the UninstallString points to the application's own uninstaller C:\Program Files\Zune\ZuneSetup.exe /x

Custom date format with jQuery validation plugin

nickf's answer is good, but note that the validation plug-in already includes validators for several other date formats, in the additional-methods.js file. Before you write your own, make sure that someone hasn't already done it.

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

I get the same question as you you can click here :

About the question in xcode5 "no matching provisioning profiles found"

(About xcode5 ?no matching provisioning profiles found )

When I was fitting with iOS7,I get the warning like this:no matching provisioning profiles found. the reason may be that your project is in other group.

Do like this:find the file named *.xcodeproj in your protect,show the content of it.

You will see three files:

  1. project.pbxproj
  2. project.xcworkspace
  3. xcuserdata

open the first, search the uuid and delete the row.

How to exit an application properly

Application.Exit() does the trick too: any forms you have can still cancel this for instance if you want to present a save changes dialog.

git with IntelliJ IDEA: Could not read from remote repository

This fixed it for me (I am using SSH, not HTTPS, and the native git, not the built-in) on MacOS High Sierra (10.13.5)/IntelliJ IDEA 2018.4:

File -> Invalidate Caches and Restart

Xcode 10: A valid provisioning profile for this executable was not found

Today I had the same error while installing an app to my device. The problem occurred after I updated to the new xCode 11.4.

What I did to fix the issue:

  • Unpaired device (Xcode > Window > Devices And Simulators > Left click device to unpair device.
  • Restart iPhone
  • Clean Build Folder (Xcode > Product > Clean Build Folder)
  • Clean Derived Data (in ../library/Developer/Xcode/DerivedData)
  • Clean Build Folder again (Xcode > Product > Clean Build Folder)
  • Build app on device.

What's the difference between size_t and int in C++?

size_t is the type used to represent sizes (as its names implies). Its platform (and even potentially implementation) dependent, and should be used only for this purpose. Obviously, representing a size, size_t is unsigned. Many stdlib functions, including malloc, sizeof and various string operation functions use size_t as a datatype.

An int is signed by default, and even though its size is also platform dependant, it will be a fixed 32bits on most modern machine (and though size_t is 64 bits on 64-bits architecture, int remain 32bits long on those architectures).

To summarize : use size_t to represent the size of an object and int (or long) in other cases.

Easy way of running the same junit test over and over?

This works much easier for me.

public class RepeatTests extends TestCase {

    public static Test suite() {
        TestSuite suite = new TestSuite(RepeatTests.class.getName());

        for (int i = 0; i < 10; i++) {              
        suite.addTestSuite(YourTest.class);             
        }

        return suite;
    }
}

Out-File -append in Powershell does not produce a new line and breaks string into characters

Add-Content is default ASCII and add new line however Add-Content brings locked files issues too.

How to send email from SQL Server?

Step 1) Create Profile and Account

You need to create a profile and account using the Configure Database Mail Wizard which can be accessed from the Configure Database Mail context menu of the Database Mail node in Management Node. This wizard is used to manage accounts, profiles, and Database Mail global settings.

Step 2)

RUN:

sp_CONFIGURE 'show advanced', 1
GO
RECONFIGURE
GO
sp_CONFIGURE 'Database Mail XPs', 1
GO
RECONFIGURE
GO

Step 3)

USE msdb
GO
EXEC sp_send_dbmail @profile_name='yourprofilename',
@recipients='[email protected]',
@subject='Test message',
@body='This is the body of the test message.
Congrates Database Mail Received By you Successfully.'

To loop through the table

DECLARE @email_id NVARCHAR(450), @id BIGINT, @max_id BIGINT, @query NVARCHAR(1000)

SELECT @id=MIN(id), @max_id=MAX(id) FROM [email_adresses]

WHILE @id<=@max_id
BEGIN
    SELECT @email_id=email_id 
    FROM [email_adresses]

    set @query='sp_send_dbmail @profile_name=''yourprofilename'',
                        @recipients='''+@email_id+''',
                        @subject=''Test message'',
                        @body=''This is the body of the test message.
                        Congrates Database Mail Received By you Successfully.'''

    EXEC @query
    SELECT @id=MIN(id) FROM [email_adresses] where id>@id

END

Posted this on the following link http://ms-sql-queries.blogspot.in/2012/12/how-to-send-email-from-sql-server.html

What does -save-dev mean in npm install grunt --save-dev

--save-dev: Package will appear in your devDependencies.

According to the npm install docs.

If someone is planning on downloading and using your module in their program, then they probably don't want or need to download and build the external test or documentation framework that you use.

In other words, when you run npm install, your project's devDependencies will be installed, but the devDependencies for any packages that your app depends on will not be installed; further, other apps having your app as a dependency need not install your devDependencies. Such modules should only be needed when developing the app (eg grunt, mocha etc).

According to the package.json docs

Edit: Attempt at visualising what npm install does:

  • yourproject
    • dependency installed
      • dependency installed
        • dependency installed
        • devDependency NOT installed
      • devDependency NOT installed
    • devDependency installed
      • dependency installed
      • devDependency NOT installed

How to iterate over associative arrays in Bash

Welcome to input associative array 2.0!

    clear
    echo "Welcome to input associative array 2.0! (Spaces in keys and values now supported)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            echo -n "(pair $(( $i+1 )))"
            read -p ' Enter key: ' k
            read -p '         Enter value: ' v
            echo " "
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in "${!array[@]}"; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array 2.0!"

Output:

Welcome to input associative array 2.0! (Spaces in keys and values now supported)
Enter number for array size: 4
(pair 1) Enter key: Key Number 1
         Enter value: Value#1

(pair 2) Enter key: Key Two
         Enter value: Value2

(pair 3) Enter key: Key3
         Enter value: Val3

(pair 4) Enter key: Key4
         Enter value: Value4


The keys are:  Key4 Key3 Key Number 1 Key Two
The values are:  Value4 Val3 Value#1 Value2

Key <-> Value
-------------
Key4 <-> Value4
Key3 <-> Val3
Key Number 1 <-> Value#1
Key Two <-> Value2

Thanks for using input associative array 2.0!

Input associative array 1.0

(keys and values that contain spaces are not supported)

    clear
    echo "Welcome to input associative array! (written by mO extraordinaire!)"
    unset array
    declare -A array
    read -p 'Enter number for array size: ' num
    for (( i=0; i < num; i++ ))
        do
            read -p 'Enter key and value separated by a space: ' k v
            array[$k]=$v
        done
    echo " "
    echo "The keys are: " ${!array[@]}
    echo "The values are: " ${array[@]}
    echo " "
    echo "Key <-> Value"
    echo "-------------"
    for i in ${!array[@]}; do echo $i "<->" ${array[$i]}; done
    echo " "
    echo "Thanks for using input associative array!"

Output:

Welcome to input associative array! (written by mO extraordinaire!)
Enter number for array size: 10
Enter key and value separated by a space: a1 10
Enter key and value separated by a space: b2 20
Enter key and value separated by a space: c3 30
Enter key and value separated by a space: d4 40
Enter key and value separated by a space: e5 50
Enter key and value separated by a space: f6 60
Enter key and value separated by a space: g7 70
Enter key and value separated by a space: h8 80
Enter key and value separated by a space: i9 90
Enter key and value separated by a space: j10 100

The keys are:  h8 a1 j10 g7 f6 e5 d4 c3 i9 b2
The values are:  80 10 100 70 60 50 40 30 90 20

Key <-> Value
-------------
h8 <-> 80
a1 <-> 10
j10 <-> 100
g7 <-> 70
f6 <-> 60
e5 <-> 50
d4 <-> 40
c3 <-> 30
i9 <-> 90
b2 <-> 20

Thanks for using input associative array!

Visual Studio 2015 installer hangs during install?

Check if your Windows has pending updates. After the restart, installation worked as expected.

Add padding to HTML text input field

HTML

<div class="FieldElement"><input /></div>
<div class="searchIcon"><input type="submit" /></div>

For Other Browsers:

.FieldElement input {
width: 413px;
border:1px solid #ccc;
padding: 0 2.5em 0 0.5em;
}

.searchIcon
{
 background: url(searchicon-image-path) no-repeat;
 width: 17px;
 height: 17px;
 text-indent: -999em;
 display: inline-block;
 left: 432px;
 top: 9px;
}

For IE:

.FieldElement input {
width: 380px;
border:0;
}

.FieldElement {
 border:1px solid #ccc;
 width: 455px;     
 }

.searchIcon
{
 background: url(searchicon-image-path) no-repeat;
 width: 17px;
 height: 17px;
 text-indent: -999em;
 display: inline-block;
 left: 432px;
 top: 9px;
}

What does the 'b' character do in front of a string literal?

The b denotes a byte string.

Bytes are the actual data. Strings are an abstraction.

If you had multi-character string object and you took a single character, it would be a string, and it might be more than 1 byte in size depending on encoding.

If took 1 byte with a byte string, you'd get a single 8-bit value from 0-255 and it might not represent a complete character if those characters due to encoding were > 1 byte.

TBH I'd use strings unless I had some specific low level reason to use bytes.

Getting java.net.SocketTimeoutException: Connection timed out in android

Set This in OkHttpClient.Builder() Object

val httpClient = OkHttpClient.Builder()
        httpClient.connectTimeout(5, TimeUnit.MINUTES) // connect timeout
            .writeTimeout(5, TimeUnit.MINUTES) // write timeout
            .readTimeout(5, TimeUnit.MINUTES) // read timeout

How to install mscomct2.ocx file from .cab file (Excel User Form and VBA)

You're correct that this is really painful to hand out to others, but if you have to, this is how you do it.

  1. Just extract the .ocx file from the .cab file (it is similar to a zip)
  2. Copy to the system folder (c:\windows\sysWOW64 for 64 bit systems and c:\windows\system32 for 32 bit)
  3. Use regsvr32 through the command prompt to register the file (e.g. "regsvr32 c:\windows\sysWOW64\mscomct2.ocx")

References

Angularjs: Get element in controller

You can pass in the element to the controller, just like the scope:

function someControllerFunc($scope, $element){

}

How to auto-indent code in the Atom editor?

I found the option in the menu, under Edit > Lines > Auto Indent. It doesn't seem to have a default keymap bound.

You could try to add a key mapping (Atom > Open Your Keymap [on Windows: File > Settings > Keybindings > "your keymap file"]) like this one:

'atom-text-editor':
  'cmd-alt-l': 'editor:auto-indent'

It worked for me :)


For Windows:

'atom-text-editor':
  'ctrl-alt-l': 'editor:auto-indent'

Accessing localhost:port from Android emulator

localhost seemed to be working fine in my emulator at start and then i started getting connection refused exception i used 127.0.2.2 from the emulator browser and it worked and when i used this in my android app in emulator it again started showing the connection refused problem.

then i did ifconfig and i used the ip 192.168.2.2 and it worked perfectly

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

There is another way:

  1. Open up CMD (as Administrator)
  2. Type: mklink /J C:\Program-Files "C:\Program Files" (Or in my case mklink /J C:\Program-Files-(x86) "C:\Program Files (x86)")
  3. Hit enter
  4. Magic happens! (Check your C drive)

Now you can point to C:\Program-Files (C:\Program-Files-(x86)).

How to connect Robomongo to MongoDB

I was able to connect Robomongo to a remote instance of MongoDB running on Mongo Labs using the connection string as follows:

  1. Download the latest version of Robomongo. I downloaded 0.9 RC6 from here.

  2. From the connection string, populate the server address and port numbers as follows.

    Connection settings

  3. Populate DB name and username and password as follows under the authentication tab.

    Authentication settings

  4. Test the connection.

    Test connection

    Enter image description here

Best practices for SQL varchar column length

Whenever I set up a new SQL table I feel the same way about 2^n being more "even"... but to sum up the answers here, there is no significant impact on storage space simply by defining varchar(2^n) or even varchar(MAX).

That said, you should still anticipate the potential implications on storage and performance when setting a high varchar() limit. For example, let's say you create a varchar(MAX) column to hold product descriptions with full-text indexing. If 99% of descriptions are only 500 characters long, and then suddenly you get somebody who replaces said descriptions with wikipedia articles, you may notice unanticipated significant storage and performance hits.

Another thing to consider from Bill Karwin:

There's one possible performance impact: in MySQL, temporary tables and MEMORY tables store a VARCHAR column as a fixed-length column, padded out to its maximum length. If you design VARCHAR columns much larger than the greatest size you need, you will consume more memory than you have to. This affects cache efficiency, sorting speed, etc.

Basically, just come up with reasonable business constraints and error on a slightly larger size. As @onedaywhen pointed out, family names in UK are usually between 1-35 characters. If you decide to make it varchar(64), you're not really going to hurt anything... unless you're storing this guy's family name that's said to be up to 666 characters long. In that case, maybe varchar(1028) makes more sense.

And in case it's helpful, here's what varchar 2^5 through 2^10 might look like if filled:

varchar(32)     Lorem ipsum dolor sit amet amet.

varchar(64)     Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie

varchar(128)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas

varchar(256)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt

varchar(512)    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie

varchar(1024)   Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donecie
                vestibulum massa. Nullam dignissim elementum molestie. Vehiculas
                velit metus, sit amet tristique purus condimentum eleifend. Quis
                que mollis magna vel massa malesuada bibendum. Proinde tincidunt
                dolor tellus, sit amet porta neque varius vitae. Seduse molestie
                lacus id lacinia tempus. Vestibulum accumsan facilisis lorem, et
                mollis diam pretium gravida. In facilisis vitae tortor id vulput
                ate. Proin ornare arcu in sollicitudin pharetra. Crasti molestie
                dapibus leo lobortis eleifend. Vivamus vitae diam turpis. Vivamu
                nec tristique magna, vel tincidunt diam. Maecenas elementum semi
                quam. In ut est porttitor, sagittis nulla id, fermentum turpist.
                Curabitur pretium nibh a imperdiet cursus. Sed at vulputate este
                proin fermentum pretium justo, ac malesuada eros et Pellentesque
                vulputate hendrerit molestie. Aenean imperdiet a enim at finibus
                fusce ut ullamcorper risus, a cursus massa. Nunc non dapibus vel
                Lorem ipsum dolor sit amet, consectetur Praesent ut ultrices sit

Node.js – events js 72 throw er unhandled 'error' event

Well, your script throws an error and you just need to catch it (and/or prevent it from happening). I had the same error, for me it was an already used port (EADDRINUSE).

How do I concatenate a boolean to a string in Python?

answer = True
myvar = "the answer is " + str(answer)

Python does not do implicit casting, as implicit casting can mask critical logic errors. Just cast answer to a string itself to get its string representation ("True"), or use string formatting like so:

myvar = "the answer is %s" % answer

Note that answer must be set to True (capitalization is important).

SQL update statement in C#

command.Text = "UPDATE Student 
  SET Address = @add, City = @cit
  Where FirstName = @fn and LastName = @add";

 

how to delete files from amazon s3 bucket?

found one more way to do it using the boto:

from boto.s3.connection import S3Connection, Bucket, Key

conn = S3Connection(AWS_ACCESS_KEY, AWS_SECERET_KEY)

b = Bucket(conn, S3_BUCKET_NAME)

k = Key(b)

k.key = 'images/my-images/'+filename

b.delete_key(k)

Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Fabrício's answer is spot on; but I wanted to complement his answer with something less technical, which focusses on an analogy to help explain the concept of asynchronicity.


An Analogy...

Yesterday, the work I was doing required some information from a colleague. I rang him up; here's how the conversation went:

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim wants a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. Give me a ring back when you've got the information!

At this point, I hung up the phone. Since I needed information from Bob to complete my report, I left the report and went for a coffee instead, then I caught up on some email. 40 minutes later (Bob is slow), Bob called back and gave me the information I needed. At this point, I resumed my work with my report, as I had all the information I needed.


Imagine if the conversation had gone like this instead;

Me: Hi Bob, I need to know how we foo'd the bar'd last week. Jim want's a report on it, and you're the only one who knows the details about it.

Bob: Sure thing, but it'll take me around 30 minutes?

Me: That's great Bob. I'll wait.

And I sat there and waited. And waited. And waited. For 40 minutes. Doing nothing but waiting. Eventually, Bob gave me the information, we hung up, and I completed my report. But I'd lost 40 minutes of productivity.


This is asynchronous vs. synchronous behavior

This is exactly what is happening in all the examples in our question. Loading an image, loading a file off disk, and requesting a page via AJAX are all slow operations (in the context of modern computing).

Rather than waiting for these slow operations to complete, JavaScript lets you register a callback function which will be executed when the slow operation has completed. In the meantime, however, JavaScript will continue to execute other code. The fact that JavaScript executes other code whilst waiting for the slow operation to complete makes the behaviorasynchronous. Had JavaScript waited around for the operation to complete before executing any other code, this would have been synchronous behavior.

var outerScopeVar;    
var img = document.createElement('img');

// Here we register the callback function.
img.onload = function() {
    // Code within this function will be executed once the image has loaded.
    outerScopeVar = this.width;
};

// But, while the image is loading, JavaScript continues executing, and
// processes the following lines of JavaScript.
img.src = 'lolcat.png';
alert(outerScopeVar);

In the code above, we're asking JavaScript to load lolcat.png, which is a sloooow operation. The callback function will be executed once this slow operation has done, but in the meantime, JavaScript will keep processing the next lines of code; i.e. alert(outerScopeVar).

This is why we see the alert showing undefined; since the alert() is processed immediately, rather than after the image has been loaded.

In order to fix our code, all we have to do is move the alert(outerScopeVar) code into the callback function. As a consequence of this, we no longer need the outerScopeVar variable declared as a global variable.

var img = document.createElement('img');

img.onload = function() {
    var localScopeVar = this.width;
    alert(localScopeVar);
};

img.src = 'lolcat.png';

You'll always see a callback is specified as a function, because that's the only* way in JavaScript to define some code, but not execute it until later.

Therefore, in all of our examples, the function() { /* Do something */ } is the callback; to fix all the examples, all we have to do is move the code which needs the response of the operation into there!

* Technically you can use eval() as well, but eval() is evil for this purpose


How do I keep my caller waiting?

You might currently have some code similar to this;

function getWidthOfImage(src) {
    var outerScopeVar;

    var img = document.createElement('img');
    img.onload = function() {
        outerScopeVar = this.width;
    };
    img.src = src;
    return outerScopeVar;
}

var width = getWidthOfImage('lolcat.png');
alert(width);

However, we now know that the return outerScopeVar happens immediately; before the onload callback function has updated the variable. This leads to getWidthOfImage() returning undefined, and undefined being alerted.

To fix this, we need to allow the function calling getWidthOfImage() to register a callback, then move the alert'ing of the width to be within that callback;

function getWidthOfImage(src, cb) {     
    var img = document.createElement('img');
    img.onload = function() {
        cb(this.width);
    };
    img.src = src;
}

getWidthOfImage('lolcat.png', function (width) {
    alert(width);
});

... as before, note that we've been able to remove the global variables (in this case width).

Npm install cannot find module 'semver'

On Arch Linux what did the trick for me was:

sudo pacman -Rs npm
sudo pacman -S npm

Could not find method android() for arguments

guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:

Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.

So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.

I solved my problem just follow this steps:

? Copy .aar package in app/libs.

? Add this in app/build.gradle file:

repositories {
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):

dependencies {
    compile(name:'package_name', ext:'aar')
}

So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

You can use strcmp:

break x:20 if strcmp(y, "hello") == 0

20 is line number, x can be any filename and y can be any variable.

What is the best way to repeatedly execute a function every x seconds?

Lock your time loop to the system clock like this:

import time
starttime = time.time()
while True:
    print "tick"
    time.sleep(60.0 - ((time.time() - starttime) % 60.0))

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

How to use global variables in React Native?

Set up a flux container

simple example

import alt from './../../alt.js';

    class PostActions {
        constructor(){
        this.generateActions('setMessages');
        }

        setMessages(indexArray){
            this.actions.setMessages(indexArray);
        }
    }


export default alt.createActions(PostActions);

store looks like this

class PostStore{

    constructor(){

       this.messages = [];

       this.bindActions(MessageActions);
    }




    setMessages(messages){
        this.messages = messages;
    }
}

export default alt.createStore(PostStore);

Then every component that listens to the store can share this variable In your constructor is where you should grab it

constructor(props){
    super(props);

   //here is your data you get from the store, do what you want with it 
    var messageStore = MessageStore.getState();

}


    componentDidMount() {
      MessageStore.listen(this.onMessageChange.bind(this));
    }

    componentWillUnmount() {
      MessageStore.unlisten(this.onMessageChange.bind(this));
    }

    onMessageChange(state){ 
        //if the data ever changes each component listining will be notified and can do the proper processing. 
   }

This way, you can share you data across the app without every component having to communicate with each other.

PHP Include for HTML?

I figured out a simple solution to the PHP include stuff. Simply rename all your .html files to .php and your're good to go.

Compress images on client side before uploading

I read about an experiment here: http://webreflection.blogspot.com/2010/12/100-client-side-image-resizing.html

The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...

However, I’m not sure about using canvas to compress images, but you can certainly resize them.

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

It seems like your query returns more than one result check the database. In documentation of query.uniqueResult() you can read:

Throws: org.hibernate.NonUniqueResultException - if there is more than one matching result

If you want to avoid this error and still use unique result request, you can use this kind of workaround query.setMaxResults(1).uniqueResult();

DateTime "null" value

You can use a nullable class.

DateTime? date = new DateTime?();

Adding horizontal spacing between divs in Bootstrap 3

From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;

<ul>
    <li class='item col-md-12 panel' id='gameplay-title'>Title</li>
    <li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>

And so on... To add more categories add another ul in there. Now, for the CSS you just need this;

ul {
    list-style: none;
}
.item {
    display: inline;
    padding-right: 20px;
}

Anaconda Navigator won't launch (windows 10)

You need to update Anaconda using:

conda update

and

conda update anaconda-navigator

Try these commands on anaconda prompt and then try to launch navigator from the prompt itself using following command:

anaconda-navigator

If still the problem doesn't get solved, share the anaconda prompt logs here if they have any errors.

Logical Operators, || or OR?

Source: http://wallstreetdeveloper.com/php-logical-operators/

Here is sample code for working with logical operators:

<html>

<head>
    <title>Logical</title>
</head>

<body>
    <?php
        $a = 10;
        $b = 20;
        if ($a>$b)
        {
            echo " A is Greater";
        }
        elseif ($a<$b)
        {
            echo " A is lesser";
        }
        else
        {
             echo "A and B are equal";
        }
    ?>
    <?php
        $c = 30;
        $d = 40;
        //if (($a<$c) AND ($b<$d))
        if (($a<$c) && ($b<$d))
        {
            echo "A and B are larger";
        }
        if (isset($d))
            $d = 100;
        echo $d;
        unset($d);
    ?>
    <?php
        $var1 = 2;
        switch($var1)
        {
            case 1:  echo "var1 is 1";
                     break;
            case 2:  echo "var1 is 2";
                     break;
            case 3:  echo "var1 is 3";
                     break;
            default: echo "var1 is unknown";
        }
    ?>
</body>
</html>

Simple two column html layout without using tables

If you want to do it the HTML5 way (this particular code works better for things like blogs, where <article> is used multiple times, once for each blog entry teaser; ultimately, the elements themselves don't matter much, it's the styling and element placement that will get you your desired results):

<style type="text/css">
article {
  float: left;
  width: 500px;
}

aside {
  float: right;
  width: 200px;
}

#wrap {
  width: 700px;
  margin: 0 auto;
}
</style>

<div id="wrap">
  <article>
     Main content here
  </article>
  <aside>
     Sidebar stuff here
  </aside>
</div>

How to reset (clear) form through JavaScript?

Note, function form.reset() will not work if some input tag in the form have attribute name='reset'

How are iloc and loc different?

Label vs. Location

The main distinction between the two methods is:

  • loc gets rows (and/or columns) with particular labels.

  • iloc gets rows (and/or columns) at integer locations.

To demonstrate, consider a series s of characters with a non-monotonic integer index:

>>> s = pd.Series(list("abcdef"), index=[49, 48, 47, 0, 1, 2]) 
49    a
48    b
47    c
0     d
1     e
2     f

>>> s.loc[0]    # value at index label 0
'd'

>>> s.iloc[0]   # value at index location 0
'a'

>>> s.loc[0:1]  # rows at index labels between 0 and 1 (inclusive)
0    d
1    e

>>> s.iloc[0:1] # rows at index location between 0 and 1 (exclusive)
49    a

Here are some of the differences/similarities between s.loc and s.iloc when passed various objects:

<object> description s.loc[<object>] s.iloc[<object>]
0 single item Value at index label 0 (the string 'd') Value at index location 0 (the string 'a')
0:1 slice Two rows (labels 0 and 1) One row (first row at location 0)
1:47 slice with out-of-bounds end Zero rows (empty Series) Five rows (location 1 onwards)
1:47:-1 slice with negative step Four rows (labels 1 back to 47) Zero rows (empty Series)
[2, 0] integer list Two rows with given labels Two rows with given locations
s > 'e' Bool series (indicating which values have the property) One row (containing 'f') NotImplementedError
(s>'e').values Bool array One row (containing 'f') Same as loc
999 int object not in index KeyError IndexError (out of bounds)
-1 int object not in index KeyError Returns last value in s
lambda x: x.index[3] callable applied to series (here returning 3rd item in index) s.loc[s.index[3]] s.iloc[s.index[3]]

loc's label-querying capabilities extend well-beyond integer indexes and it's worth highlighting a couple of additional examples.

Here's a Series where the index contains string objects:

>>> s2 = pd.Series(s.index, index=s.values)
>>> s2
a    49
b    48
c    47
d     0
e     1
f     2

Since loc is label-based, it can fetch the first value in the Series using s2.loc['a']. It can also slice with non-integer objects:

>>> s2.loc['c':'e']  # all rows lying between 'c' and 'e' (inclusive)
c    47
d     0
e     1

For DateTime indexes, we don't need to pass the exact date/time to fetch by label. For example:

>>> s3 = pd.Series(list('abcde'), pd.date_range('now', periods=5, freq='M')) 
>>> s3
2021-01-31 16:41:31.879768    a
2021-02-28 16:41:31.879768    b
2021-03-31 16:41:31.879768    c
2021-04-30 16:41:31.879768    d
2021-05-31 16:41:31.879768    e

Then to fetch the row(s) for March/April 2021 we only need:

>>> s3.loc['2021-03':'2021-04']
2021-03-31 17:04:30.742316    c
2021-04-30 17:04:30.742316    d

Rows and Columns

loc and iloc work the same way with DataFrames as they do with Series. It's useful to note that both methods can address columns and rows together.

When given a tuple, the first element is used to index the rows and, if it exists, the second element is used to index the columns.

Consider the DataFrame defined below:

>>> import numpy as np 
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),  
                      index=list('abcde'), 
                      columns=['x','y','z', 8, 9])
>>> df
    x   y   z   8   9
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
e  20  21  22  23  24

Then for example:

>>> df.loc['c': , :'z']  # rows 'c' and onwards AND columns up to 'z'
    x   y   z
c  10  11  12
d  15  16  17
e  20  21  22

>>> df.iloc[:, 3]        # all rows, but only the column at index location 3
a     3
b     8
c    13
d    18
e    23

Sometimes we want to mix label and positional indexing methods for the rows and columns, somehow combining the capabilities of loc and iloc.

For example, consider the following DataFrame. How best to slice the rows up to and including 'c' and take the first four columns?

>>> import numpy as np 
>>> df = pd.DataFrame(np.arange(25).reshape(5, 5),  
                      index=list('abcde'), 
                      columns=['x','y','z', 8, 9])
>>> df
    x   y   z   8   9
a   0   1   2   3   4
b   5   6   7   8   9
c  10  11  12  13  14
d  15  16  17  18  19
e  20  21  22  23  24

We can achieve this result using iloc and the help of another method:

>>> df.iloc[:df.index.get_loc('c') + 1, :4]
    x   y   z   8
a   0   1   2   3
b   5   6   7   8
c  10  11  12  13

get_loc() is an index method meaning "get the position of the label in this index". Note that since slicing with iloc is exclusive of its endpoint, we must add 1 to this value if we want row 'c' as well.

How to write PNG image to string with the PIL?

For Python3 it is required to use BytesIO:

from io import BytesIO
from PIL import Image, ImageDraw

image = Image.new("RGB", (300, 50))
draw = ImageDraw.Draw(image)
draw.text((0, 0), "This text is drawn on image")

byte_io = BytesIO()

image.save(byte_io, 'PNG')

Read more: http://fadeit.dk/blog/post/python3-flask-pil-in-memory-image

How can I resolve the error: "The command [...] exited with code 1"?

For me, in VS 2013, I had to get rid of missing references under References in the UI project (MVC). Turns out, the ones missing were not referenced.

why $(window).load() is not working in jQuery?

I have to write a whole answer separately since it's hard to add a comment so long to the second answer.

I'm sorry to say this, but the second answer above doesn't work right.

The following three scenarios will show my point:

Scenario 1: Before the following way was deprecated,

  $(window).load(function () {
     alert("Window Loaded.");
  });

if we execute the following two queries:

<script>
   $(window).load(function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the way it should be.

Scenario 2: But if we execute the following two queries like the second answer above suggests:

<script>
   $(window).ready(function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

the alert (Window Loaded.) from the first query will show first, and the one (Dom Loaded.) from the second query will show later, which is NOT right.

Scenario 3: On the other hand, if we execute the following two queries, we'll get the correct result:

<script>
   $(window).on("load", function () {
     alert("Window Loaded.");
   }); 

   $(document).ready(function() {
     alert("Dom Loaded.");
   });
</script>,

that is to say, the alert (Dom Loaded.) from the second query will show first, and the one (Window Loaded.) from the first query will show later, which is the RIGHT result.

In short, the FIRST answer is the CORRECT one:

$(window).on('load', function () {
  alert("Window Loaded.");
});

How do I choose the URL for my Spring Boot webapp?

As of spring boot 2 the server.contextPath property is deprecated. Instead you should use server.servlet.contextPath.

So in your application.properties file add:

server.servlet.contextPath=/myWebApp

For more details see: https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-2.0-Migration-Guide#servlet-specific-server-properties

Hide HTML element by id

@Adam Davis, the code you entered is actually a jQuery call. If you already have the library loaded, that works just fine, otherwise you will need to append the CSS

<style type="text/css">
    #nav-ask{ display:none; }
</style>

or if you already have a "hideMe" CSS Class:

<script type="text/javascript">

    if(document.getElementById && document.createTextNode)
    {
        if(document.getElementById('nav-ask'))
        {
            document.getElementById('nav-ask').className='hideMe';
        }
    }

</script>

How can I show current location on a Google Map on Android Marshmallow?

Sorry but that's just much too much overhead (above), short and quick, if you have the MapFragment, you also have to map, just do the following:

if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            googleMap.setMyLocationEnabled(true)
} else {
    // Show rationale and request permission.
}

Code is in Kotlin, hope you don't mind.

have fun

Btw I think this one is a duplicate of: Show Current Location inside Google Map Fragment

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

Django DoesNotExist

I have found the solution to this issue using ObjectDoesNotExist on this way

from django.core.exceptions import ObjectDoesNotExist
......

try:
  # try something
except ObjectDoesNotExist:
  # do something

After this, my code works as I need

Thanks any way, your post help me to solve my issue

How can I submit a form using JavaScript?

You can use...

document.getElementById('theForm').submit();

...but don't replace the innerHTML. You could hide the form and then insert a processing... span which will appear in its place.

var form = document.getElementById('theForm');

form.style.display = 'none';

var processing = document.createElement('span');

processing.appendChild(document.createTextNode('processing ...'));

form.parentNode.insertBefore(processing, form);

How to resolve "could not execute statement; SQL [n/a]; constraint [numbering];"?

I have got the same error but I have resolved the issue in the following ways:

  1. Provide all the mandatory filed of your bean/model class
  2. Don't violet the concept of the unique constraint, Provide unique value in Unique constraints.

How to put a jpg or png image into a button in HTML

You can use some inline CSS like this

<input type="submit" name="submit" style="background: url(images/stack.png); width:100px; height:25px;" />

Should do the magic, also you may wanna do a border:none; to get rid of the standard borders.

How do I reset a jquery-chosen select option with jQuery?

Setting the select element's value to an empty string is the correct way to do it. However, that only updates the root select element. The custom chosen element has no idea that the root select has been updated.

In order to notify chosen that the select has been modified, you have to trigger chosen:updated:

$('#autoship_option').val('').trigger('chosen:updated');

or, if you're not sure that the first option is an empty string, use this:

$('#autoship_option')
    .find('option:first-child').prop('selected', true)
    .end().trigger('chosen:updated');

Read the documentation here (find the section titled Updating Chosen Dynamically).


P.S. Older versions of Chosen use a slightly different event:

$('#autoship_option').val('').trigger('liszt:updated');

jquery multiple checkboxes array

A global function that can be reused:

function getCheckedGroupBoxes(groupName) {

    var checkedAry= [];
    $.each($("input[name='" + groupName + "']:checked"), function () {
        checkedAry.push($(this).attr("id"));
    });

     return checkedAry;

}

where the groupName is the name of the group of the checkboxes, in you example :'options[]'

m2eclipse error

I would add some points that helped me to solve this problem :

Having the local repository OK, on the other hand, turned out to be quite costly, as many archetypes would not get loaded, due apparently to timeouts of m2eclipse and very unstable communication speeds in my case.

In many cases only the error file could be found in the folder ex : xxx.jar.lastUpdated, instead of the jar or pom file. I had always to suppress this file to permit a new download.

Also really worthy were :

  • as already said, using the mvn clean install from the command line, apparently much more patient than m2eclipse, and also efficient and verbose, at least for the time being.

  • (and also the Update Project of the Maven menu)

  • downloading using the dependency:get goal

    mvn org.apache.maven.plugins:maven-dependency-plugin:2.1:get -DrepoUrl=url -Dartifact=groupId:artifactId:version1

(from within the project folder) (hint given in another thread, thanks also).

  • also downloading and installing manually (.jar+.sha1), from in particular, "m2proxy atlassian" .

  • adding other repositories in the pom.xml itself (the settings.xml mirror configuration did'nt do the job, I don't know yet why). Ex : nexus/content/repositories/releases/ et nexus/content/repositories/releases/, sous repository.jboss.org, ou download.java.net/maven/2 .

To finish, in any case, a lot of time (!..) could have been et could certainly still be spared with a light tool repairing thoroughly the local repository straightaway. I could not yet find it. Actually it should even be normally a mvn command ("--repair-local-repository").

SQL query, store result of SELECT in local variable

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)

INSERT INTO @result1
SELECT a, b, c
FROM table1

SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1

This should be fine for what you need.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

The configuration I use in my parent level pom where I have separate unit and integration test phases.

I configure the following properties in the parent POM Properties

    <maven.surefire.report.plugin>2.19.1</maven.surefire.report.plugin>
    <jacoco.plugin.version>0.7.6.201602180812</jacoco.plugin.version>
    <jacoco.check.lineRatio>0.52</jacoco.check.lineRatio>
    <jacoco.check.branchRatio>0.40</jacoco.check.branchRatio>
    <jacoco.check.complexityMax>15</jacoco.check.complexityMax>
    <jacoco.skip>false</jacoco.skip>
    <jacoco.excludePattern/>
    <jacoco.destfile>${project.basedir}/../target/coverage-reports/jacoco.exec</jacoco.destfile>

    <sonar.language>java</sonar.language>
    <sonar.exclusions>**/generated-sources/**/*</sonar.exclusions>
    <sonar.core.codeCoveragePlugin>jacoco</sonar.core.codeCoveragePlugin>
    <sonar.coverage.exclusions>${jacoco.excludePattern}</sonar.coverage.exclusions>
    <sonar.dynamicAnalysis>reuseReports</sonar.dynamicAnalysis>
    <sonar.jacoco.reportPath>${project.basedir}/../target/coverage-reports</sonar.jacoco.reportPath>

    <skip.surefire.tests>${skipTests}</skip.surefire.tests>
    <skip.failsafe.tests>${skipTests}</skip.failsafe.tests>

I place the plugin definitions under plugin management.

Note that I define a property for surefire (surefireArgLine) and failsafe (failsafeArgLine) arguments to allow jacoco to configure the javaagent to run with each test.

Under pluginManagement

  <build>
     <pluginManagment>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <fork>true</fork>
                    <meminitial>1024m</meminitial>
                    <maxmem>1024m</maxmem>
                    <compilerArgument>-g</compilerArgument>
                    <source>${maven.compiler.source}</source>
                    <target>${maven.compiler.target}</target>
                    <encoding>${project.build.sourceEncoding}</encoding>
                </configuration>
            </plugin>

            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                    <forkCount>4</forkCount>
                    <reuseForks>false</reuseForks>
                    <argLine>-Xmx2048m ${surefireArgLine}</argLine>
                    <includes>
                        <include>**/*Test.java</include>
                    </includes>
                    <excludes>
                        <exclude>**/*IT.java</exclude>
                    </excludes>
                    <skip>${skip.surefire.tests}</skip>
                </configuration>
            </plugin>
            <plugin>
                <!-- For integration test separation -->
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <dependencies>
                    <dependency>
                        <groupId>org.apache.maven.surefire</groupId>
                        <artifactId>surefire-junit47</artifactId>
                        <version>2.19.1</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <forkCount>4</forkCount>
                    <reuseForks>false</reuseForks>
                    <argLine>${failsafeArgLine}</argLine>
                    <includes>
                        <include>**/*IT.java</include>
                    </includes>
                    <skip>${skip.failsafe.tests}</skip>
                </configuration>
                <executions>
                    <execution>
                        <id>integration-test</id>
                        <goals>
                            <goal>integration-test</goal>
                        </goals>
                    </execution>
                    <execution>
                        <id>verify</id>
                        <goals>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>

            <plugin>
                <!-- Code Coverage -->
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <version>${jacoco.plugin.version}</version>
                <configuration>
                    <haltOnFailure>true</haltOnFailure>
                    <excludes>
                        <exclude>**/*.mar</exclude>
                        <exclude>${jacoco.excludePattern}</exclude>
                    </excludes>
                    <rules>
                        <rule>
                            <element>BUNDLE</element>
                            <limits>
                                <limit>
                                    <counter>LINE</counter>
                                    <value>COVEREDRATIO</value>
                                    <minimum>${jacoco.check.lineRatio}</minimum>
                                </limit>
                                <limit>
                                    <counter>BRANCH</counter>
                                    <value>COVEREDRATIO</value>
                                    <minimum>${jacoco.check.branchRatio}</minimum>
                                </limit>
                            </limits>
                        </rule>
                        <rule>
                            <element>METHOD</element>
                            <limits>
                                <limit>
                                    <counter>COMPLEXITY</counter>
                                    <value>TOTALCOUNT</value>
                                    <maximum>${jacoco.check.complexityMax}</maximum>
                                </limit>
                            </limits>
                        </rule>
                    </rules>
                </configuration>
                <executions>
                    <execution>
                        <id>pre-unit-test</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <destFile>${jacoco.destfile}</destFile>
                            <append>true</append>
                            <propertyName>surefireArgLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-unit-test</id>
                        <phase>test</phase>
                        <goals>
                            <goal>report</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                            <outputDirectory>${sonar.jacoco.reportPath}</outputDirectory>
                            <skip>${skip.surefire.tests}</skip>
                        </configuration>
                    </execution>
                    <execution>
                        <id>pre-integration-test</id>
                        <phase>pre-integration-test</phase>
                        <goals>
                            <goal>prepare-agent-integration</goal>
                        </goals>
                        <configuration>
                            <destFile>${jacoco.destfile}</destFile>
                            <append>true</append>
                            <propertyName>failsafeArgLine</propertyName>
                        </configuration>
                    </execution>
                    <execution>
                        <id>post-integration-test</id>
                        <phase>post-integration-test</phase>
                        <goals>
                            <goal>report-integration</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                            <outputDirectory>${sonar.jacoco.reportPath}</outputDirectory>
                            <skip>${skip.failsafe.tests}</skip>
                        </configuration>
                    </execution>
                    <!-- Disabled until such time as code quality stops this tripping
                    <execution>
                        <id>default-check</id>
                        <goals>
                            <goal>check</goal>
                        </goals>
                        <configuration>
                            <dataFile>${jacoco.destfile}</dataFile>
                        </configuration>
                    </execution>
                    -->
                </executions>
            </plugin>
            ...

And in the build section

 <build>
     <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
        </plugin>

        <plugin>
            <!-- for unit test execution -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
        </plugin>
        <plugin>
            <!-- For integration test separation -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-failsafe-plugin</artifactId>
        </plugin>
        <plugin>
            <!-- For code coverage -->
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
        </plugin>
        ....

And in the reporting section

    <reporting>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-report-plugin</artifactId>
            <version>${maven.surefire.report.plugin}</version>
            <configuration>
                <showSuccess>false</showSuccess>
                <alwaysGenerateFailsafeReport>true</alwaysGenerateFailsafeReport>
                <alwaysGenerateSurefireReport>true</alwaysGenerateSurefireReport>
                <aggregate>true</aggregate>
            </configuration>
        </plugin>
        <plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>${jacoco.plugin.version}</version>
            <configuration>
                <excludes>
                    <exclude>**/*.mar</exclude>
                    <exclude>${jacoco.excludePattern}</exclude>
                </excludes>
            </configuration>
        </plugin>
     </plugins>
  </reporting>

How to pass a callback as a parameter into another function

Yes of course, function are objects and can be passed, but of course you must declare it:

function firstFunction(){
    //some code
    var callbackfunction = function(data){
       //do something with the data returned from the ajax request
     }
    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).

How does one set up the Visual Studio Code compiler/debugger to GCC?

Just wanted to add that if you want to debug stuff, you should compile with debug information before you debug, otherwise the debugger won't work. So, in g++ you need to do g++ -g source.cpp. The -g flag means that the compiler will insert debugging information into your executable, so that you can run gdb on it.

Is there a sleep function in JavaScript?

You can use the setTimeout or setInterval functions.

Return the most recent record from ElasticSearch index

Do you have _timestamp enabled in your doc mapping?

{
    "doctype": {
        "_timestamp": {
            "enabled": "true",
            "store": "yes"
        },
        "properties": {
            ...
        }
    }
}

You can check your mapping here:

http://localhost:9200/_all/_mapping

If so I think this might work to get most recent:

{
  "query": {
    "match_all": {}
  },
  "size": 1,
  "sort": [
    {
      "_timestamp": {
        "order": "desc"
      }
    }
  ]
}

How to pass a variable from Activity to Fragment, and pass it back?

Public variable declarations in classes is the easiest way:

On target class:

public class MyFragment extends Fragment {
    public MyCallerFragment caller; // Declare the caller var
...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {
        // Do what you want with the vars
        caller.str = "I changed your value!";
        caller.i = 9999;
        ...
        return inflater.inflate(R.layout.my_fragment, container, false);
    }
...
}

On caller class:

public class MyCallerFragment extends Fragment {
    public Integer i; // Declared public var
    public String str; // Declared public var
        ...
            FragmentManager fragmentManager = getParentFragmentManager();
            FragmentTransaction transaction = fragmentManager.beginTransaction();

            myFragment = new MyFragment();
            myFragment.caller = this;
            transaction.replace(R.id.nav_host_fragment, myFragment)
                    .addToBackStack(null).commit();
        ...
}

If you want to use the main activity it is easy too:

On main activity class:

public class MainActivity extends AppCompatActivity {
    public String str; // Declare public var
    public EditText myEditText; // You can declare public elements too.
                                // Taking care that you have it assigned
                                // correctly.
...
}

On called class:

public class MyFragment extends Fragment {
    private MainActivity main; // Declare the activity var
...
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
           Bundle savedInstanceState) {
        // Assign the main activity var
        main = (MainActivity) getActivity();

        // Do what you want with the vars
        main.str = "I changed your value!";
        main.myEditText.setText("Wow I can modify the EditText too!");
        ...
        return inflater.inflate(R.layout.my_fragment, container, false);
    }
...
}

Note: Take care when using events (onClick, onChanged, etc) because you can be on a "fighting" situation where more than one assign a variable. The result will be that the variable sometimes does not will change or will return to the last value magically.

For more combinations use your creativity. :)

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

In year of 2020, these code seems to return exception as

System.Net.Mail.SmtpStatusCode.MustIssueStartTlsFirst or The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM

This code is working for me.

            using (SmtpClient client = new SmtpClient()
            {
                Host = "smtp.office365.com",
                Port = 587,
                UseDefaultCredentials = false, // This require to be before setting Credentials property
                DeliveryMethod = SmtpDeliveryMethod.Network,
                Credentials = new NetworkCredential("[email protected]", "password"), // you must give a full email address for authentication 
                TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
                EnableSsl = true // Set to avoid secure connection exception
            })
            {

                MailMessage message = new MailMessage()
                {
                    From = new MailAddress("[email protected]"), // sender must be a full email address
                    Subject = subject,
                    IsBodyHtml = true,
                    Body = "<h1>Hello World</h1>",
                    BodyEncoding = System.Text.Encoding.UTF8,
                    SubjectEncoding = System.Text.Encoding.UTF8,

                };
                var toAddresses = recipients.Split(',');
                foreach (var to in toAddresses)
                {
                    message.To.Add(to.Trim());
                }

                try
                {
                    client.Send(message);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine(ex.Message);
                }
            }

How to convert a color integer to a hex String in Android?

Integer value of ARGB color to hexadecimal string:

String hex = Integer.toHexString(color); // example for green color FF00FF00

Hexadecimal string to integer value of ARGB color:

int color = (Integer.parseInt( hex.substring( 0,2 ), 16) << 24) + Integer.parseInt( hex.substring( 2 ), 16);

How many socket connections possible?

I achieved 1600k concurrent idle socket connections, and at the same time 57k req/s on a Linux desktop (16G RAM, I7 2600 CPU). It's a single thread http server written in C with epoll. Source code is on github, a blog here.

Edit:

I did 600k concurrent HTTP connections (client & server) on both the same computer, with JAVA/Clojure . detail info post, HN discussion: http://news.ycombinator.com/item?id=5127251

The cost of a connection(with epoll):

  • application need some RAM per connection
  • TCP buffer 2 * 4k ~ 10k, or more
  • epoll need some memory for a file descriptor, from epoll(7)

Each registered file descriptor costs roughly 90 bytes on a 32-bit kernel, and roughly 160 bytes on a 64-bit kernel.

How should I load files into my Java application?

What are you loading the files for - configuration or data (like an input file) or as a resource?

  • If as a resource, follow the suggestion and example given by Will and Justin
  • If configuration, then you can use a ResourceBundle or Spring (if your configuration is more complex).
  • If you need to read a file in order to process the data inside, this code snippet may help BufferedReader file = new BufferedReader(new FileReader(filename)) and then read each line of the file using file.readLine(); Don't forget to close the file.

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

To answer the initial question "how to properly pass routedata to error controller?":

IController errorController = new ErrorController();
errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData));

Then in your ErrorController class, implement a function like this:

[AcceptVerbs(HttpVerbs.Get)]
public ViewResult Error(Exception exception)
{
    return View("Error", exception);
}

This pushes the exception into the View. The view page should be declared as follows:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<System.Exception>" %>

And the code to display the error:

<% if(Model != null) { %>  <p><b>Detailed error:</b><br />  <span class="error"><%= Helpers.General.GetErrorMessage((Exception)Model, false) %></span></p> <% } %>

Here is the function that gathers the all exception messages from the exception tree:

    public static string GetErrorMessage(Exception ex, bool includeStackTrace)
    {
        StringBuilder msg = new StringBuilder();
        BuildErrorMessage(ex, ref msg);
        if (includeStackTrace)
        {
            msg.Append("\n");
            msg.Append(ex.StackTrace);
        }
        return msg.ToString();
    }

    private static void BuildErrorMessage(Exception ex, ref StringBuilder msg)
    {
        if (ex != null)
        {
            msg.Append(ex.Message);
            msg.Append("\n");
            if (ex.InnerException != null)
            {
                BuildErrorMessage(ex.InnerException, ref msg);
            }
        }
    }

Regex Match all characters between two strings

Sublime Text 3x

In sublime text, you simply write the two word you are interested in keeping for example in your case it is

"This is" and "sentence"

and you write .* in between

i.e. This is .* sentence

and this should do you well

Transfer data between iOS and Android via Bluetooth?

Maybe a bit delayed, but technologies have evolved since so there is certainly new info around which draws fresh light on the matter...

As iOS has yet to open up an API for WiFi Direct and Multipeer Connectivity is iOS only, I believe the best way to approach this is to use BLE, which is supported by both platforms (some better than others).

On iOS a device can act both as a BLE Central and BLE Peripheral at the same time, on Android the situation is more complex as not all devices support the BLE Peripheral state. Also the Android BLE stack is very unstable (to date).

If your use case is feature driven, I would suggest to look at Frameworks and Libraries that can achieve cross platform communication for you, without you needing to build it up from scratch.

For example: http://p2pkit.io or google nearby

Disclaimer: I work for Uepaa, developing p2pkit.io for Android and iOS.

JavaScript split String with white space

In case you're sure you have only one space between two words, you can use this one

str.replace(/\s+/g, ' ').split(' ')

so you replace one space by two, the split by space

OSError: [Errno 2] No such file or directory while using python subprocess in Django

No such file or directory can be also raised if you are trying to put a file argument to Popen with double-quotes.

For example:

call_args = ['mv', '"path/to/file with spaces.txt"', 'somewhere']

In this case, you need to remove double-quotes.

call_args = ['mv', 'path/to/file with spaces.txt', 'somewhere']

On linux SUSE or RedHat, how do I load Python 2.7

If you get an error when at the ./configure stage that says

configure: error: in `/home//Downloads/Python-2.7.14': configure: error: no acceptable C compiler found in $PATH

then try this.

no acceptable C compiler found in $PATH when installing python

How create table only using <div> tag and Css

.div-table {
  display: table;         
  width: auto;         
  background-color: #eee;         
  border: 1px solid #666666;         
  border-spacing: 5px; /* cellspacing:poor IE support for  this */
}
.div-table-row {
  display: table-row;
  width: auto;
  clear: both;
}
.div-table-col {
  float: left; /* fix for  buggy browsers */
  display: table-column;         
  width: 200px;         
  background-color: #ccc;  
}

Runnable snippet:

_x000D_
_x000D_
.div-table {_x000D_
  display: table;         _x000D_
  width: auto;         _x000D_
  background-color: #eee;         _x000D_
  border: 1px solid #666666;         _x000D_
  border-spacing: 5px; /* cellspacing:poor IE support for  this */_x000D_
}_x000D_
.div-table-row {_x000D_
  display: table-row;_x000D_
  width: auto;_x000D_
  clear: both;_x000D_
}_x000D_
.div-table-col {_x000D_
  float: left; /* fix for  buggy browsers */_x000D_
  display: table-column;         _x000D_
  width: 200px;         _x000D_
  background-color: #ccc;  _x000D_
}
_x000D_
<body>_x000D_
  <form id="form1">_x000D_
      <div class="div-table">_x000D_
             <div class="div-table-row">_x000D_
                <div class="div-table-col" align="center">Customer ID</div>_x000D_
                <div  class="div-table-col">Customer Name</div>_x000D_
                <div  class="div-table-col">Customer Address</div>_x000D_
             </div>_x000D_
            <div class="div-table-row">_x000D_
                  <div class="div-table-col">001</div>_x000D_
                <div class="div-table-col">002</div>_x000D_
                <div class="div-table-col">003</div>_x000D_
            </div>_x000D_
            <div class="div-table-row">_x000D_
                <div class="div-table-col">xxx</div>_x000D_
                <div class="div-table-col">yyy</div>_x000D_
                <div class="div-table-col">www</div>_x000D_
           </div>_x000D_
            <div class="div-table-row">_x000D_
                <div class="div-table-col">ttt</div>_x000D_
                <div class="div-table-col">uuu</div>_x000D_
                <div class="div-table-col">Mkkk</div>_x000D_
           </div>_x000D_
_x000D_
      </div>_x000D_
  </form>_x000D_
</body>
_x000D_
_x000D_
_x000D_

php var_dump() vs print_r()

I'd aditionally recommend putting the output of var_dump() or printr into a pre tag when outputting to a browser.

print "<pre>";
print_r($dataset);
print "</pre>";

Will give a more readable result.

Accessing JPEG EXIF rotation data in JavaScript on the client side

Firefox 26 supports image-orientation: from-image: images are displayed portrait or landscape, depending on EXIF data. (See sethfowler.org/blog/2013/09/13/new-in-firefox-26-css-image-orientation.)

There is also a bug to implement this in Chrome.

Beware that this property is only supported by Firefox and is likely to be deprecated.

Is there a way to suppress JSHint warning for one given line?

As you can see in the documentation of JSHint you can change options per function or per file. In your case just place a comment in your file or even more local just in the function that uses eval:

/*jshint evil:true */

function helloEval(str) {
    /*jshint evil:true */
    eval(str);
}

How to use comparison and ' if not' in python?

You can do:

if not (u0 <= u <= u0+step):
    u0 = u0+ step # change the condition until it is satisfied
else:
    do sth. # condition is satisfied

Using a loop:

while not (u0 <= u <= u0+step):
   u0 = u0+ step # change the condition until it is satisfied
do sth. # condition is satisfied

Updating state on props change in React Form

componentWillReceiveProps is being deprecated because using it "often leads to bugs and inconsistencies".

If something changes from the outside, consider resetting the child component entirely with key.

Providing a key prop to the child component makes sure that whenever the value of key changes from the outside, this component is re-rendered. E.g.,

<EmailInput
  defaultEmail={this.props.user.email}
  key={this.props.user.id}
/>

On its performance:

While this may sound slow, the performance difference is usually insignificant. Using a key can even be faster if the components have heavy logic that runs on updates since diffing gets bypassed for that subtree.

Multiple conditions in if statement shell script

if using /bin/sh you can use:

if [ <condition> ] && [ <condition> ]; then
    ...
fi

if using /bin/bash you can use:

if [[ <condition> && <condition> ]]; then
    ...
fi

How to get a DOM Element from a JQuery Selector

Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:

$('#element').get(0);

I have verified this actually returns the DOM element that was matched.

MySQL: determine which database is selected?

@mysql_result(mysql_query("SELECT DATABASE();"),0)

If no database selected, or there is no connection it returns NULL otherwise the name of the selected database.

"Series objects are mutable and cannot be hashed" error

Shortly: gene_name[x] is a mutable object so it cannot be hashed. To use an object as a key in a dictionary, python needs to use its hash value, and that's why you get an error.

Further explanation:

Mutable objects are objects which value can be changed. For example, list is a mutable object, since you can append to it. int is an immutable object, because you can't change it. When you do:

a = 5;
a = 3;

You don't change the value of a, you create a new object and make a point to its value.

Mutable objects cannot be hashed. See this answer.

To solve your problem, you should use immutable objects as keys in your dictionary. For example: tuple, string, int.

no overload for matches delegate 'system.eventhandler'

You need to wrap button click handler to match the pattern

public void klik(object sender, EventArgs e)

Minimum and maximum value of z-index?

http://www.w3.org/TR/CSS21/visuren.html#z-index

'z-index'

Value: auto | <integer> | inherit

http://www.w3.org/TR/CSS21/syndata.html#numbers

Some value types may have integer values (denoted by <integer>) or real number values (denoted by <number>). Real numbers and integers are specified in decimal notation only. An <integer> consists of one or more digits "0" to "9". A <number> can either be an <integer>, or it can be zero or more digits followed by a dot (.) followed by one or more digits. Both integers and real numbers may be preceded by a "-" or "+" to indicate the sign. -0 is equivalent to 0 and is not a negative number.

Note that many properties that allow an integer or real number as a value actually restrict the value to some range, often to a non-negative value.

So basically there are no limitations for z-index value in the CSS standard, but I guess most browsers limit it to signed 32-bit values (-2147483648 to +2147483647) in practice (64 would be a little off the top, and it doesn't make sense to use anything less than 32 bits these days)

Regex for remove everything after | (with | )

If you want to get everything after | excluding set character use this code.

[^|]*$

Others solutions \|.*$

Results : | mypcworld

This one [^|]*$

Results : mypcworld

http://regexr.com/3elkd

Changing element style attribute dynamically using JavaScript

Assuming you have HTML like this:

<div id='thediv'></div>

If you want to modify the style attribute of this div, you'd use

document.getElementById('thediv').style.[ATTRIBUTE] = '[VALUE]'

Replace [ATTRIBUTE] with the style attribute you want. Remember to remove '-' and make the following letter uppercase.

Examples

document.getElementById('thediv').style.display = 'none'; //changes the display
document.getElementById('thediv').style.paddingLeft = 'none'; //removes padding

Check div is hidden using jquery

Try:

if(!$('#car2').is(':visible'))
{  
    alert('car 2 is hidden');       
}

How can I wrap text in a label using WPF?

The Label control doesn't directly support text wrapping in WPF. You should use a TextBlock instead. (Of course, you can place the TextBlock inside of a Label control, if you wish.)

Sample code:

<TextBlock TextWrapping="WrapWithOverflow">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec adipiscing
    nulla quis libero egestas lobortis. Duis blandit imperdiet ornare. Nulla
    ac arcu ut purus placerat congue. Integer pretium fermentum gravida.
</TextBlock>

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

Google Play services SDK is inside Google Repository.

  1. Start Intellij IDEA.

  2. On the Tools menu, click Android > SDK Manager.

  3. Update the Android SDK Manager: click SDK Tools, expand Support Repository, select Google Repository, and then click OK.

Current Google Repository version is 57.

After update sync your project.

EDIT

From version 11.2.0, we've to use the google maven repo so add google maven repo link in repositories tag. Check release note from here.

allprojects {
     ..
     repositories {
     ...
        maven {
            url 'https://maven.google.com'
            // Alternative URL is 'https://dl.google.com/dl/android/maven2/'
        }
     }
}

Beautiful Soup and extracting a div and its contents by ID

from bs4 import BeautifulSoup
from requests_html import HTMLSession

url = 'your_url'
session = HTMLSession()
resp = session.get(url)

# if element with id "articlebody" is dynamic, else need not to render
resp.html.render()

soup = bs(resp.html.html, "lxml")
soup.find("div", {"id": "articlebody"})

When does Java's Thread.sleep throw InterruptedException?

The InterruptedException is usually thrown when a sleep is interrupted.

T-SQL Cast versus Convert

CAST uses ANSI standard. In case of portability, this will work on other platforms. CONVERT is specific to sql server. But is very strong function. You can specify different styles for dates

MySQL : transaction within a stored procedure

Just an alternative to the code by rkosegi,

BEGIN

    .. Declare statements ..

    DECLARE EXIT HANDLER FOR SQLEXCEPTION 
    BEGIN
          .. set any flags etc  eg. SET @flag = 0; ..
          ROLLBACK;
    END;

    START TRANSACTION;

        .. Query 1 ..
        .. Query 2 ..
        .. Query 3 ..

    COMMIT;
    .. eg. SET @flag = 1; ..

END

What is it exactly a BLOB in a DBMS context

They are binary large objects, you can use them to store binary data such as images or serialized objects among other things.

PHP - SSL certificate error: unable to get local issuer certificate

I have a proper solution of this problem, lets try and understand the root cause of this issue. This issue comes when remote servers ssl cannot be verified using root certificates in your system's certificate store or remote ssl is not installed along with chain certificates. If you have a linux system with root ssh access, then in this case you can try updating your certificate store with below command:

update-ca-certificates

If still, it doesn't work then you need to add root and interim certificate of remote server in your cert store. You can download root and intermediate certs and add them in /usr/local/share/ca-certificates directory and then run command update-ca-certificates. This should do the trick. Similarly for windows you can search how to add root and intermediate cert.

The other way you can solve this problem is by asking remote server team to add ssl certificate as a bundle of domain root cert, intermediate cert and root cert.

Make a float only show two decimal places

Use NSNumberFormatter with maximumFractionDigits as below:

NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
formatter.maximumFractionDigits = 2;
NSLog(@"%@", [formatter stringFromNumber:[NSNumber numberWithFloat:12.345]]);

And you will get 12.35

Curl not recognized as an internal or external command, operable program or batch file

Steps to install curl in windows

Install cURL on Windows

There are 4 steps to follow to get cURL installed on Windows.

Step 1 and Step 2 is to install SSL library. Step 3 is to install cURL. Step 4 is to install a recent certificate

Step One: Install Visual C++ 2008 Redistributables

From https://www.microsoft.com/en-za/download/details.aspx?id=29 For 64bit systems Visual C++ 2008 Redistributables (x64) For 32bit systems Visual C++ 2008 Redistributables (x32)

Step Two: Install Win(32/64) OpenSSL v1.0.0k Light

From http://www.shininglightpro.com/products/Win32OpenSSL.html For 64bit systems Win64 OpenSSL v1.0.0k Light For 32bit systems Win32 OpenSSL v1.0.0k Light

Step Three: Install cURL

Depending on if your system is 32 or 64 bit, download the corresponding** curl.exe.** For example, go to the Win64 - Generic section and download the Win64 binary with SSL support (the one where SSL is not crossed out). Visit http://curl.haxx.se/download.html

Copy curl.exe to C:\Windows\System32

Step Four: Install Recent Certificates

Do not skip this step. Download a recent copy of valid CERT files from https://curl.haxx.se/ca/cacert.pem Copy it to the same folder as you placed curl.exe (C:\Windows\System32) and rename it as curl-ca-bundle.crt

If you have already installed curl or after doing the above steps, add the directory where it's installed to the windows path:

1 - From the Desktop, right-click My Computer and click Properties.
2 - Click Advanced System Settings .
3 - In the System Properties window click the Environment Variables button.
4 - Select Path and click Edit.
5 - Append ;c:\path to curl directory at the end.
5 - Click OK.
6 - Close and re-open the command prompt

How to disable manual input for JQuery UI Datepicker field?

I think you should add style="background:white;" to make looks like it is writable

<input type="text" size="23" name="dateMonthly" id="dateMonthly" readonly="readonly"   style="background:white;"/>

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

You could try simply blocking the context menu by adding the following to your body tag:

<body oncontextmenu="return false;">

This will block all access to the context menu (not just from the right mouse button but from the keyboard as well).

P.S. you can add this to any tag you want to disable the context menu on

for example:

<div class="mydiv" oncontextmenu="return false;">

Will disable the context menu in that particular div only

How to force 'cp' to overwrite directory instead of creating another one inside?

The following command ensures dotfiles (hidden files) are included in the copy:

$ cp -Rf foo/. bar

How to edit data in result grid in SQL Server Management Studio

Right click on any table in your dB of interest or any database in the server using master if there are joins or using multiple dBs. Select "edit top 200 rows". Select the "SQL" button in the task bar. Copy and paste your code over the existing code and run again. Now you can edit your query's result set. Sherry ;-)

Show/hide 'div' using JavaScript

Set your HTML as

<div id="body" hidden="">
 <h1>Numbers</h1>
 </div>
 <div id="body1" hidden="hidden">
 Body 1
 </div>

And now set the javascript as

function changeDiv()
  {
  document.getElementById('body').hidden = "hidden"; // hide body div tag
  document.getElementById('body1').hidden = ""; // show body1 div tag
  document.getElementById('body1').innerHTML = "If you can see this, JavaScript function worked"; 
  // display text if JavaScript worked
   }

How to use FormData in react-native?

You can use react-native-image-picker and axios (form-data)

uploadS3 = (path) => {
    var data = new FormData();

    data.append('files',
        { uri: path, name: 'image.jpg', type: 'image/jpeg' }
    );

    var config = {
        method: 'post',
        url: YOUR_URL,
        headers: {
            Accept: "application/json",
            "Content-Type": "multipart/form-data",
        },
        data: data,
    };

    axios(config)
        .then((response) => {
            console.log(JSON.stringify(response.data));
        })
        .catch((error) => {
            console.log(error);
        });
}

react-native-image-picker

selectPhotoTapped() {
    const options = {
        quality: 1.0,
        maxWidth: 500,
        maxHeight: 500,
        storageOptions: {
            skipBackup: true,
        },
    };

    ImagePicker.showImagePicker(options, response => {
        //console.log('Response = ', response);

        if (response.didCancel) {
            //console.log('User cancelled photo picker');
        } else if (response.error) {
            //console.log('ImagePicker Error: ', response.error);
        } else if (response.customButton) {
            //console.log('User tapped custom button: ', response.customButton);
        } else {
            let source = { uri: response.uri };
             
            // Call Upload Function
            this.uploadS3(source.uri)

            // You can also display the image using data:
            // let source = { uri: 'data:image/jpeg;base64,' + response.data };
            this.setState({
                avatarSource: source,
            });
            // this.imageUpload(source);
        }
    });
}

Perl - Multiple condition if statement without duplicating code?

Simple:

if ( $name eq 'tom' && $password eq '123!'
    || $name eq 'frank' && $password eq '321!'
) {

(use the high-precedence && and || in expressions, reserving and and or for flow control, to avoid common precedence errors)

Better:

my %password = (
    'tom' => '123!',
    'frank' => '321!',
);

if ( exists $password{$name} && $password eq $password{$name} ) {

How to make a <ul> display in a horizontal row

Set the display property to inline for the list you want this to apply to. There's a good explanation of displaying lists on A List Apart.

How to round float numbers in javascript?

Number((6.688689).toFixed(1)); // 6.7

var number = 6.688689;
var roundedNumber = Math.round(number * 10) / 10;

Use toFixed() function.

(6.688689).toFixed(); // equal to "7"
(6.688689).toFixed(1); // equal to "6.7"
(6.688689).toFixed(2); // equal to "6.69"

How to run .sh on Windows Command Prompt?

I use Windows 10 Bash shell aka Linux Subsystem aka Ubuntu in Windows 10 as guided here

Determining if a number is prime

I follow same algorithm but different implementation that loop to sqrt(n) with step 2 only odd numbers because I check that if it is divisible by 2 or 2*k it is false. Here is my code

public class PrimeTest {

    public static boolean isPrime(int i) {
        if (i < 2) {
            return false;
        } else if (i % 2 == 0 && i != 2) {
            return false;
        } else {
            for (int j = 3; j <= Math.sqrt(i); j = j + 2) {
                if (i % j == 0) {
                    return false;
                }
            }
            return true;
        }
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        for (int i = 1; i < 100; i++) {
            if (isPrime(i)) {
                System.out.println(i);
            }
        }
    }

}

Why would anybody use C over C++?

One remark about "just use the subset of C++ you want to use": the problem with this idea is that it has a cost to enforce that everybody in the project uses the same subset. My own opinion is that those costs are quite high for loosely coupled projects (e.g. open source ones), and also that C++ totally failed at being a better C, in the sense that you cannot use C++ wherever you used C.

How to keep the spaces at the end and/or at the beginning of a String?

There is possible to space with different widths:

<string name="space_demo">|&#x20;|&#x2009;|&#x200A;||</string>

| SPACE | THIN SPACE | HAIR SPACE | no space |

Visualisation:

enter image description here

How to copy a char array in C?

You cannot assign arrays, the names are constants that cannot be changed.

You can copy the contents, with:

strcpy(array2, array1);

assuming the source is a valid string and that the destination is large enough, as in your example.

Adding Table rows Dynamically in Android

You can use an inflater with TableRow:

for (int i = 0; i < months; i++) {
    
    View view = getLayoutInflater ().inflate (R.layout.list_month_data, null, false);
        
    TextView textView = view.findViewById (R.id.title);
    
    textView.setText ("Text");
        
    tableLayout.addView (view);
    
}

Layout:

<TableRow
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:layout_centerInParent="true"
    android:gravity="center_horizontal"
    android:paddingTop="15dp"
    android:paddingRight="15dp"
    android:paddingLeft="15dp"
    android:paddingBottom="10dp"
    >
    
    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"
        android:gravity="center"
        />
    
</TableRow>

Can constructors be async?

Your problem is comparable to the creation of a file object and opening the file. In fact there are a lot of classes where you have to perform two steps before you can actually use the object: create + Initialize (often called something similar to Open).

The advantage of this is that the constructor can be lightweight. If desired, you can change some properties before actually initializing the object. When all properties are set, the Initialize/Open function is called to prepare the object to be used. This Initialize function can be async.

The disadvantage is that you have to trust the user of your class that he will call Initialize() before he uses any other function of your class. In fact if you want to make your class full proof (fool proof?) you have to check in every function that the Initialize() has been called.

The pattern to make this easier is to declare the constructor private and make a public static function that will construct the object and call Initialize() before returning the constructed object. This way you'll know that everyone who has access to the object has used the Initialize function.

The example shows a class that mimics your desired async constructor

public MyClass
{
    public static async Task<MyClass> CreateAsync(...)
    {
        MyClass x = new MyClass();
        await x.InitializeAsync(...)
        return x;
    }

    // make sure no one but the Create function can call the constructor:
    private MyClass(){}

    private async Task InitializeAsync(...)
    {
        // do the async things you wanted to do in your async constructor
    }

    public async Task<int> OtherFunctionAsync(int a, int b)
    {
        return await ... // return something useful
    }

Usage will be as follows:

public async Task<int> SomethingAsync()
{
    // Create and initialize a MyClass object
    MyClass myObject = await MyClass.CreateAsync(...);

    // use the created object:
    return await myObject.OtherFunctionAsync(4, 7);
}

Clearing all cookies with JavaScript

If you have access to the jquery.cookie plugin, you can erase all cookies this way:

for (var it in $.cookie()) $.removeCookie(it);

File path issues in R using Windows ("Hex digits in character string" error)

My Solution is to define an RStudio snippet as follows:

snippet pp
    "`r gsub("\\\\", "\\\\\\\\\\\\\\\\", readClipboard())`"

This snippet converts backslashes \ into double backslashes \\. The following version will work if you prefer to convert backslahes to forward slashes /.

snippet pp
    "`r gsub("\\\\", "/", readClipboard())`"

Once your preferred snippet is defined, paste a path from the clipboard by typing p-p-TAB-ENTER (that is pp and then the tab key and then enter) and the path will be magically inserted with R friendly delimiters.

How to declare a global variable in php?

Add your variables in $GLOBALS super global array like

$GLOBALS['variable'] = 'localhost'; 

and use it globally

or you can use constant which are accessible throughout the script

define('HOSTNAME', 'localhost');  

Oracle - How to generate script from sql developer

use the dbms_metadata package, as described here

Determine if Python is running inside virtualenv

This is an old question, but too many examples above are over-complicated.

Keep It Simple: (in Jupyter Notebook or Python 3.7.1 terminal on Windows 10)


import sys
print(sys.executable)```

# example output: >> `C:\Anaconda3\envs\quantecon\python.exe`

OR 
```sys.base_prefix```

# Example output: >> 'C:\\Anaconda3\\envs\\quantecon'

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Use Encoding.Convert to adjust the byte array before attempting to decode it into your destination encoding.

Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);
string msg = iso.GetString(isoBytes);