Programs & Examples On #Saltedhash

How to empty a char array?

Depends on what you mean by 'empty':

members[0] = '\0';

Where in an Eclipse workspace is the list of projects stored?

You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.

How to set width of a p:column in a p:dataTable in PrimeFaces 3.0?

Addition to @BalusC 's answer. You also need to set width of headers. In my case, below css can only apply to my table's column width.

.myTable td:nth-child(1),.myTable th:nth-child(1) {
   width: 20px;
}

Height equal to dynamic width (CSS fluid layout)

Extremely simple method jsfiddle

HTML

<div id="container">
    <div id="element">
        some text
    </div>
</div>

CSS

#container {
    width: 50%; /* desired width */
}

#element {
    height: 0;
    padding-bottom: 100%;
}

css background image in a different folder from css

Html file (/index.html)

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
     <link rel="stylesheet" media="screen" href="assets/css/style.css" />
</head>
<body>
     <h1>Background Image</h1>
</body>
</html>

Css file (/assets/css/style.css)

body{
    background:url(../img/bg.jpg);  
}

Send array with Ajax to PHP script

 dataString = [];
   $.ajax({
        type: "POST",
        url: "script.php",
        data:{data: $(dataString).serializeArray()}, 
        cache: false,

        success: function(){
            alert("OK");
        }
    });

http://api.jquery.com/serializeArray/

Rails 3: I want to list all paths defined in my rails application

Trying http://0.0.0.0:3000/routes on a Rails 5 API app (i.e.: JSON-only oriented) will (as of Rails beta 3) return

{"status":404,"error":"Not Found","exception":"#> 
<ActionController::RoutingError:...

However, http://0.0.0.0:3000/rails/info/routes will render a nice, simple HTML page with routes.

How to read a file line-by-line into a list?

See Input and Ouput:

with open('filename') as f:
    lines = f.readlines()

or with stripping the newline character:

with open('filename') as f:
    lines = [line.rstrip() for line in f]

How do I kill an Activity when the Back button is pressed?

First of all, finish() doesn't destroy your process and free up the memory. It just removes the activity from the activity stack. You'd need to kill the process, which is answered in a bunch of questions (since this is being asked several times).

But the proper answer is - Don't do it. the Android OS will automatically free up memory when it needs memory. By not freeing up memory, your app will start up faster if the user gets back to it.

Please see here for a great write-up on the topic.

Java 'file.delete()' Is not Deleting Specified File

As other answers indicate, on Windows you cannot delete a file that is open. However one other thing that can stop a file from being deleted on Windows is if it is is mmap'd to a MappedByteBuffer (or DirectByteBuffer) -- if so, the file cannot be deleted until the byte buffer is garbage collected. There is some relatively safe code for forcibly closing (cleaning) a DirectByteBuffer before it is garbage collected here: https://github.com/classgraph/classgraph/blob/master/src/main/java/nonapi/io/github/classgraph/utils/FileUtils.java#L606 After cleaning the ByteBuffer, you can delete the file. However, make sure you never use the ByteBuffer again after cleaning it, or the JVM will crash.

What is the difference between absolute and relative xpaths? Which is preferred in Selenium automation testing?

Absolute Xpath: It uses Complete path from the Root Element to the desire element.

Relative Xpath: You can simply start by referencing the element you want and go from there.

Relative Xpaths are always preferred as they are not the complete paths from the root element. (//html//body). Because in future, if any webelement is added/removed, then the absolute Xpath changes. So Always use Relative Xpaths in your Automation.

Below are Some Links which you can Refer for more Information on them.

Difference between datetime and timestamp in sqlserver?

According to the documentation, timestamp is a synonym for rowversion - it's automatically generated and guaranteed1 to be unique. datetime isn't - it's just a data type which handles dates and times, and can be client-specified on insert etc.


1 Assuming you use it properly, of course. See comments.

Remote Linux server to remote linux server dir copy. How?

Use rsync so that you can continue if the connection gets broken. And if something changes you can copy them much faster too!

Rsync works with SSH so your copy operation is secure.

How to do ToString for a possibly null object?

Even though this is an old question and the OP asked for C# I would like to share a VB.Net solution for those, who work with VB.Net rather than C#:

Dim myObj As Object = Nothing
Dim s As String = If(myObj, "").ToString()

myObj = 42
s = If(myObj, "").ToString()

Unfortunatly VB.Net doesn't allow the ?-operator after a variable so myObj?.ToString isn't valid (at least not in .Net 4.5, which I used for testing the solution). Instead I use the If to return an empty string in case myObj ist Nothing. So the first Tostring-Call return an an empty string, while the second (where myObj is not Nothing) returns "42".

XPath: How to select elements based on their value?

//Element[@attribute1="abc" and @attribute2="xyz" and .="Data"]

The reason why I add this answer is that I want to explain the relationship of . and text() .

The first thing is when using [], there are only two types of data:

  1. [number] to select a node from node-set
  2. [bool] to filter a node-set from node-set

In this case, the value is evaluated to boolean by function boolean(), and there is a rule:

Filters are always evaluated with respect to a context.

When you need to compare text() or . with a string "Data", it first uses string() function to transform those to string type, than gets a boolean result.

There are two important rule about string():

  1. The string() function converts a node-set to a string by returning the string value of the first node in the node-set, which in some instances may yield unexpected results.

    text() is relative path that return a node-set contains all the text node of current node(context node), like ["Data"]. When it is evaluated by string(["Data"]), it will return the first node of node-set, so you get "Data" only when there is only one text node in the node-set.

  2. If you want the string() function to concatenate all child text, you must then pass a single node instead of a node-set.

    For example, we get a node-set ['a', 'b'], you can pass there parent node to string(parent), this will return 'ab', and of cause string(.) in you case will return an concatenated string "Data".

Both way will get same result only when there is a text node.

Error "library not found for" after putting application in AdMob

I just update the pod file 'pod update' and it start to work for me normally.

How to use the ProGuard in Android Studio?

Try renaming your 'proguard-rules.txt' file to 'proguard-android.txt' and remove the reference to 'proguard-rules.txt' in your gradle file. The getDefaultProguardFile(...) call references a different default proguard file, one provided by Google and not that in your project. So remove this as well, so that here the gradle file reads:

buildTypes {
    release {
        runProguard true
        proguardFile 'proguard-android.txt'
    }
}

PHP function ssh2_connect is not working

Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

It's a ton more portable, easier to use and more feature packed too.

Angular.js programmatically setting a form field to dirty

you will have to manually set $dirty to true and $pristine to false for the field. If you want the classes to appear on your input, then you will have to manually add ng-dirty and remove ng-pristine classes from the element. You can use $setDirty() on the form level to do all of this on the form itself, but not the form inputs, form inputs do not currently have $setDirty() as you mentioned.

This answer may change in the future as they should add $setDirty() to inputs, seems logical.

Is it possible to get element from HashMap by its position?

HashMaps do not preserve ordering:

This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.

Take a look at LinkedHashMap, which guarantees a predictable iteration order.

Get value from hidden field using jQuery

var x = $('#h_v').val();
alert(x);

jQuery append() and remove() element

Since this is an open-ended question, I will just give you an idea of how I would go about implementing something like this myself.

<span class="inputname">
    Project Images:
    <a href="#" class="add_project_file">
        <img src="images/add_small.gif" border="0" />
    </a>
</span>

<ul class="project_images">
    <li><input name="upload_project_images[]" type="file" /></li>
</ul>

Wrapping the file inputs inside li elements allows to easily remove the parent of our 'remove' links when clicked. The jQuery to do so is close to what you have already:

// Add new input with associated 'remove' link when 'add' button is clicked.
$('.add_project_file').click(function(e) {
    e.preventDefault();

    $(".project_images").append(
        '<li>'
      + '<input name="upload_project_images[]" type="file" class="new_project_image" /> '
      + '<a href="#" class="remove_project_file" border="2"><img src="images/delete.gif" /></a>'
      + '</li>');
});

// Remove parent of 'remove' link when link is clicked.
$('.project_images').on('click', '.remove_project_file', function(e) {
    e.preventDefault();

    $(this).parent().remove();
});

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

I had the same issue, I could solve it by switching fom JDK 11 to JDK 8.

How do I check if a Key is pressed on C++

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget to

#include <Windows.h>

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

I was finding the same error complaining about mixing google play services version when switching from 8.3 to 8.4. Bizarrely I saw reference to the app-measurement lib which I wasn't using.

I thought maybe one of my app's dependencies was referencing the older version so I ran ./gradlew app:dependencies to find the offending library (non were).

But at the top of task output I found a error message saying that the google plugin could not be found and defaulting to google play services 8.3. I used the sample project @TheYann linked to compare. My setup was identical except I applied the apply plugin: 'com.google.gms.google-services' at the top my app's build.gradle file. I moved to bottom of the file and that fixed the gradle compile error.

Using Postman to access OAuth 2.0 Google APIs

  1. go to https://console.developers.google.com/apis/credentials
  2. create web application credentials.

Postman API Access

  1. use these settings with oauth2 in Postman:

SCOPE = https: //www.googleapis.com/auth/admin.directory.userschema

post https: //www.googleapis.com/admin/directory/v1/customer/customer-id/schemas

{
  "fields": [
    {
      "fieldName": "role",
      "fieldType": "STRING",
      "multiValued": true,
      "readAccessType": "ADMINS_AND_SELF"
    }
  ],
  "schemaName": "SAML"
}
  1. to patch user use:

SCOPE = https://www.googleapis.com/auth/admin.directory.user

PATCH https://www.googleapis.com/admin/directory/v1/users/[email protected]

 {
  "customSchemas": {
     "SAML": {
       "role": [
         {
          "value": "arn:aws:iam::123456789123:role/Admin,arn:aws:iam::123456789123:saml-provider/GoogleApps",
          "customType": "Admin"
         }
       ]
     }
   }
}

How to keep two folders automatically synchronized?

You can use inotifywait (with the modify,create,delete,move flags enabled) and rsync.

while inotifywait -r -e modify,create,delete,move /directory; do
    rsync -avz /directory /target
done

If you don't have inotifywait on your system, run sudo apt-get install inotify-tools

Content Type text/xml; charset=utf-8 was not supported by service

I had this error and all the configurations mentioned above were correct however I was still getting "The client and service bindings may be mismatched" error.

What resolved my error, was matching the messageEncoding attribute values in the following node of service and client config files. They were different in mine, service was Text and client Mtom. Changing service to Mtom to match client's, resolved the issue.

<configuration>
  <system.serviceModel>
      <bindings>
           <basicHttpBinding>
              <binding name="BasicHttpBinding_IMySevice" ... messageEncoding="Mtom">
              ...
              </binding>
           </basicHttpBinding>
      </bindings>
  </system.serviceModel>
</configuration>

Add jars to a Spark Job - spark-submit

ClassPath:

ClassPath is affected depending on what you provide. There are a couple of ways to set something on the classpath:

  • spark.driver.extraClassPath or it's alias --driver-class-path to set extra classpaths on the node running the driver.
  • spark.executor.extraClassPath to set extra class path on the Worker nodes.

If you want a certain JAR to be effected on both the Master and the Worker, you have to specify these separately in BOTH flags.

Separation character:

Following the same rules as the JVM:

  • Linux: A colon :
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar:/opt/prog/aws-java-sdk-1.10.50.jar"
  • Windows: A semicolon ;
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar;/opt/prog/aws-java-sdk-1.10.50.jar"

File distribution:

This depends on the mode which you're running your job under:

  1. Client mode - Spark fires up a Netty HTTP server which distributes the files on start up for each of the worker nodes. You can see that when you start your Spark job:

    16/05/08 17:29:12 INFO HttpFileServer: HTTP File server directory is /tmp/spark-48911afa-db63-4ffc-a298-015e8b96bc55/httpd-84ae312b-5863-4f4c-a1ea-537bfca2bc2b
    16/05/08 17:29:12 INFO HttpServer: Starting HTTP Server
    16/05/08 17:29:12 INFO Utils: Successfully started service 'HTTP file server' on port 58922.
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/foo.jar at http://***:58922/jars/com.mycode.jar with timestamp 1462728552732
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/aws-java-sdk-1.10.50.jar at http://***:58922/jars/aws-java-sdk-1.10.50.jar with timestamp 1462728552767
    
  2. Cluster mode - In cluster mode spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node. Here, Spark will not set an HTTP server. You have to manually make your JARS available to all the worker node via HDFS/S3/Other sources which are available to all nodes.

Accepted URI's for files

In "Submitting Applications", the Spark documentation does a good job of explaining the accepted prefixes for files:

When using spark-submit, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. Spark uses the following URL scheme to allow different strategies for disseminating jars:

  • file: - Absolute paths and file:/ URIs are served by the driver’s HTTP file server, and every executor pulls the file from the driver HTTP server.
  • hdfs:, http:, https:, ftp: - these pull down files and JARs from the URI as expected
  • local: - a URI starting with local:/ is expected to exist as a local file on each worker node. This means that no network IO will be incurred, and works well for large files/JARs that are pushed to each worker, or shared via NFS, GlusterFS, etc.

Note that JARs and files are copied to the working directory for each SparkContext on the executor nodes.

As noted, JARs are copied to the working directory for each Worker node. Where exactly is that? It is usually under /var/run/spark/work, you'll see them like this:

drwxr-xr-x    3 spark spark   4096 May 15 06:16 app-20160515061614-0027
drwxr-xr-x    3 spark spark   4096 May 15 07:04 app-20160515070442-0028
drwxr-xr-x    3 spark spark   4096 May 15 07:18 app-20160515071819-0029
drwxr-xr-x    3 spark spark   4096 May 15 07:38 app-20160515073852-0030
drwxr-xr-x    3 spark spark   4096 May 15 08:13 app-20160515081350-0031
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172020-0032
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172045-0033

And when you look inside, you'll see all the JARs you deployed along:

[*@*]$ cd /var/run/spark/work/app-20160508173423-0014/1/
[*@*]$ ll
total 89988
-rwxr-xr-x 1 spark spark   801117 May  8 17:34 awscala_2.10-0.5.5.jar
-rwxr-xr-x 1 spark spark 29558264 May  8 17:34 aws-java-sdk-1.10.50.jar
-rwxr-xr-x 1 spark spark 59466931 May  8 17:34 com.mycode.code.jar
-rwxr-xr-x 1 spark spark  2308517 May  8 17:34 guava-19.0.jar
-rw-r--r-- 1 spark spark      457 May  8 17:34 stderr
-rw-r--r-- 1 spark spark        0 May  8 17:34 stdout

Affected options:

The most important thing to understand is priority. If you pass any property via code, it will take precedence over any option you specify via spark-submit. This is mentioned in the Spark documentation:

Any values specified as flags or in the properties file will be passed on to the application and merged with those specified through SparkConf. Properties set directly on the SparkConf take highest precedence, then flags passed to spark-submit or spark-shell, then options in the spark-defaults.conf file

So make sure you set those values in the proper places, so you won't be surprised when one takes priority over the other.

Lets analyze each option in question:

  • --jars vs SparkContext.addJar: These are identical, only one is set through spark submit and one via code. Choose the one which suites you better. One important thing to note is that using either of these options does not add the JAR to your driver/executor classpath, you'll need to explicitly add them using the extraClassPath config on both.
  • SparkContext.addJar vs SparkContext.addFile: Use the former when you have a dependency that needs to be used with your code. Use the latter when you simply want to pass an arbitrary file around to your worker nodes, which isn't a run-time dependency in your code.
  • --conf spark.driver.extraClassPath=... or --driver-class-path: These are aliases, doesn't matter which one you choose
  • --conf spark.driver.extraLibraryPath=..., or --driver-library-path ... Same as above, aliases.
  • --conf spark.executor.extraClassPath=...: Use this when you have a dependency which can't be included in an uber JAR (for example, because there are compile time conflicts between library versions) and which you need to load at runtime.
  • --conf spark.executor.extraLibraryPath=... This is passed as the java.library.path option for the JVM. Use this when you need a library path visible to the JVM.

Would it be safe to assume that for simplicity, I can add additional application jar files using the 3 main options at the same time:

You can safely assume this only for Client mode, not Cluster mode. As I've previously said. Also, the example you gave has some redundant arguments. For example, passing JARs to --driver-library-path is useless, you need to pass them to extraClassPath if you want them to be on your classpath. Ultimately, what you want to do when you deploy external JARs on both the driver and the worker is:

spark-submit --jars additional1.jar,additional2.jar \
  --driver-class-path additional1.jar:additional2.jar \
  --conf spark.executor.extraClassPath=additional1.jar:additional2.jar \
  --class MyClass main-application.jar

List comprehension vs. lambda + filter

Since any speed difference is bound to be miniscule, whether to use filters or list comprehensions comes down to a matter of taste. In general I'm inclined to use comprehensions (which seems to agree with most other answers here), but there is one case where I prefer filter.

A very frequent use case is pulling out the values of some iterable X subject to a predicate P(x):

[x for x in X if P(x)]

but sometimes you want to apply some function to the values first:

[f(x) for x in X if P(f(x))]


As a specific example, consider

primes_cubed = [x*x*x for x in range(1000) if prime(x)]

I think this looks slightly better than using filter. But now consider

prime_cubes = [x*x*x for x in range(1000) if prime(x*x*x)]

In this case we want to filter against the post-computed value. Besides the issue of computing the cube twice (imagine a more expensive calculation), there is the issue of writing the expression twice, violating the DRY aesthetic. In this case I'd be apt to use

prime_cubes = filter(prime, [x*x*x for x in range(1000)])

How can I make one python file run another?

It may be called abc.py from the main script as below:

#!/usr/bin/python
import abc

abc.py may be something like this:

print'abc'

How do I fix the multiple-step OLE DB operation errors in SSIS?

This query should identify columns that are potential problems...

SELECT * 
FROM [source].INFORMATION_SCHEMA.COLUMNS src
    INNER JOIN [dest].INFORMATION_SCHEMA.COLUMNS dst 
        ON dst.COLUMN_NAME = src.COLUMN_NAME
WHERE dst.CHARACTER_MAXIMUM_LENGTH < src.CHARACTER_MAXIMUM_LENGTH 

Executing Shell Scripts from the OS X Dock?

If you don't need a Terminal window, you can make any executable file an Application just by creating a shell script Example and moving it to the filename Example.app/Contents/MacOS/Example. You can place this new application in your dock like any other, and execute it with a click.

NOTE: the name of the app must exactly match the script name. So the top level directory has to be Example.app and the script in the Contents/MacOS subdirectory must be named Example, and the script must be executable.

If you do need to have the terminal window displayed, I don't have a simple solution. You could probably do something with Applescript, but that's not very clean.

How to validate phone number in laravel 5.2?

You can try out this phone validator package. Laravel Phone

Update

I recently discovered another package Lavarel Phone Validator (stuyam/laravel-phone-validator), that uses the free Twilio phone lookup service

Javascript switch vs. if...else if...else

Is there a preformance difference in Javascript between a switch statement and an if...else if....else?

I don't think so, switch is useful/short if you want prevent multiple if-else conditions.

Is the behavior of switch and if...else if...else different across browsers? (FireFox, IE, Chrome, Opera, Safari)

Behavior is same across all browsers :)

How to use View.OnTouchListener instead of onClick

OnClick is triggered when the user releases the button. But if you still want to use the TouchListener you need to add it in code. It's just:

myView.setOnTouchListener(new View.OnTouchListener()
{
    // Implementation;
});

How to hash some string with sha256 in Java?

This was my approach using Kotlin:

private fun getHashFromEmailString(email : String) : String{
    val charset = Charsets.UTF_8
    val byteArray = email.toByteArray(charset)
    val digest = MessageDigest.getInstance("SHA-256")
    val hash = digest.digest(byteArray)

    return hash.fold("", { str, it -> str + "%02x".format(it)})
}

What is an Endpoint?

The term Endpoint was initially used for WCF services. Later even though this word is being used synonymous to API resources, REST recommends to call these URI (URI[s] which understand HTTP verbs and follow REST architecture) as "Resource".

In a nutshell, a Resource or Endpoint is kind of an entry point to a remotely hosted application which lets the users to communicate to it via HTTP protocol.

How to sort an array in descending order in Ruby

You could do:

a.sort{|a,b| b[:bar] <=> a[:bar]}

How do I free memory in C?

You have to free() the allocated memory in exact reverse order of how it was allocated using malloc().

Note that You should free the memory only after you are done with your usage of the allocated pointers.

memory allocation for 1D arrays:

    buffer = malloc(num_items*sizeof(double));

memory deallocation for 1D arrays:

    free(buffer);

memory allocation for 2D arrays:

    double **cross_norm=(double**)malloc(150 * sizeof(double *));
    for(i=0; i<150;i++)
    {
        cross_norm[i]=(double*)malloc(num_items*sizeof(double));
    }

memory deallocation for 2D arrays:

    for(i=0; i<150;i++)
    {
        free(cross_norm[i]);
    }

    free(cross_norm);

How do I convert a single character into it's hex ascii value in python

This might help

import binascii

x = b'test'
x = binascii.hexlify(x)
y = str(x,'ascii')

print(x) # Outputs b'74657374' (hex encoding of "test")
print(y) # Outputs 74657374

x_unhexed = binascii.unhexlify(x)
print(x_unhexed) # Outputs b'test'

x_ascii = str(x_unhexed,'ascii')
print(x_ascii) # Outputs test

This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you'd want to use is str(binascii.hexlify(c),'ascii').

Converting JSON to XLS/CSV in Java

you can use commons csv to convert into CSV format. or use POI to convert into xls. if you need helper to convert into xls, you can use jxls, it can convert java bean (or list) into excel with expression language.

Basically, the json doc maybe is a json array, right? so it will be same. the result will be list, and you just write the property that you want to display in excel format that will be read by jxls. See http://jxls.sourceforge.net/reference/collections.html

If the problem is the json can't be read in the jxls excel property, just serialize it into collection of java bean first.

Convert a double to a QString

Use QString's number method (docs are here):

double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);

MySQL Error 1215: Cannot add foreign key constraint

For others same error may not always be due to column type mismatch, you can find out more information about a mysql foriegn key error by issuing command

SHOW ENGINE INNODB STATUS;

you may find a error near the top of the printed message something like

Cannot find an index in the referenced table where the referenced columns appear as the first columns, or column types in the table and the referenced table do not match for constraint.

How do you deploy Angular apps?

I would say a lot of people with Web experience prior to angular, are use to deploying their web artifacts inside a war (i.e. jquery and html inside a Java/Spring project). I ended up doing this to get around CORS issue, after attempting to keep my angular and REST projects separate.

My solution was to move all angular (4) contents, generated with CLI, from my-app to MyJavaApplication/angular. Then I modifed my Maven build to use maven-resources-plugin to move the contents from /angular/dist to the root of my distribution (i.e. $project.build.directory}/MyJavaApplication). Angular loads resources from root of the war by default.

When I started to add routing to my angular project, I further modifed maven build to copy index.html from /dist to WEB-INF/app. And, added a Java controller that redirects all server side rest calls to index.

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

You could also do it like this, not sure if it's a good plan :D

class Parent extends Component {
  handleClick() {
    if (this._getAlert !== null) {
      this._getAlert()
    }
  }

  render() {
    return (
      <div>
        <Child>
        {(getAlert, childScope) => (
          <span> {!this._getAlert ? this._getAlert = getAlert.bind(childScope) : null}</span>
        )}
        </Child>
        <button onClick={() => this.handleClick()}> Click me</button>
      </div>
      );
    }
  }

class Child extends Component {
  constructor() {
    super();
    this.state = { count: 0 }
  }

  getAlert() {
    alert(`Child function called state: ${this.state.count}`);
    this.setState({ count: this.state.count + 1 });
  }

  render() {
    return this.props.children(this.getAlert, this)
  }
}

How can I set Image source with base64

img = new Image();
img.src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="
img.outerHTML;
"<img src="data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==">"

Input length must be multiple of 16 when decrypting with padded cipher

I know this message is old and was a long time ago - but i also had problem with with the exact same error:

the problem I had was relates to the fact the encrypted text was converted to String and to byte[] when trying to DECRYPT it.

    private Key getAesKey() throws Exception {
    return new SecretKeySpec(Arrays.copyOf(key.getBytes("UTF-8"), 16), "AES");
}

private Cipher getMutual() throws Exception {
    Cipher cipher = Cipher.getInstance("AES");
    return cipher;// cipher.doFinal(pass.getBytes());
}

public byte[] getEncryptedPass(String pass) throws Exception {
    Cipher cipher = getMutual();
    cipher.init(Cipher.ENCRYPT_MODE, getAesKey());
    byte[] encrypted = cipher.doFinal(pass.getBytes("UTF-8"));
    return encrypted;

}

public String getDecryptedPass(byte[] encrypted) throws Exception {
    Cipher cipher = getMutual();
    cipher.init(Cipher.DECRYPT_MODE, getAesKey());
    String realPass = new String(cipher.doFinal(encrypted));
    return realPass;
}

Why has it failed to load main-class manifest attribute from a JAR file?

I discovered that I was also having this error in NetBeans. I hope the following is helpful.

  1. Make sure that when you go to Project Configuration you set the main class you intend for running.
  2. Do a Build or Clean Build
  3. Place the jar file where you wish and try: java -jar "YourProject.jar" again at the command line.

This was the problem I was getting because I had other "test" programs I was using in NetBeans and I had to make sure the Main Class under the Run portion of the Project configuration was set correctly.

many blessings, John P

How to implement custom JsonConverter in JSON.NET to deserialize a List of base class objects?

Using the idea of totem and zlangner, I have created a KnownTypeConverter that will be able to determine the most appropriate inheritor, while taking into account that json data may not have optional elements.

So, the service sends a JSON response that contains an array of documents (incoming and outgoing). Documents have both a common set of elements and different ones. In this case, the elements related to the outgoing documents are optional and may be absent.

In this regard, a base class Document was created that includes a common set of properties. Two inheritor classes are also created: - OutgoingDocument adds two optional elements "device_id" and "msg_id"; - IncomingDocument adds one mandatory element "sender_id";

The task was to create a converter that based on json data and information from KnownTypeAttribute will be able to determine the most appropriate class that allows you to save the largest amount of information received. It should also be taken into account that json data may not have optional elements. To reduce the number of comparisons of json elements and properties of data models, I decided not to take into account the properties of the base class and to correlate with json elements only the properties of the inheritor classes.

Data from the service:

{
    "documents": [
        {
            "document_id": "76b7be75-f4dc-44cd-90d2-0d1959922852",
            "date": "2019-12-10 11:32:49",
            "processed_date": "2019-12-10 11:32:49",
            "sender_id": "9dedee17-e43a-47f1-910e-3a88ff6bc258",
        },
        {
            "document_id": "5044a9ac-0314-4e9a-9e0c-817531120753",
            "date": "2019-12-10 11:32:44",
            "processed_date": "2019-12-10 11:32:44",
        }
    ], 
    "total": 2
}

Data models:

/// <summary>
/// Service response model
/// </summary>
public class DocumentsRequestIdResponse
{
    [JsonProperty("documents")]
    public Document[] Documents { get; set; }

    [JsonProperty("total")]
    public int Total { get; set; }
}

// <summary>
/// Base document
/// </summary>
[JsonConverter(typeof(KnownTypeConverter))]
[KnownType(typeof(OutgoingDocument))]
[KnownType(typeof(IncomingDocument))]
public class Document
{
    [JsonProperty("document_id")]
    public Guid DocumentId { get; set; }

    [JsonProperty("date")]
    public DateTime Date { get; set; }

    [JsonProperty("processed_date")]
    public DateTime ProcessedDate { get; set; } 
}

/// <summary>
/// Outgoing document
/// </summary>
public class OutgoingDocument : Document
{
    // this property is optional and may not be present in the service's json response
    [JsonProperty("device_id")]
    public string DeviceId { get; set; }

    // this property is optional and may not be present in the service's json response
    [JsonProperty("msg_id")]
    public string MsgId { get; set; }
}

/// <summary>
/// Incoming document
/// </summary>
public class IncomingDocument : Document
{
    // this property is mandatory and is always populated by the service
    [JsonProperty("sender_sys_id")]
    public Guid SenderSysId { get; set; }
}

Converter:

public class KnownTypeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return System.Attribute.GetCustomAttributes(objectType).Any(v => v is KnownTypeAttribute);
    }

    public override bool CanWrite => false;

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        // load the object 
        JObject jObject = JObject.Load(reader);

        // take custom attributes on the type
        Attribute[] attrs = Attribute.GetCustomAttributes(objectType);

        Type mostSuitableType = null;
        int countOfMaxMatchingProperties = -1;

        // take the names of elements from json data
        HashSet<string> jObjectKeys = GetKeys(jObject);

        // take the properties of the parent class (in our case, from the Document class, which is specified in DocumentsRequestIdResponse)
        HashSet<string> objectTypeProps = objectType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Select(p => p.Name)
            .ToHashSet();

        // trying to find the right "KnownType"
        foreach (var attr in attrs.OfType<KnownTypeAttribute>())
        {
            Type knownType = attr.Type;
            if(!objectType.IsAssignableFrom(knownType))
                continue;

            // select properties of the inheritor, except properties from the parent class and properties with "ignore" attributes (in our case JsonIgnoreAttribute and XmlIgnoreAttribute)
            var notIgnoreProps = knownType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                .Where(p => !objectTypeProps.Contains(p.Name)
                            && p.CustomAttributes.All(a => a.AttributeType != typeof(JsonIgnoreAttribute) && a.AttributeType != typeof(System.Xml.Serialization.XmlIgnoreAttribute)));

            //  get serializable property names
            var jsonNameFields = notIgnoreProps.Select(prop =>
            {
                string jsonFieldName = null;
                CustomAttributeData jsonPropertyAttribute = prop.CustomAttributes.FirstOrDefault(a => a.AttributeType == typeof(JsonPropertyAttribute));
                if (jsonPropertyAttribute != null)
                {
                    // take the name of the json element from the attribute constructor
                    CustomAttributeTypedArgument argument = jsonPropertyAttribute.ConstructorArguments.FirstOrDefault();
                    if(argument != null && argument.ArgumentType == typeof(string) && !string.IsNullOrEmpty((string)argument.Value))
                        jsonFieldName = (string)argument.Value;
                }
                // otherwise, take the name of the property
                if (string.IsNullOrEmpty(jsonFieldName))
                {
                    jsonFieldName = prop.Name;
                }

                return jsonFieldName;
            });


            HashSet<string> jKnownTypeKeys = new HashSet<string>(jsonNameFields);

            // by intersecting the sets of names we determine the most suitable inheritor
            int count = jObjectKeys.Intersect(jKnownTypeKeys).Count();

            if (count == jKnownTypeKeys.Count)
            {
                mostSuitableType = knownType;
                break;
            }

            if (count > countOfMaxMatchingProperties)
            {
                countOfMaxMatchingProperties = count;
                mostSuitableType = knownType;
            }
        }

        if (mostSuitableType != null)
        {
            object target = Activator.CreateInstance(mostSuitableType);
            using (JsonReader jObjectReader = CopyReaderForObject(reader, jObject))
            {
                serializer.Populate(jObjectReader, target);
            }
            return target;
        }

        throw new SerializationException($"Could not serialize to KnownTypes and assign to base class {objectType} reference");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    private HashSet<string> GetKeys(JObject obj)
    {
        return new HashSet<string>(((IEnumerable<KeyValuePair<string, JToken>>) obj).Select(k => k.Key));
    }

    public static JsonReader CopyReaderForObject(JsonReader reader, JObject jObject)
    {
        JsonReader jObjectReader = jObject.CreateReader();
        jObjectReader.Culture = reader.Culture;
        jObjectReader.DateFormatString = reader.DateFormatString;
        jObjectReader.DateParseHandling = reader.DateParseHandling;
        jObjectReader.DateTimeZoneHandling = reader.DateTimeZoneHandling;
        jObjectReader.FloatParseHandling = reader.FloatParseHandling;
        jObjectReader.MaxDepth = reader.MaxDepth;
        jObjectReader.SupportMultipleContent = reader.SupportMultipleContent;
        return jObjectReader;
    }
}

PS: In my case, if no one inheritor has not been selected by converter (this can happen if the JSON data contains information only from the base class or the JSON data does not contain optional elements from the OutgoingDocument), then an object of the OutgoingDocument class will be created, since it is listed first in the list of KnownTypeAttribute attributes. At your request, you can vary the implementation of the KnownTypeConverter in this situation.

When do I use the PHP constant "PHP_EOL"?

I just experienced this issue when outputting to a Windows client. Sure, PHP_EOL is for server side, but most content output from php is for windows clients. So I have to place my findings here for the next person.

A) echo 'My Text' . PHP_EOL; // Bad because this just outputs \n and most versions of windows notepad display this on a single line, and most windows accounting software can't import this type of end of line character.

B) echo 'My Text \r\n'; //Bad because single quoted php strings do not interpret \r\n

C) echo "My Text \r\n"; // Yay it works! Looks correct in notepad, and works when importing the file to other windows software such as windows accounting and windows manufacturing software.

Is there a Python equivalent to Ruby's string interpolation?

For old Python (tested on 2.4) the top solution points the way. You can do this:

import string

def try_interp():
    d = 1
    f = 1.1
    s = "s"
    print string.Template("d: $d f: $f s: $s").substitute(**locals())

try_interp()

And you get

d: 1 f: 1.1 s: s

Cannot use Server.MapPath

You need to add reference (System.Web) Reference to System.Web

What is the difference between "Class.forName()" and "Class.forName().newInstance()"?

In JDBC world, the normal practice (according the JDBC API) is that you use Class#forName() to load a JDBC driver. The JDBC driver should namely register itself in DriverManager inside a static block:

package com.dbvendor.jdbc;

import java.sql.Driver;
import java.sql.DriverManager;

public class MyDriver implements Driver {

    static {
        DriverManager.registerDriver(new MyDriver());
    }

    public MyDriver() {
        //
    }

}

Invoking Class#forName() will execute all static initializers. This way the DriverManager can find the associated driver among the registered drivers by connection URL during getConnection() which roughly look like follows:

public static Connection getConnection(String url) throws SQLException {
    for (Driver driver : registeredDrivers) {
        if (driver.acceptsURL(url)) {
            return driver.connect(url);
        }
    }
    throw new SQLException("No suitable driver");
}

But there were also buggy JDBC drivers, starting with the org.gjt.mm.mysql.Driver as well known example, which incorrectly registers itself inside the Constructor instead of a static block:

package com.dbvendor.jdbc;

import java.sql.Driver;
import java.sql.DriverManager;

public class BadDriver implements Driver {

    public BadDriver() {
        DriverManager.registerDriver(this);
    }

}

The only way to get it to work dynamically is to call newInstance() afterwards! Otherwise you will face at first sight unexplainable "SQLException: no suitable driver". Once again, this is a bug in the JDBC driver, not in your own code. Nowadays, no one JDBC driver should contain this bug. So you can (and should) leave the newInstance() away.

"No cached version... available for offline mode."

Had the same error after updating Android Studio today. For me, it wasn't a matter of proxy settings:

  1. Uncheck "Offline work" in Android Studio 0.6.0:

    File->Settings->Gradle->Global Gradle Settings

    or in OSX:

    Preferences->Gradle->Global Gradle Setting

    or in more recent versions:

    File->Settings->Build, Execution, Deployment->Build tools->Gradle

  2. Resync the project, for example by restarting the Android Studio

  3. Once synced, you can check the option again to work offline.

(Only tested in Gradle version 0.11... and Android Studio version 0.6.0 Preview)

EDIT : Added paths for different versions/platforms (as mentioned by John Ballinger and The_Martian). Not yet verified.

Split function equivalent in T-SQL?

DECLARE
    @InputString NVARCHAR(MAX) = 'token1,token2,token3,token4,token5'
    , @delimiter varchar(10) = ','

DECLARE @xml AS XML = CAST(('<X>'+REPLACE(@InputString,@delimiter ,'</X><X>')+'</X>') AS XML)
SELECT C.value('.', 'varchar(10)') AS value
FROM @xml.nodes('X') as X(C)

Source of this response: http://sqlhint.com/sqlserver/how-to/best-split-function-tsql-delimited

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

Add this before you call method invoke:

while (!this.IsHandleCreated) 
   System.Threading.Thread.Sleep(100)

jQuery autoComplete view all on click?

I guess a better option is to put $("#idname").autocomplete( "search", "" ); into the onclick paramter of the text box . Since on select, a focus is put in by jquery , this can be a workaround . Dont know if it should be an acceptable solution.

Selenium Webdriver: Entering text into text field

Use this code.

driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");

jQuery show for 5 seconds then hide

Just as simple as this:

$("#myElem").show("slow").delay(5000).hide("slow");

Leave menu bar fixed on top when scrolled

This is jquery code which is used to fixed the div when it touch a top of browser hope it will help a lot.

<script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
<script type='text/javascript'>//<![CDATA[ 
$(window).load(function(){
$(function() {
    $.fn.scrollBottom = function() {
        return $(document).height() - this.scrollTop() - this.height();
    };

    var $el = $('#sidebar>div');
    var $window = $(window);
    var top = $el.parent().position().top;

    $window.bind("scroll resize", function() {
        var gap = $window.height() - $el.height() - 10;
        var visibleFoot = 172 - $window.scrollBottom();
        var scrollTop = $window.scrollTop()

        if (scrollTop < top + 10) {
            $el.css({
                top: (top - scrollTop) + "px",
                bottom: "auto"
            });
        } else if (visibleFoot > gap) {
            $el.css({
                top: "auto",
                bottom: visibleFoot + "px"
            });
        } else {
            $el.css({
                top: 0,
                bottom: "auto"
            });
        }
    }).scroll();
});
});//]]>  

</script>

Location of the android sdk has not been setup in the preferences in mac os?

i was facing the same problem. the solution is...Copy the link http://dl-ssl.google.com/android/eclipse/ then in eclipse go to

Help > Install New Software > Add(work with) > past the link on locations > ok > select all > next

this will solve your problem.

how do I create an infinite loop in JavaScript

You can also use a while loop:

while (true) {
    //your code
}

Object Required Error in excel VBA

In order to set the value of integer variable we simply assign the value to it. eg g1val = 0 where as set keyword is used to assign value to object.

Sub test()

Dim g1val, g2val As Integer

  g1val = 0
  g2val = 0

    For i = 3 To 18

     If g1val > Cells(33, i).Value Then
        g1val = g1val
    Else
       g1val = Cells(33, i).Value
     End If

    Next i

    For j = 32 To 57
        If g2val > Cells(31, j).Value Then
           g2val = g2val
        Else
          g2val = Cells(31, j).Value
        End If
    Next j

End Sub

MySQL Data Source not appearing in Visual Studio

I tried to install to VS 2015 using the Web installer. It seemed to work, but there was still no MySQL entry for Data Connections. I ended up going to http://dev.mysql.com/downloads/windows/visualstudio/, using it to uninstall then re-install the connector. Not it works as expected.

Change Title of Javascript Alert

As others have said, you can't do that either using alert()or confirm().

You can, however, create an external HTML document containing your error message and an OK button, set its <title> element to whatever you want, then display it in a modal dialog box using showModalDialog().

Using IF ELSE statement based on Count to execute different Insert statements

There are many, many ways to code this, but here is one possible way. I'm assuming MS SQL

We'll start by getting row count (Another Quick Example) and then do if/else

-- Let's get our row count and assign it to a var that will be used
--    in our if stmt 
DECLARE @HasExistingRows int -- I'm assuming it can fit into an int
SELECT @HasExistingRows = Count(*) 
   ELSE 0 -- false
FROM
   INCIDENTS
WHERE {Your Criteria}
GROUP BY {Required Grouping}

Now we can do the If / Else Logic MSDN Docs

-- IF / Else / Begin / END Syntax
IF @HasExistingRows = 0 -- No Existing Rows
   BEGIN
      {Insert Logic for No Existing Rows}
   END
ELSE -- existing rows are found
   BEGIN
      {Insert logic for existing rows}
   END

Another faster way (inspired by Mahmoud Gamal's comment):

Forget the whole variable creation / assignment - look up "EXISTS" - MSDN Docs 2.

IF EXISTS ({SELECT Query})
   BEGIN
      {INSERT Version 1}
   END
ELSE
   BEGIN
      {INSERT version 2}
   END

How can I see which Git branches are tracking which remote / upstream branch?

In case anyone's reading this and wanting to protect master with client-side branch protection,

git branch -vv | grep "^\*" |grep -E '\* master |origin\/master'

will return 0 if either the local checked-out branch or its upstream remote branch is master.

Just put this in your .git/hooks directory's pre-commit and update files accordingly and Bob is your father's brother.

Where is localhost folder located in Mac or Mac OS X?

For posterity

I never use PHP so I completely forgot where apache was installed on my mac as it was running on port 8080 mocking me, installed in a non-standard path. After giving up on the internet, I tried this...

httpd -t -D DUMP_INCLUDES

Because httpd was running it produced the httpd.config path and then the clouds parted and the sun shown brightly on my face. Victory! as within it lies the path to localhost.

ServerRoot "/your/path"

Java Replace Line In Text File

At the bottom, I have a general solution to replace lines in a file. But first, here is the answer to the specific question at hand. Helper function:

public static void replaceSelected(String replaceWith, String type) {
    try {
        // input the file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();
        String inputStr = inputBuffer.toString();

        System.out.println(inputStr); // display the original file for debugging

        // logic to replace lines in the string (could use regex here to be generic)
        if (type.equals("0")) {
            inputStr = inputStr.replace(replaceWith + "1", replaceWith + "0"); 
        } else if (type.equals("1")) {
            inputStr = inputStr.replace(replaceWith + "0", replaceWith + "1");
        }

        // display the new file for debugging
        System.out.println("----------------------------------\n" + inputStr);

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputStr.getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

Then call it:

public static void main(String[] args) {
    replaceSelected("Do the dishes", "1");   
}

Original Text File Content:

Do the dishes0
Feed the dog0
Cleaned my room1

Output:

Do the dishes0
Feed the dog0
Cleaned my room1
----------------------------------
Do the dishes1
Feed the dog0
Cleaned my room1

New text file content:

Do the dishes1
Feed the dog0
Cleaned my room1


And as a note, if the text file was:

Do the dishes1
Feed the dog0
Cleaned my room1

and you used the method replaceSelected("Do the dishes", "1");, it would just not change the file.


Since this question is pretty specific, I'll add a more general solution here for future readers (based on the title).

// read file one line at a time
// replace line as you read the file and store updated lines in StringBuffer
// overwrite the file with the new lines
public static void replaceLines() {
    try {
        // input the (modified) file content to the StringBuffer "input"
        BufferedReader file = new BufferedReader(new FileReader("notes.txt"));
        StringBuffer inputBuffer = new StringBuffer();
        String line;

        while ((line = file.readLine()) != null) {
            line = ... // replace the line here
            inputBuffer.append(line);
            inputBuffer.append('\n');
        }
        file.close();

        // write the new string with the replaced line OVER the same file
        FileOutputStream fileOut = new FileOutputStream("notes.txt");
        fileOut.write(inputBuffer.toString().getBytes());
        fileOut.close();

    } catch (Exception e) {
        System.out.println("Problem reading file.");
    }
}

uppercase first character in a variable with bash

This one worked for me:

Searching for all *php file in the current directory , and replace the first character of each filename to capital letter:

e.g: test.php => Test.php

for f in *php ; do mv "$f" "$(\sed 's/.*/\u&/' <<< "$f")" ; done

How do you modify the web.config appSettings at runtime?

Try This:

using System;
using System.Configuration;
using System.Web.Configuration;

namespace SampleApplication.WebConfig
{
    public partial class webConfigFile : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Helps to open the Root level web.config file.
            Configuration webConfigApp = WebConfigurationManager.OpenWebConfiguration("~");
            //Modifying the AppKey from AppValue to AppValue1
            webConfigApp.AppSettings.Settings["ConnectionString"].Value = "ConnectionString";
            //Save the Modified settings of AppSettings.
            webConfigApp.Save();
        }
    }
}

Understanding the difference between Object.create() and new SomeFunction()

Accordingly to this answer and to this video new keyword does next things:

  1. Creates new object.

  2. Links new object to constructor function (prototype).

  3. Makes this variable point to the new object.

  4. Executes constructor function using the new object and implicit perform return this;

  5. Assigns constructor function name to new object's property constructor.

Object.create performs only 1st and 2nd steps!!!

How do you convert a jQuery object into a string?

It may be possible to use the jQuery.makeArray(obj) utility function:

var obj = $('<p />',{'class':'className'}).html('peekaboo');
var objArr = $.makeArray(obj);
var plainText = objArr[0];

How to get div height to auto-adjust to background size?

I would do the reverse and place the image inside of the main div with a width of 100%, which will make both the div and image responsive to screen size,

Then add the content within an absolute positioned div with width and height of 100% inside of the main div.

<div class="main" style="position: relative; width: 100%;">
    <img src="your_image.png" style="width: 100%;">
    <div style="position: absolute; width: 100%; height: 100%; display: flex...">
            YOUR CONTENT
    </div>
</div>

Associative arrays in Shell scripts

To add to Irfan's answer, here is a shorter and faster version of get() since it requires no iteration over the map contents:

get() {
    mapName=$1; key=$2

    map=${!mapName}
    value="$(echo $map |sed -e "s/.*--${key}=\([^ ]*\).*/\1/" -e 's/:SP:/ /g' )"
}

Convert datetime to valid JavaScript date

This works everywhere including Safari 5 and Firefox 5 on OS X.

UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below

_x000D_
_x000D_
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));_x000D_
console.log(date_test);
_x000D_
_x000D_
_x000D_


FIDDLE

jQuery: Test if checkbox is NOT checked

I know this has already been answered, but still, this is a good way to do it:

if ($("#checkbox").is(":checked")==false) {
    //Do stuff here like: $(".span").html("<span>Lorem</span>");
}

LINQ: combining join and group by

Once you've done this

group p by p.SomeId into pg  

you no longer have access to the range variables used in the initial from. That is, you can no longer talk about p or bp, you can only talk about pg.

Now, pg is a group and so contains more than one product. All the products in a given pg group have the same SomeId (since that's what you grouped by), but I don't know if that means they all have the same BaseProductId.

To get a base product name, you have to pick a particular product in the pg group (As you are doing with SomeId and CountryCode), and then join to BaseProducts.

var result = from p in Products                         
 group p by p.SomeId into pg                         
 // join *after* group
 join bp in BaseProducts on pg.FirstOrDefault().BaseProductId equals bp.Id         
 select new ProductPriceMinMax { 
       SomeId = pg.FirstOrDefault().SomeId, 
       CountryCode = pg.FirstOrDefault().CountryCode, 
       MinPrice = pg.Min(m => m.Price), 
       MaxPrice = pg.Max(m => m.Price),
       BaseProductName = bp.Name  // now there is a 'bp' in scope
 };

That said, this looks pretty unusual and I think you should step back and consider what you are actually trying to retrieve.

Importing json file in TypeScript

Often in Node.js applications a .json is needed. With TypeScript 2.9, --resolveJsonModule allows for importing, extracting types from and generating .json files.

Example #

_x000D_
_x000D_
// tsconfig.json_x000D_
_x000D_
{_x000D_
    "compilerOptions": {_x000D_
        "module": "commonjs",_x000D_
        "resolveJsonModule": true,_x000D_
        "esModuleInterop": true_x000D_
    }_x000D_
}_x000D_
_x000D_
// .ts_x000D_
_x000D_
import settings from "./settings.json";_x000D_
_x000D_
settings.debug === true;  // OK_x000D_
settings.dry === 2;  // Error: Operator '===' cannot be applied boolean and number_x000D_
_x000D_
_x000D_
// settings.json_x000D_
_x000D_
{_x000D_
    "repo": "TypeScript",_x000D_
    "dry": false,_x000D_
    "debug": false_x000D_
}
_x000D_
_x000D_
_x000D_ by: https://www.typescriptlang.org/docs/handbook/release-notes/typescript-2-9.html

What is the difference between function and procedure in PL/SQL?

In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.

Get checkbox list values with jQuery

var aArray = [];
window.$( "#myDiv" ).find( "input[type=checkbox][checked]" ).each( function()
{
  aArray.push( this.name );

});

You can put it in a function and execute on click of the button.

String to list in Python

Here the simples

a = [x for x in 'abcdefgh'] #['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Android: alternate layout xml for landscape mode

The layouts in /res/layout are applied to both portrait and landscape, unless you specify otherwise. Let’s assume we have /res/layout/home.xml for our homepage and we want it to look differently in the 2 layout types.

  1. create folder /res/layout-land (here you will keep your landscape adjusted layouts)
  2. copy home.xml there
  3. make necessary changes to it

Source

"document.getElementByClass is not a function"

Before jumping into any further error checking please first check whether its

document.getElementsByClassName() itself.

double check its getElements and not getElement

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

Another possible solution to this error that I found. Might not have answered OP's exact question but may help others who stumble across this error message.

I was creating my Client in code using WebHttpBinding, in order to replicate the following line:

<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Windows" proxyCredentialType="Windows" />
</security>

I had to do:

var binding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Windows;

as well as setting proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

Label word wrapping

You can use a TextBox and set multiline to true and canEdit to false .

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means you have a null reference somewhere in there. Can you debug the app and stop the debugger when it gets here and investigate? Probably img1 is null or ConfigurationManager.AppSettings.Get("Url") is returning null.

Looping through JSON with node.js

Not sure if it helps, but it looks like there might be a library for async iteration in node hosted here:

https://github.com/caolan/async

Async is a utility module which provides straight-forward, powerful functions for working with asynchronous JavaScript. Although originally designed for use with node.js, it can also be used directly in the browser.

Async provides around 20 functions that include the usual 'functional' suspects (map, reduce, filter, forEach…) as well as some common patterns for asynchronous control flow (parallel, series, waterfall…). All these functions assume you follow the node.js convention of providing a single callback as the last argument of your async function.

How can I find a specific file from a Linux terminal?

The below line of code would do it for you.

find / -name index.html

However, on most Linux servers, your files will be located in /var/www or in your user directory folder /home/(user) depending on how you have it set up. If you're using a control panel, most likely it'll be under your user folder.

jQuery multiple conditions within if statement

Try

if (!(i == 'InvKey' || i == 'PostDate')) {

or

if (i != 'InvKey' || i != 'PostDate') {

that says if i does not equals InvKey OR PostDate

How can I get the file name from request.FILES?

request.FILES['filename'].name

From the request documentation.

If you don't know the key, you can iterate over the files:

for filename, file in request.FILES.iteritems():
    name = request.FILES[filename].name

How do I format date in jQuery datetimepicker?

You can use the format option, as described in the documentation

$("#timePicker").datetimepicker({
  format: 'Y-m-d H:i'
});

Best lightweight web server (only static content) for Windows

Have a look at Cassini. This is basically what Visual Studio uses for its built-in debug web server. I've used it with Umbraco and it seems quite good.

Best practice for partial updates in a RESTful service

You basically have two options:

  1. Use PATCH (but note that you have to define your own media type that specifies what will happen exactly)

  2. Use POST to a sub resource and return 303 See Other with the Location header pointing to the main resource. The intention of the 303 is to tell the client: "I have performed your POST and the effect was that some other resource was updated. See Location header for which resource that was." POST/303 is intended for iterative additions to a resources to build up the state of some main resource and it is a perfect fit for partial updates.

CSS force new line

or you can use:

a {
    display: inline-block;
  }

Convert a List<T> into an ObservableCollection<T>

ObservableCollection < T > has a constructor overload which takes IEnumerable < T >

Example for a List of int:

ObservableCollection<int> myCollection = new ObservableCollection<int>(myList);

One more example for a List of ObjectA:

ObservableCollection<ObjectA> myCollection = new ObservableCollection<ObjectA>(myList as List<ObjectA>);

How do I calculate someone's age based on a DateTime type birthday?

This is one of the most accurate answers that is able to resolve the birthday of 29th of Feb compared to any year of 28th Feb.

public int GetAge(DateTime birthDate)
{
    int age = DateTime.Now.Year - birthDate.Year;

    if (birthDate.DayOfYear > DateTime.Now.DayOfYear)
        age--;

    return age;
}




Handle spring security authentication exceptions with @ExceptionHandler

In ResourceServerConfigurerAdapter class, below code snipped worked for me. http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler()).and.csrf().. did not work. That's why I wrote it as separate call.

public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Override
    public void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling().authenticationEntryPoint(new AuthFailureHandler());

        http.csrf().disable()
                .anonymous().disable()
                .authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                .antMatchers("/subscribers/**").authenticated()
                .antMatchers("/requests/**").authenticated();
    }

Implementation of AuthenticationEntryPoint for catching token expiry and missing authorization header.


public class AuthFailureHandler implements AuthenticationEntryPoint {

  @Override
  public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e)
      throws IOException, ServletException {
    httpServletResponse.setContentType("application/json");
    httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

    if( e instanceof InsufficientAuthenticationException) {

      if( e.getCause() instanceof InvalidTokenException ){
        httpServletResponse.getOutputStream().println(
            "{ "
                + "\"message\": \"Token has expired\","
                + "\"type\": \"Unauthorized\","
                + "\"status\": 401"
                + "}");
      }
    }
    if( e instanceof AuthenticationCredentialsNotFoundException) {

      httpServletResponse.getOutputStream().println(
          "{ "
              + "\"message\": \"Missing Authorization Header\","
              + "\"type\": \"Unauthorized\","
              + "\"status\": 401"
              + "}");
    }

  }
}

SQL Server SELECT into existing table

If the destination table does exist but you don't want to specify column names:

DECLARE @COLUMN_LIST NVARCHAR(MAX);
DECLARE @SQL_INSERT NVARCHAR(MAX);

SET @COLUMN_LIST = (SELECT DISTINCT
    SUBSTRING(
        (
            SELECT ', table1.' + SYSCOL1.name  AS [text()]
            FROM sys.columns SYSCOL1
            WHERE SYSCOL1.object_id = SYSCOL2.object_id and SYSCOL1.is_identity <> 1
            ORDER BY SYSCOL1.object_id
            FOR XML PATH ('')
        ), 2, 1000)
FROM
    sys.columns SYSCOL2
WHERE
    SYSCOL2.object_id = object_id('dbo.TableOne') )

SET @SQL_INSERT =  'INSERT INTO dbo.TableTwo SELECT ' + @COLUMN_LIST + ' FROM dbo.TableOne table1 WHERE col3 LIKE ' + @search_key
EXEC sp_executesql @SQL_INSERT

Include php files when they are in different folders

If I understand you correctly, You have two folders, one houses your php script that you want to include into a file that is in another folder?

If this is the case, you just have to follow the trail the right way. Let's assume your folders are set up like this:

root
    includes
        php_scripts
            script.php
    blog
        content
            index.php

If this is the proposed folder structure, and you are trying to include the "Script.php" file into your "index.php" folder, you need to include it this way:

include("../../../includes/php_scripts/script.php");

The way I do it is visual. I put my mouse pointer on the index.php (looking at the file structure), then every time I go UP a folder, I type another "../" Then you have to make sure you go UP the folder structure ABOVE the folders that you want to start going DOWN into. After that, it's just normal folder hierarchy.

Multiple separate IF conditions in SQL Server

To avoid syntax errors, be sure to always put BEGIN and END after an IF clause, eg:

IF (@A!= @SA)
   BEGIN
   --do stuff
   END
IF (@C!= @SC)
   BEGIN
   --do stuff
   END

... and so on. This should work as expected. Imagine BEGIN and END keyword as the opening and closing bracket, respectively.

Take multiple lists into dataframe

There are several ways to create a dataframe from multiple lists.

list1=[1,2,3,4]
list2=[5,6,7,8]
list3=[9,10,11,12]
  1. pd.DataFrame({'list1':list1, 'list2':list2, 'list3'=list3})

  2. pd.DataFrame(data=zip(list1,list2,list3),columns=['list1','list2','list3'])

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

@Eddie has given a perfect answer of the question asked. But I would like to draw attention to using an more efficient approach of Pub/Sub.

As this answer suggests,

The $broadcast/$on approach is not terribly efficient as it broadcasts to all the scopes(Either in one direction or both direction of Scope hierarchy). While the Pub/Sub approach is much more direct. Only subscribers get the events, so it isn't going to every scope in the system to make it work.

you can use angular-PubSub angular module. once you add PubSub module to your app dependency, you can use PubSub service to subscribe and unsubscribe events/topics.

Easy to subscribe:

// Subscribe to event
var sub = PubSub.subscribe('event-name', function(topic, data){
    
});

Easy to publish

PubSub.publish('event-name', {
    prop1: value1,
    prop2: value2
});

To unsubscribe, use PubSub.unsubscribe(sub); OR PubSub.unsubscribe('event-name');.

NOTE Don't forget to unsubscribe to avoid memory leaks.

ReactJS - Call One Component Method From Another Component

Well, actually, React is not suitable for calling child methods from the parent. Some frameworks, like Cycle.js, allow easily access data both from parent and child, and react to it.

Also, there is a good chance you don't really need it. Consider calling it into existing component, it is much more independent solution. But sometimes you still need it, and then you have few choices:

  • Pass method down, if it is a child (the easiest one, and it is one of the passed properties)
  • add events library; in React ecosystem Flux approach is the most known, with Redux library. You separate all events into separated state and actions, and dispatch them from components
  • if you need to use function from the child in a parent component, you can wrap in a third component, and clone parent with augmented props.

UPD: if you need to share some functionality which doesn't involve any state (like static functions in OOP), then there is no need to contain it inside components. Just declare it separately and invoke when need:

let counter = 0;
function handleInstantiate() {
   counter++;
}

constructor(props) {
   super(props);
   handleInstantiate();
}

Change the Bootstrap Modal effect

If you take a look at the bootstraps fade class used with the modal window you will find, that all it does, is to set the opacity value to 0 and adds a transition for the opacity rule.

Whenever you launch a modal the in class is added and will change the opacity to a value of 1.

Knowing that you can easily build your own fade-scale class.

Here is an example.

_x000D_
_x000D_
@import url("https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css");_x000D_
_x000D_
.fade-scale {_x000D_
  transform: scale(0);_x000D_
  opacity: 0;_x000D_
  -webkit-transition: all .25s linear;_x000D_
  -o-transition: all .25s linear;_x000D_
  transition: all .25s linear;_x000D_
}_x000D_
_x000D_
.fade-scale.in {_x000D_
  opacity: 1;_x000D_
  transform: scale(1);_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- Button trigger modal -->_x000D_
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">_x000D_
  Launch demo modal_x000D_
</button>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal fade-scale" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        ..._x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>_x000D_
        <button type="button" class="btn btn-primary">Save changes</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

-- UPDATE --

This answer is getting more up votes lately so i figured i add an update to show how easy it is to customize the BS modal in and out animations with the help of the great Animate.css library by
Daniel Eden.

All that needs to be done is to include the stylesheet to your <head></head> section. Now you simply need to add the animated class, plus one of the entrance classes of the library to the modal element.

<div class="modal animated fadeIn" id="myModal" tabindex="-1" role="dialog" ...>
  ...
</div>

But there is also a way to add an out animation to the modal window and since the library has a bunch of cool animations that will make an element disappear, why not use them. :)

To use them you will need to toggle the classes on the modal element, so it is actually better to call the modal window via JavaScript, which is described here.

You will also need to listen for some of the modal events to know when it's time to add or remove the classes from the modal element. The events being fired are described here.

To trigger a custom out animation you can't use the data-dismiss="modal" attribute on a button inside the modal window that's suppose to close the modal. You can simply add your own attribute like data-custom-dismiss="modal" and use that to call the $('selector').modal.('hide') method on it.

Here is an example that shows all the different possibilities.

_x000D_
_x000D_
/* -------------------------------------------------------_x000D_
| This first part can be ignored, it is just getting_x000D_
| all the different entrance and exit classes of the_x000D_
| animate-config.json file from the github repo._x000D_
--------------------------------------------------------- */_x000D_
_x000D_
var animCssConfURL = 'https://api.github.com/repos/daneden/animate.css/contents/animate-config.json';_x000D_
var selectIn = $('#animation-in-types');_x000D_
var selectOut = $('#animation-out-types');_x000D_
var getAnimCSSConfig = function ( url ) { return $.ajax( { url: url, type: 'get', dataType: 'json' } ) };_x000D_
var decode = function ( data ) {_x000D_
  var bin = Uint8Array.from( atob( data['content'] ), function( char ) { return char.charCodeAt( 0 ) } );_x000D_
  var bin2Str = String.fromCharCode.apply( null, bin );_x000D_
  return JSON.parse( bin2Str )_x000D_
}_x000D_
var buildSelect = function ( which, name, animGrp ) {_x000D_
  var grp = $('<optgroup></optgroup>');_x000D_
  grp.attr('label', name);_x000D_
  $.each(animGrp, function ( idx, animType ) {_x000D_
    var opt = $('<option></option>')_x000D_
    opt.attr('value', idx)_x000D_
    opt.text(idx)_x000D_
    grp.append(opt);_x000D_
  })_x000D_
  which.append(grp) _x000D_
}_x000D_
getAnimCSSConfig( animCssConfURL )_x000D_
  .done (function ( data ) {_x000D_
  var animCssConf = decode ( data );_x000D_
  $.each(animCssConf, function(name, animGrp) {_x000D_
    if ( /_entrances/.test(name) ) {_x000D_
      buildSelect(selectIn, name, animGrp);_x000D_
    }_x000D_
    if ( /_exits/.test(name) ) {_x000D_
      buildSelect(selectOut, name, animGrp);_x000D_
    }_x000D_
  })_x000D_
})_x000D_
_x000D_
_x000D_
/* -------------------------------------------------------_x000D_
| Here is were the fun begins._x000D_
--------------------------------------------------------- */_x000D_
_x000D_
var modalBtn = $('button');_x000D_
var modal = $('#myModal');_x000D_
var animInClass = "";_x000D_
var animOutClass = "";_x000D_
_x000D_
modalBtn.on('click', function() {_x000D_
  animInClass = selectIn.find('option:selected').val();_x000D_
  animOutClass = selectOut.find('option:selected').val();_x000D_
  if ( animInClass == '' || animOutClass == '' ) {_x000D_
    alert("Please select an in and out animation type.");_x000D_
  } else {_x000D_
    modal.addClass(animInClass);_x000D_
    modal.modal({backdrop: false});_x000D_
  }_x000D_
})_x000D_
_x000D_
modal.on('show.bs.modal', function () {_x000D_
  var closeModalBtns = modal.find('button[data-custom-dismiss="modal"]');_x000D_
  closeModalBtns.one('click', function() {_x000D_
    modal.on('webkitAnimationEnd oanimationend msAnimationEnd animationend', function( evt ) {_x000D_
      modal.modal('hide')_x000D_
    });_x000D_
    modal.removeClass(animInClass).addClass(animOutClass);_x000D_
  })_x000D_
})_x000D_
_x000D_
modal.on('hidden.bs.modal', function ( evt ) {_x000D_
  var closeModalBtns = modal.find('button[data-custom-dismiss="modal"]');_x000D_
  modal.removeClass(animOutClass)_x000D_
  modal.off('webkitAnimationEnd oanimationend msAnimationEnd animationend')_x000D_
  closeModalBtns.off('click')_x000D_
})
_x000D_
@import url('https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css');_x000D_
@import url('https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.css');_x000D_
_x000D_
select, button:not([data-custom-dismiss="modal"]) {_x000D_
  margin: 10px 0;_x000D_
  width: 220px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <select id="animation-in-types">_x000D_
        <option value="" selected>Choose animation-in type</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <select id="animation-out-types">_x000D_
        <option value="" selected>Choose animation-out type</option>_x000D_
      </select>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-xs-4 col-xs-offset-4 col-sm-4 col-sm-offset-4">_x000D_
      <button class="btn btn-default">Open Modal</button>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<!-- Modal -->_x000D_
<div class="modal animated" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">_x000D_
  <div class="modal-dialog" role="document">_x000D_
    <div class="modal-content">_x000D_
      <div class="modal-header">_x000D_
        <button type="button" class="close" data-custom-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>_x000D_
        <h4 class="modal-title" id="myModalLabel">Modal title</h4>_x000D_
      </div>_x000D_
      <div class="modal-body">_x000D_
        ..._x000D_
      </div>_x000D_
      <div class="modal-footer">_x000D_
        <button type="button" class="btn btn-default" data-custom-dismiss="modal">Close</button>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

jquery/javascript convert date string to date

I used the javascript date funtion toLocaleDateString to get

var Today = new Date();
var r = Today.toLocaleDateString();

The result of r will be

11/29/2016

More info at: http://www.w3schools.com/jsref/jsref_tolocaledatestring.asp

Stop setInterval

You have to assign the returned value of the setInterval function to a variable

var interval;
$(document).on('ready',function(){
    interval = setInterval(updateDiv,3000);
});

and then use clearInterval(interval) to clear it again.

JQuery $.ajax() post - data in a java servlet

You don't want a string, you really want a JS map of key value pairs. E.g., change:

 data: myDataVar.toString(),

with:

var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }



var saveData = $.ajax({
      type: 'POST',
      url: "someaction.do?action=saveData",
      data: myKeyVals,
      dataType: "text",
      success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });

jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.

UPDATE: Code fixed.

How to make a HTML Page in A4 paper size page(s)?

I have used 680px in commercial reports to print on A4 pages since 1998. The 700px could not fit correctly depend of size of margins. Modern browsers can shrink page to fit page on printer, but if you use 680 pixels you will print correctly in almost any browsers.

That is HTML to you Run code snippet and see de result:

_x000D_
_x000D_
window.print();
_x000D_
<table width=680 border=1 cellpadding=20 cellspacing=0>_x000D_
<tr><th>#</th><th>name</th></tr>_x000D_
<tr align=center><td>1</td><td>DONALD TRUMP</td></tr>_x000D_
<tr align=center><td>2</td><td>BARACK OBAMA</td></tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JSFiddle:

https://jsfiddle.net/ajofmm7r/

How to get the server path to the web directory in Symfony2 from inside the controller?

To access the root directory from outside the controller you can simply inject %kernel.root_dir% as an argument in your services configuration.

service_name:
    class: Namespace\Bundle\etc
    arguments: ['%kernel.root_dir%']

Then you can get the web root in the class constructor:

public function __construct($rootDir)
{
    $this->webRoot = realpath($rootDir . '/../web');
}

How to make a transparent HTML button?

**add the icon top button like this **

_x000D_
_x000D_
#copy_btn{_x000D_
 align-items: center;_x000D_
 position: absolute;_x000D_
 width: 30px;_x000D_
  height: 30px;_x000D_
     background-color: Transparent;_x000D_
    background-repeat:no-repeat;_x000D_
    border: none;_x000D_
    cursor:pointer;_x000D_
    overflow: hidden;_x000D_
    outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
 position: absolute;_x000D_
 padding: 0px;_x000D_
 top:0;_x000D_
 left: 0;_x000D_
width: 25px;_x000D_
  height: 35px;_x000D_
  _x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
                        <img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
_x000D_
_x000D_

disable textbox using jquery?

I'm not sure why some of these solutions use .each() - it's not necessary.

Here's some working code that disables if the 3rd checkbox is clicked, otherwise is removes the disabled attribute.

Note: I added an id to the checkbox. Also, remember that ids must be unique in your document, so either remove the ids on the radiobuttons, or make them unique

$("input:radio[name='userradiobtn']").click(function() {
    var isDisabled = $(this).is(":checked") && $(this).val() == "3";
    $("#chkbox").attr("disabled", isDisabled);
    $("#usertxtbox").attr("disabled", isDisabled);
});

Is there a way to take a screenshot using Java and save it to some sort of image?

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File; 
import javax.imageio.ImageIO;
import javax.swing.*;  

public class HelloWorldFrame extends JFrame implements ActionListener {

JButton b;
public HelloWorldFrame() {
    this.setVisible(true);
    this.setLayout(null);
    b = new JButton("Click Here");
    b.setBounds(380, 290, 120, 60);
    b.setBackground(Color.red);
    b.setVisible(true);
    b.addActionListener(this);
    add(b);
    setSize(1000, 700);
}
public void actionPerformed(ActionEvent e)
{
    if (e.getSource() == b) 
    {
        this.dispose();
        try {
            Thread.sleep(1000);
            Toolkit tk = Toolkit.getDefaultToolkit(); 
            Dimension d = tk.getScreenSize();
            Rectangle rec = new Rectangle(0, 0, d.width, d.height);  
            Robot ro = new Robot();
            BufferedImage img = ro.createScreenCapture(rec);
            File f = new File("myimage.jpg");//set appropriate path
            ImageIO.write(img, "jpg", f);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

public static void main(String[] args) {
    HelloWorldFrame obj = new HelloWorldFrame();
}
}

Detect Android phone via Javascript / jQuery

Take a look at that : http://davidwalsh.name/detect-android

JavaScript:

var ua = navigator.userAgent.toLowerCase();
var isAndroid = ua.indexOf("android") > -1; //&& ua.indexOf("mobile");
if(isAndroid) {
  // Do something!
  // Redirect to Android-site?
  window.location = 'http://android.davidwalsh.name';
}

PHP:

$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if(stripos($ua,'android') !== false) { // && stripos($ua,'mobile') !== false) {
  header('Location: http://android.davidwalsh.name');
  exit();
}

Edit : As pointed out in some comments, this will work in 99% of the cases, but some edge cases are not covered. If you need a much more advanced and bulletproofed solution in JS, you should use platform.js : https://github.com/bestiejs/platform.js

Casting objects in Java

in some cases we can’t provide guarantee for the type of elements or objects present inside our collection or wise, at the time of retrieval compulsory we should perform type casting otherwise we will get compile time error.

Arrays are always type safe that is we can provide the guarantee for the type of elements present inside array. to achieve type safety we have to use typecasting.

How to open a new tab using Selenium WebDriver

The below code will open the link in a new window:

String selectAll = Keys.chord(Keys.SHIFT, Keys.RETURN);
driver.findElement(By.linkText("linkname")).sendKeys(selectAll);

How do you search an amazon s3 bucket?

Use Amazon Athena to query S3 bucket. Also, load data to Amazon Elastic search. Hope this helps.

Remove shadow below actionbar

What is the style item to make it disappear?

In order to remove the shadow add this to your app theme:

<style name="MyAppTheme" parent="android:Theme.Holo.Light">
    <item name="android:windowContentOverlay">@null</item>
</style>

UPDATE: As @Quinny898 stated, on Android 5.0 this has changed, you have to call setElevation(0) on your action bar. Note that if you're using the support library you must call it to that like so:

getSupportActionBar().setElevation(0);

How to decide when to use Node.js?

  1. Node is great for quick prototypes but I'd never use it again for anything complex. I spent 20 years developing a relationship with a compiler and I sure miss it.

  2. Node is especially painful for maintaining code that you haven't visited for awhile. Type info and compile time error detection are GOOD THINGS. Why throw all that out? For what? And dang, when something does go south the stack traces quite often completely useless.

How to specify more spaces for the delimiter using cut?

Actually awk is exactly the tool you should be looking into:

ps axu | grep '[j]boss' | awk '{print $5}'

or you can ditch the grep altogether since awk knows about regular expressions:

ps axu | awk '/[j]boss/ {print $5}'

But if, for some bizarre reason, you really can't use awk, there are other simpler things you can do, like collapse all whitespace to a single space first:

ps axu | grep '[j]boss' | sed 's/\s\s*/ /g' | cut -d' ' -f5

That grep trick, by the way, is a neat way to only get the jboss processes and not the grep jboss one (ditto for the awk variant as well).

The grep process will have a literal grep [j]boss in its process command so will not be caught by the grep itself, which is looking for the character class [j] followed by boss.

This is a nifty way to avoid the | grep xyz | grep -v grep paradigm that some people use.

Hide scroll bar, but while still being able to scroll

I just wanted to share a combined snippet for hiding the scrollbar that I use when developing. It is a collection of several snippets found on the Internet that works for me:

.container {
    overflow-x: scroll; /* For horiz. scroll, otherwise overflow-y: scroll; */

    -ms-overflow-style: none;
    overflow: -moz-scrollbars-none;
    scrollbar-width: none;
}


.container::-webkit-scrollbar {
    display: none;  /* Safari and Chrome */
}

How do I use a regular expression to match any string, but at least 3 characters?

If you want to match starting from the beginning of the word, use:

\b\w{3,}

\b: word boundary

\w: word character

{3,}: three or more times for the word character

Where are SQL Server connection attempts logged?

Another way to check on connection attempts is to look at the server's event log. On my Windows 2008 R2 Enterprise machine I opened the server manager (right-click on Computer and select Manage. Then choose Diagnostics -> Event Viewer -> Windows Logs -> Applcation. You can filter the log to isolate the MSSQLSERVER events. I found a number that looked like this

Login failed for user 'bogus'. The user is not associated with a trusted SQL Server connection. [CLIENT: 10.12.3.126]

Scala Doubles, and Precision

It's actually very easy to handle using Scala f interpolator - https://docs.scala-lang.org/overviews/core/string-interpolation.html

Suppose we want to round till 2 decimal places:

scala> val sum = 1 + 1/4D + 1/7D + 1/10D + 1/13D
sum: Double = 1.5697802197802198

scala> println(f"$sum%1.2f")
1.57

How to check string length with JavaScript

As for the question which event you should use for this: use the input event, and fall back to keyup/keydown in older browsers.

Here’s an example, DOM0-style:

someElement.oninput = function() {
  this.onkeydown = null;
  // Your code goes here
};
someElement.onkeydown = function() {
  // Your code goes here
};

The other question is how to count the number of characters in the string. Depending on your definition of “character”, all answers posted so far are incorrect. The string.length answer is only reliable when you’re certain that only BMP Unicode symbols will be entered. For example, 'a'.length == 1, as you’d expect.

However, for supplementary (non-BMP) symbols, things are a bit different. For example, ''.length == 2, even though there’s only one Unicode symbol there. This is because JavaScript exposes UCS-2 code units as “characters”.

Luckily, it’s still possible to count the number of Unicode symbols in a JavaScript string through some hackery. You could use Punycode.js’s utility functions to convert between UCS-2 strings and Unicode code points for this:

// `String.length` replacement that only counts full Unicode characters
punycode.ucs2.decode('a').length; // 1
punycode.ucs2.decode('').length; // 1 (note that `''.length == 2`!)

P.S. I just noticed the counter script that Stack Overflow uses gets this wrong. Try entering , and you’ll see that it (incorrectly) counts as two characters.

Display / print all rows of a tibble (tbl_df)

you can print it in Rstudio with View() more convenient:

df %>% View()

View(df)

How to execute Ant build in command line

is it still actual?

As I can see you wrote <target depends="build-subprojects,build-project" name="build"/>, then you wrote <target name="build-subprojects"/> (it does nothing). Could it be a reason? Does this <echo message="${ant.project.name}: ${ant.file}"/> print appropriate message? If no then target is not running. Take a look at the next link http://www.sqaforums.com/showflat.php?Number=623277

Difference between Date(dateString) and new Date(dateString)

Date()

With this you call a function called Date(). It doesn't accept any arguments and returns a string representing the current date and time.

new Date()

With this you're creating a new instance of Date.

You can use only the following constructors:

new Date() // current date and time
new Date(milliseconds) //milliseconds since 1970/01/01
new Date(dateString)
new Date(year, month, day, hours, minutes, seconds, milliseconds)

So, use 2010-08-17 12:09:36 as parameter to constructor is not allowed.

See w3schools.


EDIT: new Date(dateString) uses one of these formats:

  • "October 13, 1975 11:13:00"
  • "October 13, 1975 11:13"
  • "October 13, 1975"

How to access a dictionary key value present inside a list?

You haven't provided enough context to provide an accurate answer (i.e. how do you want to handle identical keys in multiple dicts?)

One answer is to iterate the list, and attempt to get 'd'

mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myvalues = [i['d'] for i in mylist if 'd' in i]

Another answer is to access the dict directly (by list index), though you have to know that the key is present

mylist[1]['d']

How do I convert strings between uppercase and lowercase in Java?

There are methods in the String class; toUppercase() and toLowerCase().

i.e.

String input = "Cricket!";
String upper = input.toUpperCase(); //stores "CRICKET!"
String lower = input.toLowerCase(); //stores "cricket!" 

This will clarify your doubt

Getting date format m-d-Y H:i:s.u from milliseconds

I benched a few different ways:

1) microtime + sscanf + date:

sscanf(microtime(), '0.%6s00 %s', $usec, $sec);
$date = date('Y-m-d H:i:s.', $sec) . $usec;

I'm not sure why microtime() returns 10 chars (0.dddddd00) for the microseconds part but maybe someone can tell me ?

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { sscanf(microtime(), '0.%6s00 %s', $usec, $sec); $date = date('Y-m-d H:i:s.', $sec) . $usec; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "22372.335910797 ms" // macOS PHP 5.6.30
string(18) "16772.964000702 ms" // Linux PHP 5.4.16
string(18) "10382.229089737 ms" // Linux PHP 7.3.11 (same linux box as above)

2) DateTime::createFromFormat + Datetime->format:

$now = new DateTime('NOW');
$date = $now->format('Y-m-d H:i:s.u');

not working in PHP 5.x ...

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = new DateTime('NOW'); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "45801.825046539 ms" // macOS PHP 5.6.30 (ms not working)
string(18) "21180.155038834 ms" // Linux PHP 5.4.16 (ms not working)
string(18) "11879.796028137 ms" // Linux PHP 7.3.11 (same linux box as above)

3) gettimeofday + date:

$time = gettimeofday();
$date = date('Y-m-d H:i:s.', $time['sec']) . $time['usec'];

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $time = gettimeofday(); $date = date('Y-m-d H:i:s.', $time['sec']) . $time['usec']; } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "23706.788063049 ms" // macOS PHP 5.6.30
string(18) "14984.534025192 ms" // Linux PHP 5.4.16
string(18) "7799.1390228271 ms" // Linux PHP 7.3.11 (same linux box as above)

4) microtime + number_format + DateTime::createFromFormat + DateTime->format:

$now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', ''));
$date = $now->format('Y-m-d H:i:s.u');

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = DateTime::createFromFormat('U.u', number_format(microtime(true), 6, '.', '')); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "83326.496124268 ms" // macOS PHP 5.6.30
string(18) "61982.603788376 ms" // Linux PHP 5.4.16
string(16) "19107.1870327 ms" // Linux PHP 7.3.11 (same linux box as above)

5) microtime + sprintf + DateTime::createFromFormat + DateTime->format:

$now = DateTime::createFromFormat('U.u', sprintf('%.6f', microtime(true)));
$date = $now->format('Y-m-d H:i:s.u');

-

$start_ts = microtime(true); for($i = 0; $i < 10000000; $i++) { $now = DateTime::createFromFormat('U.u', sprintf('%.6f', microtime(true))); $date = $now->format('Y-m-d H:i:s.u'); } var_dump((microtime(true) - $start_ts)*1000 . ' ms');
string(18) "79387.331962585 ms" // macOS PHP 5.6.30
string(18) "60734.437942505 ms" // Linux PHP 5.4.16
string(18) "18594.941139221 ms" // Linux PHP 7.3.11 (same linux box as above)

NodeJS w/Express Error: Cannot GET /

Where is your get method for "/"?

Also you cant serve static html directly in Express.First you need to configure it.

app.configure(function(){
  app.set('port', process.env.PORT || 3000);  
  app.set("view options", {layout: false});  //This one does the trick for rendering static html
  app.engine('html', require('ejs').renderFile); 
  app.use(app.router);

});

Now add your get method.

app.get('/', function(req, res) {
  res.render('default.htm');
});

How to avoid 'undefined index' errors?

In my case, I get it worked by defining the default value if the submitted data is empty. Here is what I finally did (using PHP7.3.5):

if(empty($_POST['auto'])){ $_POST['auto'] = ""; }

Creating a Jenkins environment variable using Groovy

You can also define a variable without the EnvInject Plugin within your Groovy System Script:

import hudson.model.*
def build = Thread.currentThread().executable
def pa = new ParametersAction([
  new StringParameterValue("FOO", "BAR")
])
build.addAction(pa)

Then you can access this variable in the next build step which (for example) is an windows batch command:

@echo off
Setlocal EnableDelayedExpansion
echo FOO=!FOO!

This echo will show you "FOO=BAR".

Regards

Getting the text that follows after the regex match

Your regex "sentence(.*)" is right. To retrieve the contents of the group in parenthesis, you would call:

Pattern p = Pattern.compile( "sentence(.*)" );
Matcher m = p.matcher( "some lame sentence that is awesome" );
if ( m.find() ) {
   String s = m.group(1); // " that is awesome"
}

Note the use of m.find() in this case (attempts to find anywhere on the string) and not m.matches() (would fail because of the prefix "some lame"; in this case the regex would need to be ".*sentence(.*)")

how to list all sub directories in a directory

Use Directory.GetDirectories to get the subdirectories of the directory specified by "your_directory_path". The result is an array of strings.

var directories = Directory.GetDirectories("your_directory_path");

By default, that only returns subdirectories one level deep. There are options to return all recursively and to filter the results, documented here, and shown in Clive's answer.


Avoiding an UnauthorizedAccessException

It's easily possible that you'll get an UnauthorizedAccessException if you hit a directory to which you don't have access.

You may have to create your own method that handles the exception, like this:

public class CustomSearcher
{ 
    public static List<string> GetDirectories(string path, string searchPattern = "*",
        SearchOption searchOption = SearchOption.AllDirectories)
    {
        if (searchOption == SearchOption.TopDirectoryOnly)
            return Directory.GetDirectories(path, searchPattern).ToList();

        var directories = new List<string>(GetDirectories(path, searchPattern));

        for (var i = 0; i < directories.Count; i++)
            directories.AddRange(GetDirectories(directories[i], searchPattern));

        return directories;
    }

    private static List<string> GetDirectories(string path, string searchPattern)
    {
        try
        {
            return Directory.GetDirectories(path, searchPattern).ToList();
        }
        catch (UnauthorizedAccessException)
        {
            return new List<string>();
        }
    }
}

And then call it like this:

var directories = CustomSearcher.GetDirectories("your_directory_path");

This traverses a directory and all its subdirectories recursively. If it hits a subdirectory that it cannot access, something that would've thrown an UnauthorizedAccessException, it catches the exception and just returns an empty list for that inaccessible directory. Then it continues on to the next subdirectory.

iOS 7 status bar back to iOS 6 default style in iPhone app?

This might be too late to share, but I have something to contribute which might help someone, I was trying to sub-class the UINavigationBar and wanted to make it look like ios 6 with black status bar and status bar text in white.

Here is what I found working for that

        self.navigationController?.navigationBar.clipsToBounds = true
        self.navigationController?.navigationBar.translucent = false
        self.navigationController?.navigationBar.barStyle = .Black
        self.navigationController?.navigationBar.barTintColor = UIColor.whiteColor()

It made my status bar background black, status bar text white and navigation bar's color white.

iOS 9.3, XCode 7.3.1

Can dplyr package be used for conditional mutating?

Since you ask for other better ways to handle the problem, here's another way using data.table:

require(data.table) ## 1.9.2+
setDT(df)
df[a %in% c(0,1,3,4) | c == 4, g := 3L]
df[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]

Note the order of conditional statements is reversed to get g correctly. There's no copy of g made, even during the second assignment - it's replaced in-place.

On larger data this would have better performance than using nested if-else, as it can evaluate both 'yes' and 'no' cases, and nesting can get harder to read/maintain IMHO.


Here's a benchmark on relatively bigger data:

# R version 3.1.0
require(data.table) ## 1.9.2
require(dplyr)
DT <- setDT(lapply(1:6, function(x) sample(7, 1e7, TRUE)))
setnames(DT, letters[1:6])
# > dim(DT) 
# [1] 10000000        6
DF <- as.data.frame(DT)

DT_fun <- function(DT) {
    DT[(a %in% c(0,1,3,4) | c == 4), g := 3L]
    DT[a %in% c(2,5,7) | (a==1 & b==4), g := 2L]
}

DPLYR_fun <- function(DF) {
    mutate(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

BASE_fun <- function(DF) { # R v3.1.0
    transform(DF, g = ifelse(a %in% c(2,5,7) | (a==1 & b==4), 2L, 
            ifelse(a %in% c(0,1,3,4) | c==4, 3L, NA_integer_)))
}

system.time(ans1 <- DT_fun(DT))
#   user  system elapsed 
#  2.659   0.420   3.107 

system.time(ans2 <- DPLYR_fun(DF))
#   user  system elapsed 
# 11.822   1.075  12.976 

system.time(ans3 <- BASE_fun(DF))
#   user  system elapsed 
# 11.676   1.530  13.319 

identical(as.data.frame(ans1), as.data.frame(ans2))
# [1] TRUE

identical(as.data.frame(ans1), as.data.frame(ans3))
# [1] TRUE

Not sure if this is an alternative you'd asked for, but I hope it helps.

pip installs packages successfully, but executables not found from command line

I stumbled upon this question because I created, successfully built and published a PyPI Package, but couldn't execute it after installation. The $PATHvariable was correctly set.

In my case the problem was that I hadn't set the entry_pointin the setup.py file:

entry_points = {'console_scripts':

['YOUR_CONSOLE_COMMAND=MODULE_NAME.FILE_NAME:FUNCTION_NAME'],},

What are abstract classes and abstract methods?

- Abstract class is one which can't be instantiated, i.e. its object cannot be created.

- Abstract method are method's declaration without its definition.

- A Non-abstract class can only have Non-abstract methods.

- An Abstract class can have both the Non-abstract as well as Abstract methods.

- If the Class has an Abstract method then the class must also be Abstract.

- An Abstract method must be implemented by the very first Non-Abstract sub-class.

- Abstract class in Design patterns are used to encapsulate the behaviors that keeps changing.

Failed to locate the winutils binary in the hadoop binary path

The statement java.io.IOException: Could not locate executable null\bin\winutils.exe

explains that the null is received when expanding or replacing an Environment Variable. If you see the Source in Shell.Java in Common Package you will find that HADOOP_HOME variable is not getting set and you are receiving null in place of that and hence the error.

So, HADOOP_HOME needs to be set for this properly or the variable hadoop.home.dir property.

Hope this helps.

Thanks, Kamleshwar.

How to get/generate the create statement for an existing hive table?

Steps to generate Create table DDLs for all the tables in the Hive database and export into text file to run later:

step 1)
create a .sh file with the below content, say hive_table_ddl.sh

#!/bin/bash
rm -f tableNames.txt
rm -f HiveTableDDL.txt
hive -e "use $1; show tables;" > tableNames.txt  
wait
cat tableNames.txt |while read LINE
   do
   hive -e "use $1;show create table $LINE;" >>HiveTableDDL.txt
   echo  -e "\n" >> HiveTableDDL.txt
   done
rm -f tableNames.txt
echo "Table DDL generated"

step 2)

Run the above shell script by passing 'db name' as paramanter

>bash hive_table_dd.sh <<databasename>>

output :

All the create table statements of your DB will be written into the HiveTableDDL.txt

PHP XML Extension: Not installed

I solved this issue with commands bellow:

$ sudo apt-get install php7.3-intl

$ sudo /etc/init.d/php7.3-fpm restart

These commands works for me in homestead with php7.3

Web Service vs WCF Service

This answer is based on an article that no longer exists:

Summary of article:

"Basically, WCF is a service layer that allows you to build applications that can communicate using a variety of communication mechanisms. With it, you can communicate using Peer to Peer, Named Pipes, Web Services and so on.

You can’t compare them because WCF is a framework for building interoperable applications. If you like, you can think of it as a SOA enabler. What does this mean?

Well, WCF conforms to something known as ABC, where A is the address of the service that you want to communicate with, B stands for the binding and C stands for the contract. This is important because it is possible to change the binding without necessarily changing the code. The contract is much more powerful because it forces the separation of the contract from the implementation. This means that the contract is defined in an interface, and there is a concrete implementation which is bound to by the consumer using the same idea of the contract. The datamodel is abstracted out."

... later ...

"should use WCF when we need to communicate with other communication technologies (e,.g. Peer to Peer, Named Pipes) rather than Web Service"

How to cancel an $http request in AngularJS?

This enhances the accepted answer by decorating the $http service with an abort method as follows ...

'use strict';
angular.module('admin')
  .config(["$provide", function ($provide) {

$provide.decorator('$http', ["$delegate", "$q", function ($delegate, $q) {
  var getFn = $delegate.get;
  var cancelerMap = {};

  function getCancelerKey(method, url) {
    var formattedMethod = method.toLowerCase();
    var formattedUrl = encodeURI(url).toLowerCase().split("?")[0];
    return formattedMethod + "~" + formattedUrl;
  }

  $delegate.get = function () {
    var cancelerKey, canceler, method;
    var args = [].slice.call(arguments);
    var url = args[0];
    var config = args[1] || {};
    if (config.timeout == null) {
      method = "GET";
      cancelerKey = getCancelerKey(method, url);
      canceler = $q.defer();
      cancelerMap[cancelerKey] = canceler;
      config.timeout = canceler.promise;
      args[1] = config;
    }
    return getFn.apply(null, args);
  };

  $delegate.abort = function (request) {
    console.log("aborting");
    var cancelerKey, canceler;
    cancelerKey = getCancelerKey(request.method, request.url);
    canceler = cancelerMap[cancelerKey];

    if (canceler != null) {
      console.log("aborting", cancelerKey);

      if (request.timeout != null && typeof request.timeout !== "number") {

        canceler.resolve();
        delete cancelerMap[cancelerKey];
      }
    }
  };

  return $delegate;
}]);
  }]);

WHAT IS THIS CODE DOING?

To cancel a request a "promise" timeout must be set. If no timeout is set on the HTTP request then the code adds a "promise" timeout. (If a timeout is set already then nothing is changed).

However, to resolve the promise we need a handle on the "deferred". We thus use a map so we can retrieve the "deferred" later. When we call the abort method, the "deferred" is retrieved from the map and then we call the resolve method to cancel the http request.

Hope this helps someone.

LIMITATIONS

Currently this only works for $http.get but you can add code for $http.post and so on

HOW TO USE ...

You can then use it, for example, on state change, as follows ...

rootScope.$on('$stateChangeStart', function (event, toState, toParams) {
  angular.forEach($http.pendingRequests, function (request) {
        $http.abort(request);
    });
  });

Retrieve the commit log for a specific line in a file?

Here is a solution that defines a git alias, so you will be able use it like that :

git rblame -M -n -L '/REGEX/,+1' FILE

Output example :

00000000 18 (Not Committed Yet 2013-08-19 13:04:52 +0000 728) fooREGEXbar
15227b97 18 (User1 2013-07-11 18:51:26 +0000 728) fooREGEX
1748695d 23 (User2 2013-03-19 21:09:09 +0000 741) REGEXbar

You can define the alias in your .gitconfig or simply run the following command

git config alias.rblame !sh -c 'while line=$(git blame "$@" $commit 2>/dev/null); do commit=${line:0:8}^; [ 00000000^ == $commit ] && commit=$(git rev-parse HEAD); echo $line; done' dumb_param

This is an ugly one-liner, so here is a de-obfuscated equivalent bash function :

git-rblame () {
    local commit line
    while line=$(git blame "$@" $commit 2>/dev/null); do
        commit="${line:0:8}^"
        if [ "00000000^" == "$commit" ]; then
            commit=$(git rev-parse HEAD)
        fi
        echo $line
    done
}

The pickaxe solution ( git log --pickaxe-regex -S'REGEX' ) will only give you line additions/deletions, not the other alterations of the line containing the regular expression.

A limitation of this solution is that git blame only returns the 1st REGEX match, so if multiple matches exist the recursion may "jump" to follow another line. Be sure to check the full history output to spot those "jumps" and then fix your REGEX to ignore the parasite lines.

Finally, here is an alternate version that run git show on each commit to get the full diff :

git config alias.rblameshow !sh -c 'while line=$(git blame "$@" $commit 2>/dev/null); do commit=${line:0:8}^; [ 00000000^ == $commit ] && commit=$(git rev-parse HEAD); git show $commit; done' dumb_param

Get first element from a dictionary

Dictionary does not define order of items. If you just need an item use Keys or Values properties of dictionary to pick one.

How to remove numbers from string using Regex.Replace?

As a string extension:

    public static string RemoveIntegers(this string input)
    {
        return Regex.Replace(input, @"[\d-]", string.Empty);
    }

Usage:

"My text 1232".RemoveIntegers(); // RETURNS "My text "

Why doesn't Console.Writeline, Console.Write work in Visual Studio Express?

There are 2 possible problems are:

  • Firstly, you have not used the using System which should be before writing code that uses "System class", as Console.WriteLine()
  • Secondly, you have not coded what happens after the Console displays "Test"

The possible solution will be:

using System;

namespace Test
{
    public static Main()
    {
        //Print to the console
        Console.WriteLine("Test");

        //Allow user to read output
        Console.ReadKey();
    }
}

It is also strategic to code Console.Write("Press any key to exit..."); on the line that precedes the Console.ReadKey(); to make the user aware that the program is ending, he/she must press any key to exit.

Android: Changing Background-Color of the Activity (Main View)

Try this:

_x000D_
_x000D_
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimaryDark"


</androidx.constraintlayout.widget.ConstraintLayout>
    />
_x000D_
_x000D_
_x000D_

Mysql adding user for remote access

In order to connect remotely you have to have MySQL bind port 3306 to your machine's IP address in my.cnf. Then you have to have created the user in both localhost and '%' wildcard and grant permissions on all DB's as such . See below:

my.cnf (my.ini on windows)

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

then

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

Then

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';
flush privileges;

Depending on your OS you may have to open port 3306 to allow remote connections.

How can I remove space (margin) above HTML header?

This css allowed chrome and firefox to render all other elements on my page normally and remove the margin above my h1 tag. Also, as a page is resized em can work better than px.

h1 {
  margin-top: -.3em;
  margin-bottom: 0em;
}

MVC 3: How to render a view without its layout page when loaded via ajax?

I prefer, and use, your #1 option. I don't like #2 because to me View() implies you are returning an entire page. It should be a fully fleshed out and valid HTML page once the view engine is done with it. PartialView() was created to return arbitrary chunks of HTML.

I don't think it's a big deal to have a view that just calls a partial. It's still DRY, and allows you to use the logic of the partial in two scenarios.

Many people dislike fragmenting their action's call paths with Request.IsAjaxRequest(), and I can appreciate that. But IMO, if all you are doing is deciding whether to call View() or PartialView() then the branch is not a big deal and is easy to maintain (and test). If you find yourself using IsAjaxRequest() to determine large portions of how your action plays out, then making a separate AJAX action is probably better.

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

I have a script that drops in the iframe with it's content. It also makes sure that iFrameResizer exists (it injects it as a script) and then does the resizing.

I'll drop in a simplified example below.

// /js/embed-iframe-content.js

(function(){
    // Note the id, we need to set this correctly on the script tag responsible for
    // requesting this file.
    var me = document.getElementById('my-iframe-content-loader-script-tag');

    function loadIFrame() {
        var ifrm = document.createElement('iframe');
        ifrm.id = 'my-iframe-identifier';
        ifrm.setAttribute('src', 'http://www.google.com');
        ifrm.style.width = '100%';
        ifrm.style.border = 0;
        // we initially hide the iframe to avoid seeing the iframe resizing
        ifrm.style.opacity = 0;
        ifrm.onload = function () {
            // this will resize our iframe
            iFrameResize({ log: true }, '#my-iframe-identifier');
            // make our iframe visible
            ifrm.style.opacity = 1;
        };

        me.insertAdjacentElement('afterend', ifrm);
    }

    if (!window.iFrameResize) {
        // We first need to ensure we inject the js required to resize our iframe.

        var resizerScriptTag = document.createElement('script');
        resizerScriptTag.type = 'text/javascript';

        // IMPORTANT: insert the script tag before attaching the onload and setting the src.
        me.insertAdjacentElement('afterend', ifrm);

        // IMPORTANT: attach the onload before setting the src.
        resizerScriptTag.onload = loadIFrame;

        // This a CDN resource to get the iFrameResizer code.
        // NOTE: You must have the below "coupled" script hosted by the content that
        // is loaded within the iframe:
        // https://unpkg.com/[email protected]/js/iframeResizer.contentWindow.min.js
        resizerScriptTag.src = 'https://unpkg.com/[email protected]/js/iframeResizer.min.js';
    } else {
        // Cool, the iFrameResizer exists so we can just load our iframe.
        loadIFrame();
    }    
}())

Then the iframe content can be injected anywhere within another page/site by using the script like so:

<script
  id="my-iframe-content-loader-script-tag"
  type="text/javascript"
  src="/js/embed-iframe-content.js"
></script>

The iframe content will be injected below wherever you place the script tag.

Hope this is helpful to someone.

multi line comment vb.net in Visual studio 2010

multi comment in vb.net

VB.NET doesn't support for multi line comment.

The only way to do multi-line comments in VB.NET is to do a lot of single line comments(').

Or just highlight the whole code and just use (Ctrl+E,C), (Ctrl+E,U) to comment or uncomment.

Only in c# /* */

Or in ASP.NET html source using <!-- -->.

Meaning of - <?xml version="1.0" encoding="utf-8"?>

The encoding declaration identifies which encoding is used to represent the characters in the document.

More on the XML Declaration here: http://msdn.microsoft.com/en-us/library/ms256048.aspx

What is the correct syntax of ng-include?

For those who are looking for the shortest possible "item renderer" solution from a partial, so a combo of ng-repeat and ng-include:

<div ng-repeat="item in items" ng-include src="'views/partials/item.html'" />

Actually, if you use it like this for one repeater, it will work, but won't for 2 of them! Angular (v1.2.16) will freak out for some reason if you have 2 of these one after another, so it is safer to close the div the pre-xhtml way:

<div ng-repeat="item in items" ng-include src="'views/partials/item.html'"></div>

Finding all cycles in a directed graph

I found this page in my search and since cycles are not same as strongly connected components, I kept on searching and finally, I found an efficient algorithm which lists all (elementary) cycles of a directed graph. It is from Donald B. Johnson and the paper can be found in the following link:

http://www.cs.tufts.edu/comp/150GA/homeworks/hw1/Johnson%2075.PDF

A java implementation can be found in:

http://normalisiert.de/code/java/elementaryCycles.zip

A Mathematica demonstration of Johnson's algorithm can be found here, implementation can be downloaded from the right ("Download author code").

Note: Actually, there are many algorithms for this problem. Some of them are listed in this article:

http://dx.doi.org/10.1137/0205007

According to the article, Johnson's algorithm is the fastest one.

converting list to json format - quick and easy way

why reinvent the wheel? use microsoft's json serialize or a 3rd party library such as json.NET

How to get query parameters from URL in Angular 5?

import { ParamMap, Router, ActivatedRoute } from '@angular/router';

constructor(private route: ActivatedRoute) {}

ngOnInit() {
    console.log(this.route.snapshot.queryParamMap);
}

UPDATE

import { Router, RouterStateSnapshot } from '@angular/router';

export class LoginComponent {
    constructor(private router: Router) {
        const snapshot: RouterStateSnapshot = router.routerState.snapshot;
        console.log(snapshot);  // <-- hope it helps
    }
}

The tilde operator in Python

I was solving this leetcode problem and I came across this beautiful solution by a user named Zitao Wang.

The problem goes like this for each element in the given array find the product of all the remaining numbers without making use of divison and in O(n) time

The standard solution is:

Pass 1: For all elements compute product of all the elements to the left of it
Pass 2: For all elements compute product of all the elements to the right of it
        and then multiplying them for the final answer 

His solution uses only one for loop by making use of. He computes the left product and right product on the fly using ~

def productExceptSelf(self, nums):
    res = [1]*len(nums)
    lprod = 1
    rprod = 1
    for i in range(len(nums)):
        res[i] *= lprod
        lprod *= nums[i]
        res[~i] *= rprod
        rprod *= nums[~i]
    return res

How to split a comma-separated value to columns

CREATE FUNCTION [dbo].[fnSplit](@sInputList VARCHAR(8000), @sDelimiter VARCHAR(8000) = ',')
RETURNS @List TABLE (item VARCHAR(8000))
BEGIN

    DECLARE @sItem VARCHAR(8000)
    WHILE CHARINDEX(@sDelimiter, @sInputList, 0) <> 0
    BEGIN

        SELECT @sItem = RTRIM(LTRIM(SUBSTRING(@sInputList, 1, CHARINDEX(@sDelimiter, @sInputList,0) - 1))),
               @sInputList = RTRIM(LTRIM(SUBSTRING(@sInputList, CHARINDEX(@sDelimiter, @sInputList, 0) + LEN(@sDelimiter),LEN(@sInputList))))

        -- Indexes to keep the position of searching
        IF LEN(@sItem) > 0

        INSERT INTO @List SELECT @sItem

    END

    IF LEN(@sInputList) > 0
    BEGIN

        INSERT INTO @List SELECT @sInputList -- Put the last item in

    END

    RETURN

END

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

python int( ) function

import random
import time
import sys
while True:
    x=random.randint(1,100)
    print('''Guess my number--it's from 1 to 100.''')
    z=0
    while True:
        z=z+1
        xx=int(str(sys.stdin.readline()))
        if xx > x:
            print("Too High!")
        elif xx < x:
            print("Too Low!")
        elif xx==x:
            print("You Win!! You used %s guesses!"%(z))
            print()
            break
        else:
            break

in this, I first string the number str(), which converts it into an inoperable number. Then, I int() integerize it, to make it an operable number. I just tested your problem on my IDLE GUI, and it said that 49.8 < 50.

Set Text property of asp:label in Javascript PROPER way

The label's information is stored in the ViewState input on postback (keep in mind the server knows nothing of the page outside of the form values posted back, which includes your label's text).. you would have to somehow update that on the client side to know what changed in that label, which I'm guessing would not be worth your time.

I'm not entirely sure what problem you're trying to solve here, but this might give you a few ideas of how to go about it:

You could create a hidden field to go along with your label, and anytime you update your label, you'd update that value as well.. then in the code behind set the Text property of the label to be what was in that hidden field.

CMake unable to determine linker language with C++

In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.

XAMPP - Port 80 in use by "Unable to open process" with PID 4! 12

Another very easy option is to simply set Apache to listen on a different port. This can be done by clicking on the "Config" button on the same line as the "Apache" module, select the "httpd.conf" file in the dropdown, then change the "Listen 80" line to "Listen 8080". Save the file and close it.

Now it avoids Port 80 and uses Port 8080 instead without issue. The only additional thing you need to do is make sure to put localhost:8080 in the browser so the browser knows to look on Port 8080. Otherwise it defaults to Port 80 and won't find your local site.

This will also require you to restart Apache for the change to take effect.

Voila! Fixed.

jQuery issue in Internet Explorer 8

Maybe you insert two scripts,it should be work.

<script src="http://ie7-js.googlecode.com/svn/version/2.1(beta4)/IE8.js"></script>  
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js">/script> 

Run Jquery function on window events: load, resize, and scroll?

You can bind listeners to one common functions -

$(window).bind("load resize scroll",function(e){
  // do stuff
});

Or another way -

$(window).bind({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Alternatively, instead of using .bind() you can use .on() as bind directly maps to on(). And maybe .bind() won't be there in future jquery versions.

$(window).on({
     load:function(){

     },
     resize:function(){

     },
     scroll:function(){

    }
});

Does Python have a string 'contains' substring method?

You can use y.count().

It will return the integer value of the number of times a sub string appears in a string.

For example:

string.count("bah") >> 0
string.count("Hello") >> 1

Prevent users from submitting a form by hitting Enter

ONLY BLOCK SUBMIT but not other, important functionality of enter key, such as creating a new paragraph in a <textarea>:

_x000D_
_x000D_
window.addEventListener('keydown', function(event) {_x000D_
  //set default value for variable that will hold the status of keypress_x000D_
  pressedEnter = false;_x000D_
_x000D_
  //if user pressed enter, set the variable to true_x000D_
  if (event.keyCode == 13)_x000D_
    pressedEnter = true;_x000D_
_x000D_
  //we want forms to disable submit for a tenth of a second only_x000D_
  setTimeout(function() {_x000D_
    pressedEnter = false;_x000D_
  }, 100)_x000D_
_x000D_
})_x000D_
_x000D_
//find all forms_x000D_
var forms = document.getElementsByTagName('form')_x000D_
_x000D_
//loop through forms_x000D_
for (i = 0; i < forms.length; i++) {_x000D_
  //listen to submit event_x000D_
  forms[i].addEventListener('submit', function(e) {_x000D_
    //if user just pressed enter, stop the submit event_x000D_
    if (pressedEnter == true) {_x000D_
      updateLog('Form prevented from submit.')_x000D_
      e.preventDefault();_x000D_
      return false;_x000D_
    }_x000D_
_x000D_
    updateLog('Form submitted.')_x000D_
  })_x000D_
}_x000D_
_x000D_
var log = document.getElementById('log')_x000D_
updateLog = function(msg) {_x000D_
  log.innerText = msg_x000D_
}
_x000D_
input,_x000D_
textarea {_x000D_
  display: inline-block;_x000D_
  margin-bottom: 1em;_x000D_
  border: 1px solid #6f6f6f;_x000D_
  padding: 5px;_x000D_
  border-radius: 2px;_x000D_
  width: 90%;_x000D_
  font-size: 14px;_x000D_
}_x000D_
_x000D_
input[type=submit] {_x000D_
  background: lightblue;_x000D_
  color: #fff;_x000D_
}
_x000D_
<form>_x000D_
  <p>Sample textarea (try enter key):</p>_x000D_
  <textarea rows="4">Hit enter, a new line will be added. But the form won't submit</textarea><br/>_x000D_
  <p>Sample textfield (try enter key):</p>_x000D_
  <input type="text" placeholder="" />_x000D_
  <br/>_x000D_
  <input type="submit" value="Save" />_x000D_
  <h3 id="log"></h3>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Get characters after last / in url

You can use substr and strrchr:

$url = 'http://www.vimeo.com/1234567';
$str = substr(strrchr($url, '/'), 1);
echo $str;      // Output: 1234567

Best JavaScript compressor

Here is a YUI compressor script (Byuic) that finds all the js and css down a path and compresses /(optionally) obfuscates them. Nice to integrate into a build process.

Android/Java - Date Difference in days

I found a very easy way to do this and it's what I'm using in my app.

Let's say you have the dates in Time objects (or whatever, we just need the milliseconds):

Time date1 = initializeDate1(); //get the date from somewhere
Time date2 = initializeDate2(); //get the date from somewhere

long millis1 = date1.toMillis(true);
long millis2 = date2.toMillis(true);

long difference = millis2 - millis1 ;

//now get the days from the difference and that's it
long days = TimeUnit.MILLISECONDS.toDays(difference);

//now you can do something like
if(days == 7)
{
    //do whatever when there's a week of difference
}

if(days >= 30)
{
    //do whatever when it's been a month or more
}

Add Twitter Bootstrap icon to Input box

Bootstrap 4.x with 3 different way.

  1. Icon with default bootstrap Style Icon with default bootstrap Style

    <div class="input-group">
          <input type="text" class="form-control" placeholder="From" aria-label="from" aria-describedby="from">
          <div class="input-group-append">
            <span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>
          </div>
        </div>
    
  2. Icon Inside Input with default bootstrap class Icon Inside Input with default bootstrap class

    <div class="input-group">
          <input type="text" class="form-control border-right-0" placeholder="From" aria-label="from" aria-describedby="from">
          <div class="input-group-append">
            <span class="input-group-text bg-transparent"><i class="fas fa-map-marker-alt"></i></span>
          </div>
    
    </div>
    
  3. Icon Inside Input with small custom css Icon Inside Input with small custom css

    <div class="input-group">
          <input type="text" class="form-control rounded-right" placeholder="From" aria-label="from" aria-describedby="from">
            <span class="icon-inside"><i class="fas fa-map-marker-alt"></i></span>
        </div> 
    

    Custom Css

    .icon-inside {
          position: absolute;
          right: 10px;
          top: calc(50% - 12px);
          pointer-events: none;
          font-size: 16px;
          font-size: 1.125rem;
          color: #c4c3c3;
          z-index:3;
        }
    

_x000D_
_x000D_
.icon-inside {_x000D_
      position: absolute;_x000D_
      right: 10px;_x000D_
      top: calc(50% - 12px);_x000D_
      pointer-events: none;_x000D_
      font-size: 16px;_x000D_
      font-size: 1.125rem;_x000D_
      color: #c4c3c3;_x000D_
      z-index:3;_x000D_
    }
_x000D_
<link rel="stylesheet" type="text/css" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" />_x000D_
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">_x000D_
_x000D_
    <div class="container">_x000D_
    <h5 class="mt-3">Icon <small>with default bootstrap Style</small><h5>_x000D_
    <div class="input-group">_x000D_
      <input type="text" class="form-control" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
      <div class="input-group-append">_x000D_
        <span class="input-group-text"><i class="fas fa-map-marker-alt"></i></span>_x000D_
      </div>_x000D_
    </div>_x000D_
_x000D_
    <h5 class="mt-3">Icon Inside Input <small>with default bootstrap class</small><h5>_x000D_
    <div class="input-group">_x000D_
      <input type="text" class="form-control border-right-0" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
      <div class="input-group-append">_x000D_
        <span class="input-group-text bg-transparent"><i class="fas fa-map-marker-alt"></i></span>_x000D_
      </div>_x000D_
    </div>_x000D_
_x000D_
    <h5 class="mt-3">Icon Inside Input<small> with small custom css</small><h5>_x000D_
    <div class="input-group">_x000D_
      <input type="text" class="form-control rounded-right" placeholder="From" aria-label="from" aria-describedby="from">_x000D_
        <span class="icon-inside"><i class="fas fa-map-marker-alt"></i></span>_x000D_
    </div>_x000D_
_x000D_
    </div>
_x000D_
_x000D_
_x000D_

python mpl_toolkits installation issue

It doesn't work on Ubuntu 16.04, it seems that some libraries have been forgotten in the python installation package on this one. You should use package manager instead.

Solution

Uninstall matplotlib from pip then install it again with apt-get

python 2:

sudo pip uninstall matplotlib
sudo apt-get install python-matplotlib

python 3:

sudo pip3 uninstall matplotlib
sudo apt-get install python3-matplotlib

Random number c++ in some range

float RandomFloat(float min, float max)
{
    float r = (float)rand() / (float)RAND_MAX;
    return min + r * (max - min);
}

Capture key press without placing an input element on the page?

Code & detects ctrl+z

document.onkeyup = function(e) {
  if(e.ctrlKey && e.keyCode == 90) {
    // ctrl+z pressed
  }
}

How to make an array of arrays in Java

try

String[][] arrays = new String[5][];

Excel plot time series frequency with continuous xaxis

I would like to compliment Ram Narasimhans answer with some tips I found on an Excel blog

Non-uniformly distributed data can be plotted in excel in

  • X Y (Scatter Plots)
  • Linear plots with Date axis
    • These don't take time into account, only days.
    • This method is quite cumbersome as it requires translating your time units to days, months, or years.. then change the axis labels... Not Recommended

Just like Ram Narasimhan suggested, to have the points centered you will want the mid point but you don't need to move to a numeric format, you can stay in the time format.

1- Add the center point to your data series

+---------------+-------+------+
|    Time       | Time  | Freq |
+---------------+-------+------+
| 08:00 - 09:00 | 08:30 |  12  |
| 09:00 - 10:00 | 09:30 |  13  |
| 10:00 - 11:00 | 10:30 |  10  |
| 13:00 - 14:00 | 13:30 |   5  |
| 14:00 - 15:00 | 14:30 |  14  |
+---------------+-------+------+

2- Create a Scatter Plot

3- Excel allows you to specify time values for the axis options. Time values are a parts per 1 of a 24-hour day. Therefore if we want to 08:00 to 15:00, then we Set the Axis options to:

  • Minimum : Fix : 0.33333
  • Maximum : Fix : 0.625
  • Major unit : Fix : 0.041667

Line Scatter Plot


Alternative Display:

Make the points turn into columns:

To be able to represent these points as bars instead of just point we need to draw disjoint lines. Here is a way to go about getting this type of chart.

1- You're going to need to add several rows where we draw the line and disjoint the data

+-------+------+
| Time  | Freq |
+-------+------+
| 08:30 |   0  |
| 08:30 |  12  |
|       |      |
| 09:30 |   0  |
| 09:30 |  13  |
|       |      |
| 10:30 |   0  |
| 10:30 |  10  |
|       |      |
| 13:30 |   0  |
| 13:30 |   5  |
|       |      |
| 14:30 |   0  |
| 14:30 |  14  |
+-------+------+

2- Plot an X Y (Scatter) Chart with Lines.

3- Now you can tweak the data series to have a fatter line, no markers, etc.. to get a bar/column type chart with non-uniformly distributed data.

Bar-Line Scatter Plot

how to play video from url

pDialog = new ProgressDialog(this);

    // Set progressbar message
    pDialog.setMessage("Buffering...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    // Show progressbar
    pDialog.show();

    try {
        // Start the MediaController
        MediaController mediacontroller = new MediaController(this);
        mediacontroller.setAnchorView(mVideoView);      

        Uri videoUri = Uri.parse(videoUrl);
        mVideoView.setMediaController(mediacontroller);
        mVideoView.setVideoURI(videoUri);

    } catch (Exception e) {

        e.printStackTrace();
    }

    mVideoView.requestFocus();
    mVideoView.setOnPreparedListener(new OnPreparedListener() {
        // Close the progress bar and play the video
        public void onPrepared(MediaPlayer mp) {
            pDialog.dismiss();
            mVideoView.start();
        }
    });
    mVideoView.setOnCompletionListener(new OnCompletionListener() {

        public void onCompletion(MediaPlayer mp) {
            if (pDialog.isShowing()) {
                pDialog.dismiss();
            }
            finish();               
        }
    });

Why is my element value not getting changed? Am I using the wrong function?

How to address your textbox depends on the HTML-code:

<!-- 1 --><input type="textbox" id="Tue" />
<!-- 2 --><input type="textbox" name="Tue" />

If you use the 'id' attribute:

var textbox = document.getElementById('Tue');

for 'name':

var textbox = document.getElementsByName('Tue')[0]

(Note that getElementsByName() returns all elements with the name as array, therefore we use [0] to access the first one)

Then, use the 'value' attribute:

textbox.value = 'Foobar';

XML Parsing - Read a Simple XML File and Retrieve Values

Easy way to parse the xml is to use the LINQ to XML

for example you have the following xml file

<library>
    <track id="1" genre="Rap" time="3:24">
        <name>Who We Be RMX (feat. 2Pac)</name>
        <artist>DMX</artist>
        <album>The Dogz Mixtape: Who's Next?!</album>
    </track>
    <track id="2" genre="Rap" time="5:06">
        <name>Angel (ft. Regina Bell)</name>
        <artist>DMX</artist>
        <album>...And Then There Was X</album>
    </track>
    <track id="3" genre="Break Beat" time="6:16">
        <name>Dreaming Your Dreams</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
    <track id="4" genre="Break Beat" time="9:38">
        <name>Finished Symphony</name>
        <artist>Hybrid</artist>
        <album>Wide Angle</album>
    </track>
<library>

For reading this file, you can use the following code:

public void Read(string  fileName)
{
    XDocument doc = XDocument.Load(fileName);

    foreach (XElement el in doc.Root.Elements())
    {
        Console.WriteLine("{0} {1}", el.Name, el.Attribute("id").Value);
        Console.WriteLine("  Attributes:");
        foreach (XAttribute attr in el.Attributes())
            Console.WriteLine("    {0}", attr);
        Console.WriteLine("  Elements:");

        foreach (XElement element in el.Elements())
            Console.WriteLine("    {0}: {1}", element.Name, element.Value);
    }
}

Working with time DURATION, not time of day

Highlight the cell(s)/column which you want as Duration, right click on the mouse to "Format Cells". Go to "Custom" and look for "h:mm" if you want to input duration in hour and minutes format. If you want to include seconds as well, click on "h:mm:ss". You can even add up the total duration after that.

Hope this helps.

How to escape apostrophe (') in MySql?

Here's an example:

SELECT * FROM pubs WHERE name LIKE "%John's%"

Just use double quotes to enclose the single quote.

If you insist in using single quotes (and the need to escape the character):

SELECT * FROM pubs WHERE name LIKE '%John\'s%'

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

This is because your servlet is trying to access a request object which is no more exist.. A servlet's forward or include statement does not stop execution of method block. It continues to the end of method block or first return statement just like any other java method.

The best way to resolve this problem just set the page (where you suppose to forward the request) dynamically according your logic. That is:

protected void doPost(request , response){
String returnPage="default.jsp";
if(condition1){
 returnPage="page1.jsp";
}
if(condition2){
   returnPage="page2.jsp";
}
request.getRequestDispatcher(returnPage).forward(request,response); //at last line
}

and do the forward only once at last line...

you can also fix this problem using return statement after each forward() or put each forward() in if...else block

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

How can I get browser to prompt to save password?

Using a cookie would probably be the best way to do this.

You could have a checkbox for 'Remember me?' and have the form create a cookie to store the //user's login// info. EDIT: User Session Information

To create a cookie, you'll need to process the login form with PHP.

XmlWriter to Write to a String Instead of to a File

You need to create a StringWriter, and pass that to the XmlWriter.

The string overload of the XmlWriter.Create is for a filename.

E.g.

using (var sw = new StringWriter()) {
  using (var xw = XmlWriter.Create(sw)) {
    // Build Xml with xw.


  }
  return sw.ToString();
}

Making authenticated POST requests with Spring RestTemplate for Android

Very useful I had a slightly different scenario where I the request xml was itself the body of the POST and not a param. For that the following code can be used - Posting as an answer just in case anyone else having similar issue will benefit.

    final HttpHeaders headers = new HttpHeaders();
    headers.add("header1", "9998");
    headers.add("username", "xxxxx");
    headers.add("password", "xxxxx");
    headers.add("header2", "yyyyyy");
    headers.add("header3", "zzzzz");
    headers.setContentType(MediaType.APPLICATION_XML);
    headers.setAccept(Arrays.asList(MediaType.APPLICATION_XML));
    final HttpEntity<MyXmlbeansRequestDocument> httpEntity = new HttpEntity<MyXmlbeansRequestDocument>(
            MyXmlbeansRequestDocument.Factory.parse(request), headers);
    final ResponseEntity<MyXmlbeansResponseDocument> responseEntity = restTemplate.exchange(url, HttpMethod.POST, httpEntity,MyXmlbeansResponseDocument.class);
    log.info(responseEntity.getBody());

Binding select element to object in Angular

This code is very simple:

<select class="form-control" id="marasemaat" style="margin-top: 10%;font-size: 13px;" [(ngModel)]="fullNamePresentor" [formControl]="stateControl"  
            (change)="onSelect($event.target.value)">
            <option *ngFor="let char of programInfo1;let i = index;"   onclick="currentSlide(9,false)" value={{char.id}}>{{char.title + " "}}  ----> {{char.name + " "+ char.family }} ---- > {{(char.time.split('T', 2)[1]).split(':',2)}}</option>
  
          </select>

I can't install intel HAXM

Note: this is not an answer because I could not find a solution. But I think the information may be useful for others (and it wouldn't be practical as a comment). I have tried all of the steps detailed in the various docs but I could not get Android Emulator to work on my AMD Ryzen 7 :(


Most answers work only for Intel CPUs. If you have an AMD CPU (like me, an AMD Ryzen 7) you need to know about some restrictions and you have to use WHPX instead of HAXM.

I found this on MS's site: Because the Android emulator currently supports AMD hardware acceleration only on Linux, hardware acceleration is not available for AMD-based computers running Windows.

Fortunatelly there is a way to make it work but configuring hardware acceleration for an AMD CPU is a bit more complex:

Requirements and recommendations: - AMD CPU recommendation: AMD Ryzen CPU - Android Studio 3.2 Beta 1 or higher - Android Emulator version 27.3.8 or higher - Windows 10 with April 2018 Update or higher

To use WHPX acceleration on Windows, you must enable the Windows Hypervisor Platform option in the Turn Windows features on or off dialog box. For changes to this option to take effect, restart your computer.

Additionally, the following changes must be made in the BIOS settings: - AMD CPU: Virtualization or SVM must be enabled.

Note that there are further restrictions as well:

  • You can't run a VM-accelerated emulator inside another VM, such as a VM hosted by VirtualBox, VMWare, or Docker. You must run the emulator directly on your system hardware.
  • You can't run software that uses another virtualization technology at the same time that you run the accelerated emulator. For example, VirtualBox, VMWare, and Docker currently use a different virtualization technology, so you can't run them at the same time as the accelerated emulator.

Some more info: Android Emulator - AMD Processor & Hyper-V Support

This recommendation did not help either:

Please note: More recent versions of the emulator (27.2.8, 27.3.0, or later), require an emulator flag while the feature is in the preview. To do this, create or edit the file C:\Users\.android\advancedFeatures.ini and add the line “WindowsHypervisorPlatform = on”, or start the emulator from the command line with “-feature WindowsHypervisorPlatform”.

Find the most frequent number in a NumPy array

If you're willing to use SciPy:

>>> from scipy.stats import mode
>>> mode([1,2,3,1,2,1,1,1,3,2,2,1])
(array([ 1.]), array([ 6.]))
>>> most_frequent = mode([1,2,3,1,2,1,1,1,3,2,2,1])[0][0]
>>> most_frequent
1.0

Characters allowed in GET parameter

"." | "!" | "~" | "*" | "'" | "(" | ")" are also acceptable [RFC2396]. Really, anything can be in a GET parameter if it is properly encoded.

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)