Programs & Examples On #Fsevents

Loop through all the resources in a .resx file

You should always use the resource manager and not read files directly to ensure globalization is taken into account.

using System.Collections;
using System.Globalization;
using System.Resources;

...

/* Reference to your resources class -- may be named differently in your case */
ResourceManager MyResourceClass =
    new ResourceManager(typeof(Resources));

ResourceSet resourceSet =
    MyResourceClass.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
foreach (DictionaryEntry entry in resourceSet)
{
    string resourceKey = entry.Key.ToString();
    object resource = entry.Value;
}

@UniqueConstraint annotation in Java

Way1 :

@Entity

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")})

-- Here both Column1 and Column2 acts as unique constraints separately. Ex : if any time either the value of column1 or column2 value matches then you will get UNIQUE_CONSTRAINT Error.

Way2 :

@Entity

@Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames ={"column1","column2"})})

-- Here both column1 and column2 combined values acts as unique constraints

css divide width 100% to 3 column

In case you wonder, In Bootstrap templating system (which is very accurate), here is how they divide the columns when you apply the class .col-md-4 (1/3 of the 12 column system)

CSS

.col-md-4{
    float: left;
    width: 33.33333333%;
}

I'm not a fan of float, but if you really want your element to be perfectly 1/3 of your page, then you don't have a choice because sometimes when you use inline-block element, browser can consider space in your HTML as a 1px space which would break your perfect 1/3. Hope it helped !

Create boolean column in MySQL with false as default value?

If you are making the boolean column as not null then the default 'default' value is false; you don't have to explicitly specify it.

How to set min-height for bootstrap container

Have you tried height: auto; on your .container div?

Here is a fiddle, if you change img height, container height will adjust to it.

EDIT

So if you "can't" change the inline min-height, you can overwrite the inline style with an !important parameter. It's not the cleanest way, but it solves your problem.

add to your .containerclass this line

min-height:0px !important;

I've updated my fiddle to give you an example.

Javascript .querySelector find <div> by innerTEXT

You best see if you have a parent element of the div you are querying. If so get the parent element and perform an element.querySelectorAll("div"). Once you get the nodeList apply a filter on it over the innerText property. Assume that a parent element of the div that we are querying has an id of container. You can normally access container directly from the id but let's do it the proper way.

var conty = document.getElementById("container"),
     divs = conty.querySelectorAll("div"),
    myDiv = [...divs].filter(e => e.innerText == "SomeText");

So that's it.

How to split a long array into smaller arrays, with JavaScript

Another implementation, using Array.reduce (I think it’s the only one missing!):

const splitArray = (arr, size) =>
{
    if (size === 0) {
        return [];
    }

    return arr.reduce((split, element, index) => {
        index % size === 0 ? split.push([element]) : split[Math.floor(index / size)].push(element);
        return split;
    }, []);
};

As many solutions above, this one’s non-destructive. Returning an empty array when the size is 0 is just a convention. If the if block is omitted you get an error, which might be what you want.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.

You need to put a > tbody in between > table and > tr:

$("div.custList > table > tbody > tr")

Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):

$("div.custList table tr")

That said, you can get the immediate <td> children there by $(this).children('td').

How to find Control in TemplateField of GridView?

I have done it accessing the controls inside the cell control. Find in all control collections.

 ControlCollection cc = (ControlCollection)e.Row.Controls[1].Controls;

 Label lbCod = (Label)cc[1];

Percentage Height HTML 5/CSS

bobince's answer will let you know in which cases "height: XX%;" will or won't work.

If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom. Example for square:

<div class="square-container">
  <div class="square-content">
    <!-- put your content in here -->
  </div>
</div>

.square-container {  /* any display: block; element */
  position: relative;
  height: 0;
  padding-bottom: 100%; /* of parent width */
}
.square-content {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
}

The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I have solved this issue,

login to server computer where SQL Server is installed get you csv file on server computer and execute your query it will insert the records.

If you will give datatype compatibility issue change the datatype for that column

How to use Tomcat 8.5.x and TomEE 7.x with Eclipse?

You have to patch catalina.jar, as this is version number the WTP adapter looks at. It's a quite useless check, and the adapter should allow you to start the server anyway, but nobody has though of that yet.

For years and with every version of Tomcat this is always a problem.

To patch you can do the following:

  • cd [tomcat or tomee home]/lib
  • mkdir catalina
  • cd catalina/
  • unzip ../catalina.jar
  • vim org/apache/catalina/util/ServerInfo.properties

Make sure it looks like the following (the version numbers all need to start with 8.0):

server.info=Apache Tomcat/8.0.0
server.number=8.0.0
server.built=May 11 2016 21:49:07 UTC

Then:

  • jar uf ../catalina.jar org/apache/catalina/util/ServerInfo.properties
  • cd ..
  • rm -rf catalina

How can I get Android Wifi Scan Results into a list?

refer below link for getting ScanResult with redundant ssid removed from the list

duplicate SSID in scanning wifi result

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

jquery ajax get responsetext from http url

The only way that I know that enables you to use ajax cross-domain is JSONP (http://ajaxian.com/archives/jsonp-json-with-padding).

And here's a post that posts some various techniques to achieve cross-domain ajax (http://usejquery.com/posts/9/the-jquery-cross-domain-ajax-guide)

Number of occurrences of a character in a string

Here is the most inefficient way to get the count in all answers. But you'll get a Dictionary that contains key-value pairs as a bonus.

string test = "key1=value1&key2=value2&key3=value3";

var keyValues = Regex.Matches(test, @"([\w\d]+)=([\w\d]+)[&$]*")
                     .Cast<Match>()
                     .ToDictionary(m => m.Groups[1].Value, m => m.Groups[2].Value);

var count = keyValues.Count - 1;

Pass multiple optional parameters to a C# function

Use a parameter array with the params modifier:

public static int AddUp(params int[] values)
{
    int sum = 0;
    foreach (int value in values)
    {
        sum += value;
    }
    return sum;
}

If you want to make sure there's at least one value (rather than a possibly empty array) then specify that separately:

public static int AddUp(int firstValue, params int[] values)

(Set sum to firstValue to start with in the implementation.)

Note that you should also check the array reference for nullity in the normal way. Within the method, the parameter is a perfectly ordinary array. The parameter array modifier only makes a difference when you call the method. Basically the compiler turns:

int x = AddUp(4, 5, 6);

into something like:

int[] tmp = new int[] { 4, 5, 6 };
int x = AddUp(tmp);

You can call it with a perfectly normal array though - so the latter syntax is valid in source code as well.

How to format date in angularjs

{{convertToDate  | date :  dateformat}}                                             
$rootScope.dateFormat = 'MM/dd/yyyy';

Choosing line type and color in Gnuplot 4.0

You need to use linecolor instead of lc, like:

set style line 1 lt 1 lw 3 pt 3 linecolor rgb "red"

"help set style line" gives you more info.

Escaping Strings in JavaScript

You can also use this

_x000D_
_x000D_
let str = "hello single ' double \" and slash \\ yippie";

let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
_x000D_
_x000D_

How to add a class to a given element?

find your target element "d" however you wish and then:

d.className += ' additionalClass'; //note the space

you can wrap that in cleverer ways to check pre-existence, and check for space requirements etc..

How can I store the result of a system command in a Perl variable?

Also for eg. you can use IPC::Run:

use IPC::Run qw(run);

my $pid = 5892;
run [qw(top -H -n 1 -p), $pid],
    '|', sub { print grep { /myprocess/ } <STDIN> },
    '|', [qw(wc -l)],
    '>', \my $out;

print $out;
  • processes are running without bash subprocess
  • can be piped to perl subs
  • very similar to shell

Inserting data into a MySQL table using VB.NET

You need to use ?param instead of @param when performing queries to MySQL

 str_carSql = "insert into members_car (car_id, member_id, model, color, chassis_id, plate_number, code) values (?id,?m_id,?model,?color,?ch_id,?pt_num,?code)"
        sqlCommand.Connection = SQLConnection
        sqlCommand.CommandText = str_carSql
        sqlCommand.Parameters.AddWithValue("?id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?m_id", TextBox20.Text)
        sqlCommand.Parameters.AddWithValue("?model", TextBox23.Text)
        sqlCommand.Parameters.AddWithValue("?color", TextBox24.Text)
        sqlCommand.Parameters.AddWithValue("?ch_id", TextBox22.Text)
        sqlCommand.Parameters.AddWithValue("?pt_num", TextBox21.Text)
        sqlCommand.Parameters.AddWithValue("?code", ComboBox1.SelectedItem)
        sqlCommand.ExecuteNonQuery()

Change the catch block to see the actual exception:

  Catch ex As Exception
         MsgBox(ex.Message)   
          Return False

    End Try

How to print an unsigned char in C?

Because char is by default signed declared that means the range of the variable is

-127 to +127>

your value is overflowed. To get the desired value you have to declared the unsigned modifier. the modifier's (unsigned) range is:

 0 to 255

to get the the range of any data type follow the process 2^bit example charis 8 bit length to get its range just 2 ^(power) 8.

What's the most efficient way to check if a record exists in Oracle?

select case 
            when exists (select 1 
                         from sales 
                         where sales_type = 'Accessories') 
            then 'Y' 
            else 'N' 
        end as rec_exists
from dual;

process.waitFor() never returns

Here is a method that works for me. NOTE: There is some code within this method that may not apply to you, so try and ignore it. For example "logStandardOut(...), git-bash, etc".

private String exeShellCommand(String doCommand, String inDir, boolean ignoreErrors) {
logStandardOut("> %s", doCommand);

ProcessBuilder builder = new ProcessBuilder();
StringBuilder stdOut = new StringBuilder();
StringBuilder stdErr = new StringBuilder();

boolean isWindows = System.getProperty("os.name").toLowerCase().startsWith("windows");
if (isWindows) {
  String gitBashPathForWindows = "C:\\Program Files\\Git\\bin\\bash";
  builder.command(gitBashPathForWindows, "-c", doCommand);
} else {
  builder.command("bash", "-c", doCommand);
}

//Do we need to change dirs?
if (inDir != null) {
  builder.directory(new File(inDir));
}

//Execute it
Process process = null;
BufferedReader brStdOut;
BufferedReader brStdErr;
try {
  //Start the command line process
  process = builder.start();

  //This hangs on a large file
  // https://stackoverflow.com/questions/5483830/process-waitfor-never-returns
  //exitCode = process.waitFor();

  //This will have both StdIn and StdErr
  brStdOut = new BufferedReader(new InputStreamReader(process.getInputStream()));
  brStdErr = new BufferedReader(new InputStreamReader(process.getErrorStream()));

  //Get the process output
  String line = null;
  String newLineCharacter = System.getProperty("line.separator");

  while (process.isAlive()) {
    //Read the stdOut
    while ((line = brStdOut.readLine()) != null) {
      stdOut.append(line + newLineCharacter);
    }

    //Read the stdErr
    while ((line = brStdErr.readLine()) != null) {
      stdErr.append(line + newLineCharacter);
    }

    //Nothing else to read, lets pause for a bit before trying again
    process.waitFor(100, TimeUnit.MILLISECONDS);
  }

  //Read anything left, after the process exited
  while ((line = brStdOut.readLine()) != null) {
    stdOut.append(line + newLineCharacter);
  }

  //Read anything left, after the process exited
  while ((line = brStdErr.readLine()) != null) {
    stdErr.append(line + newLineCharacter);
  }

  //cleanup
  if (brStdOut != null) {
    brStdOut.close();
  }

  if (brStdErr != null) {
    brStdOut.close();
  }

  //Log non-zero exit values
  if (!ignoreErrors && process.exitValue() != 0) {
    String exMsg = String.format("%s%nprocess.exitValue=%s", stdErr, process.exitValue());
    throw new ExecuteCommandException(exMsg);
  }

} catch (ExecuteCommandException e) {
  throw e;
} catch (Exception e) {
  throw new ExecuteCommandException(stdErr.toString(), e);
} finally {
  //Log the results
  logStandardOut(stdOut.toString());
  logStandardError(stdErr.toString());
}

return stdOut.toString();

}

Convert dictionary to bytes and back again python?

This should work:

s=json.dumps(variables)
variables2=json.loads(s)
assert(variables==variables2)

JUnit 5: How to assert an exception is thrown?

Here is an easy way.

@Test
void exceptionTest() {

   try{
        model.someMethod("invalidInput");
        fail("Exception Expected!");
   }
   catch(SpecificException e){

        assertTrue(true);
   }
   catch(Exception e){
        fail("wrong exception thrown");
   }

}

It only succeeds when the Exception you expect is thrown.

How does += (plus equal) work?

As everyone said above

_x000D_
_x000D_
var str = "foo"
str += " bar"
console.log(str) //will now give you "foo bar"
_x000D_
_x000D_
_x000D_

Check this out as well https://www.sitepoint.com/shorthand-javascript-techniques/

How might I convert a double to the nearest integer value?

double d = 1.234;
int i = Convert.ToInt32(d);

Reference

Handles rounding like so:

rounded to the nearest 32-bit signed integer. If value is halfway between two whole numbers, the even number is returned; that is, 4.5 is converted to 4, and 5.5 is converted to 6.

IntelliJ does not show project folders

I went to File -> Project Structure -> Modules clicked on + and then import module found my root folder and selected it.

It worked.

For IntelliJ 14

Print <div id="printarea"></div> only?

All the answers so far are pretty flawed - they either involve adding class="noprint" to everything or will mess up display within #printable.

I think the best solution would be to create a wrapper around the non-printable stuff:

<head>
    <style type="text/css">

    #printable { display: none; }

    @media print
    {
        #non-printable { display: none; }
        #printable { display: block; }
    }
    </style>
</head>
<body>
    <div id="non-printable">
        Your normal page contents
    </div>

    <div id="printable">
        Printer version
    </div>
</body>

Of course this is not perfect as it involves moving things around in your HTML a bit...

how to include js file in php?

If you truly wish to use PHP, you could use

include "file.php";

or

require "file.php";

and then in file.php, use a heredoc & echo it in.

file.php contents:
$some_js_code <<<_code
function myFunction()
{
   Alert("Some JS code would go here.");
}
_code;

At the top of your PHP file, bring in the file using either include or require then in head (or body section) echo it in

<?php
require "file.php";
?>
<html>
<head>
<?php
echo $some_js_code;
?>
</script>
</head>
<body>
</body>
</html>

Different way but it works. Just my $.02...

How to change font size in Eclipse for Java text editors?

On the Eclipse toolbar, select Window ? Preferences, set the font size (General ? Appearance ? Colors and Fonts ? Basic ? Text Font).

Save the preferences.

Loop through an array of strings in Bash?

Possible first line of every Bash script/session:

say() { for line in "${@}" ; do printf "%s\n" "${line}" ; done ; }

Use e.g.:

$ aa=( 7 -4 -e ) ; say "${aa[@]}"
7
-4
-e

May consider: echo interprets -e as option here

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

Please refer the below-detailed explanation.

I have used Built-in data frame in R, called mtcars.

> mtcars 
               mpg cyl disp  hp drat   wt ... 
Mazda RX4     21.0   6  160 110 3.90 2.62 ... 
Mazda RX4 Wag 21.0   6  160 110 3.90 2.88 ... 
Datsun 710    22.8   4  108  93 3.85 2.32 ... 
           ............

The top line of the table is called the header which contains the column names. Each horizontal line afterward denotes a data row, which begins with the name of the row, and then followed by the actual data. Each data member of a row is called a cell.

single square bracket "[]" operator

To retrieve data in a cell, we would enter its row and column coordinates in the single square bracket "[]" operator. The two coordinates are separated by a comma. In other words, the coordinates begin with row position, then followed by a comma, and ends with the column position. The order is important.

Eg 1:- Here is the cell value from the first row, second column of mtcars.

> mtcars[1, 2] 
[1] 6

Eg 2:- Furthermore, we can use the row and column names instead of the numeric coordinates.

> mtcars["Mazda RX4", "cyl"] 
[1] 6 

Double square bracket "[[]]" operator

We reference a data frame column with the double square bracket "[[]]" operator.

Eg 1:- To retrieve the ninth column vector of the built-in data set mtcars, we write mtcars[[9]].

mtcars[[9]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...

Eg 2:- We can retrieve the same column vector by its name.

mtcars[["am"]] [1] 1 1 1 0 0 0 0 0 0 0 0 ...

Declaring an HTMLElement Typescript

The type comes after the name in TypeScript, partly because types are optional.

So your line:

HTMLElement el = document.getElementById('content');

Needs to change to:

const el: HTMLElement = document.getElementById('content');

Back in 2013, the type HTMLElement would have been inferred from the return value of getElementById, this is still the case if you aren't using strict null checks (but you ought to be using the strict modes in TypeScript). If you are enforcing strict null checks you will find the return type of getElementById has changed from HTMLElement to HTMLElement | null. The change makes the type more correct, because you don't always find an element.

So when using type mode, you will be encouraged by the compiler to use a type assertion to ensure you found an element. Like this:

const el: HTMLElement | null = document.getElementById('content');

if (el) {
  const definitelyAnElement: HTMLElement = el;
}

I have included the types to demonstrate what happens when you run the code. The interesting bit is that el has the narrower type HTMLElement within the if statement, due to you eliminating the possibility of it being null.

You can do exactly the same thing, with the same resulting types, without any type annotations. They will be inferred by the compiler, thus saving all that extra typing:

const el = document.getElementById('content');

if (el) {
  const definitelyAnElement = el;
}

Longer object length is not a multiple of shorter object length?

Yes, this is something that you should worry about. Check the length of your objects with nrow(). R can auto-replicate objects so that they're the same length if they differ, which means you might be performing operations on mismatched data.

In this case you have an obvious flaw in that your subtracting aggregated data from raw data. These will definitely be of different lengths. I suggest that you merge them as time series (using the dates), then locf(), then do your subtraction. Otherwise merge them by truncating the original dates to the same interval as the aggregated series. Just be very careful that you don't drop observations.

Lastly, as some general advice as you get started: look at the result of your computations to see if they make sense. You might even pull them into a spreadsheet and replicate the results.

Find where java class is loaded from

Another way to find out where a class is loaded from (without manipulating the source) is to start the Java VM with the option: -verbose:class

How to increase the timeout period of web service in asp.net?

you can do this in different ways:

  1. Setting a timeout in the web service caller from code (not 100% sure but I think I have seen this done);
  2. Setting a timeout in the constructor of the web service proxy in the web references;
  3. Setting a timeout in the server side, web.config of the web service application.

see here for more details on the second case:

http://msdn.microsoft.com/en-us/library/ff647786.aspx#scalenetchapt10_topic14

and here for details on the last case:

How to increase the timeout to a web service request?

How can I initialize C++ object member variables in the constructor?

You can specify how to initialize members in the member initializer list:

BigMommaClass {
    BigMommaClass(int, int);

private:
    ThingOne thingOne;
    ThingTwo thingTwo;
};

BigMommaClass::BigMommaClass(int numba1, int numba2)
    : thingOne(numba1 + numba2), thingTwo(numba1, numba2) {}

send Content-Type: application/json post with node.js

Mikeal's request module can do this easily:

var request = require('request');

var options = {
  uri: 'https://www.googleapis.com/urlshortener/v1/url',
  method: 'POST',
  json: {
    "longUrl": "http://www.google.com/"
  }
};

request(options, function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body.id) // Print the shortened url.
  }
});

Cleaning `Inf` values from an R dataframe

Here is a dplyr/tidyverse solution using the na_if() function:

dat %>% mutate_if(is.numeric, list(~na_if(., Inf)))

Note that this only replaces positive infinity with NA. Need to repeat if negative infinity values also need to be replaced.

dat %>% mutate_if(is.numeric, list(~na_if(., Inf))) %>% 
  mutate_if(is.numeric, list(~na_if(., -Inf)))

JIRA JQL searching by date - is there a way of getting Today() (Date) instead of Now() (DateTime)

In case you want to search for all the issues updated after 9am previous day until today at 9AM, please try: updated >= startOfDay(-15h) and updated <= startOfDay(9h). (explanation: 9AM - 24h/day = -15h)

You can also use updated >= startOfDay(-900m) . where 900m = 15h*60m

Reference: https://confluence.atlassian.com/display/JIRA/Advanced+Searching

pros and cons between os.path.exists vs os.path.isdir

os.path.exists will also return True if there's a regular file with that name.

os.path.isdir will only return True if that path exists and is a directory, or a symbolic link to a directory.

Can git undo a checkout of unstaged files

In VSCODE ctrl+z (undo) worked for me

I did git checkout .instead of git add . and all my file changes were lost.

But Now using command + z in my mac , recovered the changes and saved a tone of work for me.

How to count lines in a document?

count number of lines and store result in variable use this command:

count=$(wc -l < file.txt) echo "Number of lines: $count"

Undo a merge by pull request?

If the pull was the last thing he did then

git reset --hard HEAD~1

Executors.newCachedThreadPool() versus Executors.newFixedThreadPool()

The ThreadPoolExecutor class is the base implementation for the executors that are returned from many of the Executors factory methods. So let's approach Fixed and Cached thread pools from ThreadPoolExecutor's perspective.

ThreadPoolExecutor

The main constructor of this class looks like this:

public ThreadPoolExecutor(
                  int corePoolSize,
                  int maximumPoolSize,
                  long keepAliveTime,
                  TimeUnit unit,
                  BlockingQueue<Runnable> workQueue,
                  ThreadFactory threadFactory,
                  RejectedExecutionHandler handler
)

Core Pool Size

The corePoolSize determines the minimum size of the target thread pool. The implementation would maintain a pool of that size even if there are no tasks to execute.

Maximum Pool Size

The maximumPoolSize is the maximum number of threads that can be active at once.

After the thread pool grows and becomes bigger than the corePoolSize threshold, the executor can terminate idle threads and reach to the corePoolSize again. If allowCoreThreadTimeOut is true, then the executor can even terminate core pool threads if they were idle more than keepAliveTime threshold.

So the bottom line is if threads remain idle more than keepAliveTime threshold, they may get terminated since there is no demand for them.

Queuing

What happens when a new task comes in and all core threads are occupied? The new tasks will be queued inside that BlockingQueue<Runnable> instance. When a thread becomes free, one of those queued tasks can be processed.

There are different implementations of the BlockingQueue interface in Java, so we can implement different queuing approaches like:

  1. Bounded Queue: New tasks would be queued inside a bounded task queue.

  2. Unbounded Queue: New tasks would be queued inside an unbounded task queue. So this queue can grow as much as the heap size allows.

  3. Synchronous Handoff: We can also use the SynchronousQueue to queue the new tasks. In that case, when queuing a new task, another thread must already be waiting for that task.

Work Submission

Here's how the ThreadPoolExecutor executes a new task:

  1. If fewer than corePoolSize threads are running, tries to start a new thread with the given task as its first job.
  2. Otherwise, it tries to enqueue the new task using the BlockingQueue#offer method. The offer method won't block if the queue is full and immediately returns false.
  3. If it fails to queue the new task (i.e. offer returns false), then it tries to add a new thread to the thread pool with this task as its first job.
  4. If it fails to add the new thread, then the executor is either shut down or saturated. Either way, the new task would be rejected using the provided RejectedExecutionHandler.

The main difference between the fixed and cached thread pools boils down to these three factors:

  1. Core Pool Size
  2. Maximum Pool Size
  3. Queuing

+-----------+-----------+-------------------+---------------------------------+
| Pool Type | Core Size |    Maximum Size   |         Queuing Strategy        |
+-----------+-----------+-------------------+---------------------------------+
|   Fixed   | n (fixed) |     n (fixed)     | Unbounded `LinkedBlockingQueue` |
+-----------+-----------+-------------------+---------------------------------+
|   Cached  |     0     | Integer.MAX_VALUE |        `SynchronousQueue`       |
+-----------+-----------+-------------------+---------------------------------+


Fixed Thread Pool


Here's how the Excutors.newFixedThreadPool(n) works:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

As you can see:

  • The thread pool size is fixed.
  • If there is high demand, it won't grow.
  • If threads are idle for quite some time, it won't shrink.
  • Suppose all those threads are occupied with some long-running tasks and the arrival rate is still pretty high. Since the executor is using an unbounded queue, it may consume a huge part of the heap. Being unfortunate enough, we may experience an OutOfMemoryError.

When should I use one or the other? Which strategy is better in terms of resource utilization?

A fixed-size thread pool seems to be a good candidate when we're going to limit the number of concurrent tasks for resource management purposes.

For example, if we're going to use an executor to handle web server requests, a fixed executor can handle the request bursts more reasonably.

For even better resource management, it's highly recommended to create a custom ThreadPoolExecutor with a bounded BlockingQueue<T> implementation coupled with reasonable RejectedExecutionHandler.


Cached Thread Pool


Here's how the Executors.newCachedThreadPool() works:

public static ExecutorService newCachedThreadPool() {
    return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
                                  60L, TimeUnit.SECONDS,
                                  new SynchronousQueue<Runnable>());
}

As you can see:

  • The thread pool can grow from zero threads to Integer.MAX_VALUE. Practically, the thread pool is unbounded.
  • If any thread is idle for more than 1 minute, it may get terminated. So the pool can shrink if threads remain too much idle.
  • If all allocated threads are occupied while a new task comes in, then it creates a new thread, as offering a new task to a SynchronousQueue always fails when there is no one on the other end to accept it!

When should I use one or the other? Which strategy is better in terms of resource utilization?

Use it when you have a lot of predictable short-running tasks.

Calling multiple JavaScript functions on a button click

I think that since return validateView(); will return a value (to the click event?), your second call ShowDiv1(); will not get called.

You can always wrap multiple function calls in another function, i.e.

<asp:LinkButton OnClientClick="return display();">

function display() {
   if(validateView() && ShowDiv1()) return true;
}

You also might try:

<asp:LinkButton OnClientClick="return (validateView() && ShowDiv1());">

Though I have no idea if that would throw an exception.

Launching an application (.EXE) from C#?

Use System.Diagnostics.Process.Start() method.

Check out this article on how to use it.

Process.Start("notepad", "readme.txt");

string winpath = Environment.GetEnvironmentVariable("windir");
string path = System.IO.Path.GetDirectoryName(
              System.Windows.Forms.Application.ExecutablePath);

Process.Start(winpath + @"\Microsoft.NET\Framework\v1.0.3705\Installutil.exe",
path + "\\MyService.exe");

Which Java library provides base64 encoding/decoding?

If you're an Android developer you can use android.util.Base64 class for this purpose.

How to generate a random string in Ruby

My 2 cents:

  def token(length=16)
    chars = [*('A'..'Z'), *('a'..'z'), *(0..9)]
    (0..length).map {chars.sample}.join
  end

Read file data without saving it in Flask

We simply did:

import io
from pathlib import Path

    def test_my_upload(self, accept_json):
        """Test my uploads endpoint for POST."""
        data = {
            "filePath[]": "/tmp/bin",
            "manifest[]": (io.StringIO(str(Path(__file__).parent /
                                           "path_to_file/npmlist.json")).read(),
                           'npmlist.json'),
        }
        headers = {
            'a': 'A',
            'b': 'B'
        }
        res = self.client.post(api_route_for('/test'),
                               data=data,
                               content_type='multipart/form-data',
                               headers=headers,
                               )
        assert res.status_code == 200

How to find and return a duplicate value in array

Try this! If you want to find the maximum duplicated element with their how many time is it has duplicated then should try

    def get_maximum_duplicated_element_with_count(input_array)
        a = input_array
        max_duplicated_val = max_duplicated_val_count = 0
        a.each do |n| 
            max_duplicated_val, max_duplicated_val_count = n, a.count(n) if a.count(n) >  max_duplicated_val_count      
        end
        puts "Maximun Duplicated element Is => #{max_duplicated_val}"
        puts "#{max_duplicated_val} is Duplicated #{max_duplicated_val_count} times"
    end
    get_maximum_duplicated_element_with_count([1, 4, 4, 5, 6, 6, 2, 6])

Output will be

Maximun Duplicated element Is => 6
6 is Duplicated 3 times

How to extract code of .apk file which is not working?

Note: All of the following instructions apply universally (aka to all OSes) unless otherwise specified.


Prerequsites

You will need:

  • A working Java installation
  • A working terminal/command prompt
  • A computer
  • An APK file

Steps

Step 1: Changing the file extension of the APK file

  1. Change the file extension of the .apk file by either adding a .zip extension to the filename, or to change .apk to .zip.

    For example, com.example.apk becomes com.example.zip, or com.example.apk.zip. Note that on Windows and macOS, it may prompt you whether you are sure you want to change the file extension. Click OK or Add if you're using macOS:

macOS add extension confirm dialog

Step 2: Extracting Java files from APK

  1. Extract the renamed APK file in a specific folder. For example, let that folder be demofolder.

    • If it didn't work, try opening the file in another application such as WinZip or 7-Zip.

    • For macOS, you can try running unzip in Terminal (available at /Applications/Terminal.app), where it takes one or more arguments: the file to unzip + optional arguments. See man unzip for documentation and arguments.

  2. Download dex2jar (see all releases on GitHub) and extract that zip file in the same folder as stated in the previous point.

  3. Open command prompt (or a terminal) and change your current directory to the folder created in the previous point and type the command d2j-dex2jar.bat classes.dex and press enter. This will generate classes-dex2jar.jar file in the same folder.

    • macOS/Linux users: Replace d2j-dex2jar.bat with d2j-dex2jar.sh. In other words, run d2j-jar2dex.sh classes.dex in the terminal and press enter.
  4. Download Java Decompiler (see all releases on Github) and extract it and start (aka double click) the executable/application.

  5. From the JD-GUI window, either drag and drop the generated classes-dex2jar.jar file into it, or go to File > Open File... and browse for the jar.

  6. Next, in the menu, go to File > Save All Sources (Windows: Ctrl+Alt+S, macOS: ?+?+S). This should open a dialog asking you where to save a zip file named `classes-dex2jar.jar.src.zip" consisting of all packages and java files. (You can rename the zip file to be saved)

  7. Extract that zip file (classes-dex2jar.jar.src.zip) and you should get all java files of the application.

Step 3: Getting xml files from APK

  • For more info, see the apktool website for installation instructions and more
  • Windows:

    1. Download the wrapper script (optional) and the apktool jar (required) and place it in the same folder (for example, myxmlfolder).
    2. Change your current directory to the myxmlfolder folder and rename the apktool jar file to apktool.jar.
    3. Place the .apk file in the same folder (i.e myxmlfolder).
    4. Open the command prompt (or terminal) and change your current directory to the folder where apktool is stored (in this case, myxmlfolder). Next, type the command apktool if framework-res.apk.

      What we're doing here is that we are installing a framework. For more info, see the docs.

    5. The above command should result in "Framework installed ..."
    6. In the command prompt, type the command apktool d filename.apk (where filename is the name of apk file). This should decode the file. For more info, see the docs.

      This should result in a folder filename.out being outputted, where filename is the original name of the apk file without the .apk file extension. In this folder are all the XML files such as layout, drawables etc.

Source: How to get source code from APK file - Comptech Blogspot

Python Requests and persistent sessions

This will work for you in Python;

# Call JIRA API with HTTPBasicAuth
import json
import requests
from requests.auth import HTTPBasicAuth

JIRA_EMAIL = "****"
JIRA_TOKEN = "****"
BASE_URL = "https://****.atlassian.net"
API_URL = "/rest/api/3/serverInfo"

API_URL = BASE_URL+API_URL

BASIC_AUTH = HTTPBasicAuth(JIRA_EMAIL, JIRA_TOKEN)
HEADERS = {'Content-Type' : 'application/json;charset=iso-8859-1'}

response = requests.get(
    API_URL,
    headers=HEADERS,
    auth=BASIC_AUTH
)

print(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(",", ": ")))

Windows Scipy Install: No Lapack/Blas Resources Found

You probably just have too new (unsupported) Python 3.x installed.

This page has overcomplicated solutions to the problem. Most of numpy / scipy users should not need to compile their numpy installations or need to rely on 3rd party "numpy+mkl" wheels.

Downloading a compiler is an anti-pattern, you do not want to build numpy, only use it. [github.com/numpy]

Solution

  • Once you have installed supported python version, remove your non-working numpy installation with
pip uninstall numpy

and install scipy with

pip install scipy --only-binary numpy
  • The --only-binary numpy will force installing binary wheel (.whl) version of numpy. If it fails, you have too new (not yet supported) version of python.

  • If you have multiple python versions installed, you can ensure that pip is installing the python version you want by

<path_to_python_executable> -m pip install <X> 

instead of pip install <X>.

Why this is happening?

  • Scipy relies on numpy, as can be seen from the setup.py or just by reading the pip install logs.
  • If you have too new (non-supported) python installation, there are no built wheel (.whl) in the pip repository, but tarballs (.tar.gz), which in this case require the user machine to compile some C++-code during installation. See also: Python packaging: wheels vs tarball (tar.gz)

Appendix

  • Check the https://pypi.org/project/numpy/ for list of supported Python versions. Currently (2020-11-04) the newest supported python version is Python 3.9. when using numpy 1.19.3 or above, and Python 3.8 for numpy 1.19.2. (For compatibility of older numpy versions, see numpy release notes)
  • If you are on Windows and see pip trying to install numpy-<x>.tag.gz, you know it probably will not work. Try older version of Python, instead. You want to see pip to installing a binary wheel for numpy for Windows (numpy-<x>.whl). You can check the wheels in pip available for numpy here.

How to set transparent background for Image Button in code?

Do it in your xml

<ImageButton
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/imageButtonSettings"
        android:layout_gravity="right|bottom"
        android:src="@drawable/tabbar_settings_icon"
        android:background="@android:color/transparent"/>

find the array index of an object with a specific key value in underscore

you can use indexOf method from lodash

var tv = [{id:1},{id:2}]
var voteID = 2;
var data = _.find(tv, function(voteItem){ return voteItem.id == voteID; });
var index=_.indexOf(tv,data);

Oracle SQL: Use sequence in insert with Select Statement

Assuming that you want to group the data before you generate the key with the sequence, it sounds like you want something like

INSERT INTO HISTORICAL_CAR_STATS (
    HISTORICAL_CAR_STATS_ID, 
    YEAR,
    MONTH, 
    MAKE,
    MODEL,
    REGION,
    AVG_MSRP,
    CNT) 
SELECT MY_SEQ.nextval,
       year,
       month,
       make,
       model,
       region,
       avg_msrp,
       cnt
  FROM (SELECT '2010' year,
               '12' month,
               'ALL' make,
               'ALL' model,
               REGION,
               sum(AVG_MSRP*COUNT)/sum(COUNT) avg_msrp,
               sum(cnt) cnt
          FROM HISTORICAL_CAR_STATS
         WHERE YEAR = '2010' 
           AND MONTH = '12'
           AND MAKE != 'ALL' 
         GROUP BY REGION)

Android Studio gradle takes too long to build

Enabling Java 8 features caused deadly slow build

gradle

 jackOptions {
        enabled true
  }

  compileOptions {
    targetCompatibility 1.8
    sourceCompatibility 1.8
}

After deleting above lines, it builds in seconds.

There is issue Compiling with Jack takes very long time

Project Manager's Answer

We're aware that build times are an issue with Jack right now. We have improvements in the 2.4 Gradle plugin that should be a significant improvement for incremental builds.

As of now, latest Gradle version i can find is 2.3.0-beta4

Convert integer value to matching Java Enum

if you have enum like this

public enum PcapLinkType {
  DLT_NULL(0)
  DLT_EN10MB(1)
  DLT_EN3MB(2),
  DLT_AX25(3),
  DLT_UNKNOWN(-1);

    private final int value;   

    PcapLinkType(int value) {
        this.value= value;
    }
}

then you can use it like

PcapLinkType type = PcapLinkType.values()[1]; /*convert val to a PcapLinkType */

want current date and time in "dd/MM/yyyy HH:mm:ss.SS" format

SimpleDateFormat

sdf=new SimpleDateFormat("dd/MM/YYYY hh:mm:ss");
String dateString=sdf.format(date);

It will give the output 28/09/2013 09:57:19 as you expected.

For complete program click here

How to create an HTML button that acts like a link?

In JavaScript

setLocation(base: string) {
  window.location.href = base;
}

In HTML

<button onclick="setLocation('/<whatever>')>GO</button>"

Copy every nth line from one sheet to another

In A1 of your new sheet, put this:

=OFFSET(Sheet1!$A$1,(ROW()-1)*7,0)

... and copy down. If you start somewhere other than row 1, change ROW() to ROW(A1) or some other cell on row 1, then copy down again.

If you want to copy the nth line but multiple columns, use the formula:

=OFFSET(Sheet1!A$1,(ROW()-1)*7,0)

This can be copied right too.

With jQuery, how do I capitalize the first letter of a text field while the user is still editing that field?

this will help you in - convert first letter of each word to uppercase

<script>
  /* convert First Letter UpperCase */
  $('#txtField').on('keyup', function (e) {
    var txt = $(this).val();
    $(this).val(txt.replace(/^(.)|\s(.)/g, function ($1) {
      return $1.toUpperCase( );
    }));
  });
</script>

Example : this is a title case sentence -> This Is A Title Case Sentence

assignment operator overloading in c++

this might be helpful:

// Operator overloading in C++
//assignment operator overloading
#include<iostream>
using namespace std;

class Employee
{
private:
int idNum;
double salary;
public:
Employee ( ) {
    idNum = 0, salary = 0.0;
}

void setValues (int a, int b);
void operator= (Employee &emp );

};

void Employee::setValues ( int idN , int sal )
{

salary = sal; idNum = idN;

}

void Employee::operator = (Employee &emp)  // Assignment operator overloading function
{
salary = emp.salary;
}

int main ( )
{

Employee emp1;
emp1.setValues(10,33);
Employee emp2;
emp2 = emp1; // emp2 is calling object using assignment operator

}

"Rate This App"-link in Google Play store app on the phone

Here is my version using the BuildConfig class:

Intent marketIntent = new Intent(Intent.ACTION_VIEW, uri);

marketIntent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    marketIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_DOCUMENT);
}

try {
    startActivity(marketIntent);
} catch (ActivityNotFoundException e) {
    startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + BuildConfig.APPLICATION_ID)));
}

coercing to Unicode: need string or buffer, NoneType found when rendering in django admin

First, check that whatever you are returning via unicode is a String.

If it is not a string you can change it to a string like this (where self.id is an integer)

def __unicode__(self):
    return '%s' % self.id

following which, if it still doesn't work, restart your ./manage.py shell for the changes to take effect and try again. It should work.

Best Regards

Border around specific rows in a table?

If you set the border-collapse style to collapse on the parent table you should be able to style the tr: (styles are inline for demo)

<table style="border-collapse: collapse;">
  <tr>
    <td>No Border</td>
  </tr>
  <tr style="border:2px solid #f00;">
    <td>Border</td>
  </tr>
  <tr>
    <td>No Border</td>
  </tr>
</table>

Output:

HTML output

CSS display:inline property with list-style-image: property on <li> tags

If you look at the 'display' property in the CSS spec, you will see that 'list-item' is specifically a display type. When you set an item to "inline", you're replacing the default display type of list-item, and the marker is specifically a part of the list-item type.

The above answer suggests float, but I've tried that and it doesn't work (at least on Chrome). According to the spec, if you set your boxes to float left or right,"The 'display' is ignored, unless it has the value 'none'." I take this to mean that the default display type of 'list-item' is gone (taking the marker with it) as soon as you float the element.

Edit: Yeah, I guess I was wrong. See top entry. :)

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Normally, you'd get an RST if you do a close which doesn't linger (i.e. in which data can be discarded by the stack if it hasn't been sent and ACK'd) and a normal FIN if you allow the close to linger (i.e. the close waits for the data in transit to be ACK'd).

Perhaps all you need to do is set your socket to linger so that you remove the race condition between a non lingering close done on the socket and the ACKs arriving?

Ruby on Rails: how to render a string as HTML?

Use raw:

<%=raw @str >

But as @jmort253 correctly says, consider where the HTML really belongs.

How do I deal with certificates using cURL while trying to access an HTTPS url?

It seems your curl points to a non-existing file with CA certs or similar.

For the primary reference on CA certs with curl, see: https://curl.haxx.se/docs/sslcerts.html

Best way to run scheduled tasks

If you own the server you should use the windows task scheduler. Use AT /? from the command line to see the options.

Otherwise, from a web based environment, you might have to do something nasty like set up a different machine to make requests to a certain page on a timed interval.

How to split a comma-separated string?

For completeness, using the Guava library, you'd do: Splitter.on(",").split(“dog,cat,fox”)

Another example:

String animals = "dog,cat, bear,elephant , giraffe ,  zebra  ,walrus";
List<String> l = Lists.newArrayList(Splitter.on(",").trimResults().split(animals));
// -> [dog, cat, bear, elephant, giraffe, zebra, walrus]

Splitter.split() returns an Iterable, so if you need a List, wrap it in Lists.newArrayList() as above. Otherwise just go with the Iterable, for example:

for (String animal : Splitter.on(",").trimResults().split(animals)) {
    // ...
}

Note how trimResults() handles all your trimming needs without having to tweak regexes for corner cases, as with String.split().

If your project uses Guava already, this should be your preferred solution. See Splitter documentation in Guava User Guide or the javadocs for more configuration options.

Simultaneously merge multiple data.frames in a list

I will reuse the data example from @PaulRougieux

x <- data_frame(i = c("a","b","c"), j = 1:3)
y <- data_frame(i = c("b","c","d"), k = 4:6)
z <- data_frame(i = c("c","d","a"), l = 7:9)

Here's a short and sweet solution using purrr and tidyr

library(tidyverse)

 list(x, y, z) %>% 
  map_df(gather, key=key, value=value, -i) %>% 
  spread(key, value)

How to check if an environment variable exists and get its value?

All the answers worked. However, I had to add the variables that I needed to get to the sudoers files as follows:

sudo visudo
Defaults env_keep += "<var1>, <var2>, ..., <varn>"

Vertically align an image inside a div with responsive height

Use this css, as you already have the markup for it:

.img-container {
    position: absolute;
    top: 50%;
    left: 50%;
}

.img-container > img {
  margin-top:-50%;
  margin-left:-50%;  
}

Here is a working JsBin: http://jsbin.com/ihilUnI/1/edit

This solution only works for square images (because a percentage margin-top value depends on the width of the container, not the height). For random-size images, you can do the following:

.img-container {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%); /* add browser-prefixes */
}

Working JsBin solution: http://jsbin.com/ihilUnI/2/edit

Eventviewer eventid for lock and unlock

For newer versions of Windows (including but not limited to both Windows 10 and Windows Server 2016), the event IDs are:

  • 4800 - The workstation was locked.
  • 4801 - The workstation was unlocked.

Locking and unlocking a workstation also involve the following logon and logoff events:

  • 4624 - An account was successfully logged on.
  • 4634 - An account was logged off.
  • 4648 - A logon was attempted using explicit credentials.

When using a Terminal Services session, locking and unlocking may also involve the following events if the session is disconnected, and event 4778 may replace event 4801:

  • 4779 - A session was disconnected from a Window Station.
  • 4778 - A session was reconnected to a Window Station.

Events 4800 and 4801 are not audited by default, and must be enabled using either Local Group Policy Editor (gpedit.msc) or Local Security Policy (secpol.msc).

The path for the policy using Local Group Policy Editor is:

  • Local Computer Policy
  • Computer Configuration
  • Windows Settings
  • Security Settings
  • Advanced Audit Policy Configuration
  • System Audit Policies - Local Group Policy Object
  • Logon/Logoff
  • Audit Other Logon/Logoff Events

The path for the policy using Local Security Policy is the following subset of the path for Local Group Policy Editor:

  • Security Settings
  • Advanced Audit Policy Configuration
  • System Audit Policies - Local Group Policy Object
  • Logon/Logoff
  • Audit Other Logon/Logoff Events

Eclipse CDT: Symbol 'cout' could not be resolved

I had the same issue using Eclipse CDT (Kepler) on Windows with Cygwin installed. After pointing the project properties at every Cygwin include I could think of, it still couldn't find cout.

The final missing piece turned out to be C:cygwin64\lib\gcc\x86_64-pc-cygwin\4.8.2\install-tool\include.

To sum up:

  • Right click on the project
  • Choose Properties
  • Navigate to C/C++ General > Paths and Symbols > Includes tab
  • Click Add...
  • Click File system...
  • Browse to the location of your Cygwin lib\gcc\x86_64-pc-cygwin\4.8.2\install-tool\include
  • Click OK

Here is what my project includes ended up looking like when it was all said and done: enter image description here

Is there a way in Pandas to use previous row value in dataframe.apply when previous value is also calculated in the apply?

In general, the key to avoiding an explicit loop would be to join (merge) 2 instances of the dataframe on rowindex-1==rowindex.

Then you would have a big dataframe containing rows of r and r-1, from where you could do a df.apply() function.

However the overhead of creating the large dataset may offset the benefits of parallel processing...

#ifdef in C#

C# does have a preprocessor. It works just slightly differently than that of C++ and C.

Here is a MSDN links - the section on all preprocessor directives.

Batch not-equal (inequality) operator

I know this is quite out of date, but this might still be useful for those coming late to the party. (EDIT: updated since this still gets traffic and @Goozak has pointed out in the comments that my original analysis of the sample was incorrect as well.)

I pulled this from the example code in your link:

IF !%1==! GOTO VIEWDATA
REM  IF NO COMMAND-LINE ARG...
FIND "%1" C:\BOZO\BOOKLIST.TXT
GOTO EXIT0
REM  PRINT LINE WITH STRING MATCH, THEN EXIT.

:VIEWDATA
TYPE C:\BOZO\BOOKLIST.TXT | MORE
REM  SHOW ENTIRE FILE, 1 PAGE AT A TIME.

:EXIT0

!%1==! is simply an idiomatic use of == intended to verify that the thing on the left, that contains your variable, is different from the thing on the right, that does not. The ! in this case is just a character placeholder. It could be anything. If %1 has content, then the equality will be false, if it does not you'll just be comparing ! to ! and it will be true.

!==! is not an operator, so writing "asdf" !==! "fdas" is pretty nonsensical.

The suggestion to use if not "asdf" == "fdas" is definitely the way to go.

Setting DIV width and height in JavaScript

The onclick attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.

How do I get the HTTP status code with jQuery?

The third argument is the XMLHttpRequest object, so you can do whatever you want.

$.ajax({
  url  : 'http://example.com',
  type : 'post',
  data : 'a=b'
}).done(function(data, statusText, xhr){
  var status = xhr.status;                //200
  var head = xhr.getAllResponseHeaders(); //Detail header info
});

Random String Generator Returning Same String

You're instantiating the Random object inside your method.

The Random object is seeded from the system clock, which means that if you call your method several times in quick succession it'll use the same seed each time, which means that it'll generate the same sequence of random numbers, which means that you'll get the same string.

To solve the problem, move your Random instance outside of the method itself (and while you're at it you could get rid of that crazy sequence of calls to Convert and Floor and NextDouble):

private readonly Random _rng = new Random();
private const string _chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private string RandomString(int size)
{
    char[] buffer = new char[size];

    for (int i = 0; i < size; i++)
    {
        buffer[i] = _chars[_rng.Next(_chars.Length)];
    }
    return new string(buffer);
}

Change Color of Fonts in DIV (CSS)

To do links, you can do

.social h2 a:link {
  color: pink;
  font-size: 14px;   
}

You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.

how to remove time from datetime

First thing's first, if your dates are in varchar format change that, store dates as dates it will save you a lot of headaches and it is something that is best done sooner rather than later. The problem will only get worse.

Secondly, once you have a date DO NOT convert the date to a varchar! Keep it in date format and use formatting on the application side to get the required date format.

There are various methods to do this depending on your DBMS:


SQL-Server 2008 and later:

SELECT  CAST(CURRENT_TIMESTAMP AS DATE)

SQL-Server 2005 and Earlier

SELECT  DATEADD(DAY, DATEDIFF(DAY, 0, CURRENT_TIMESTAMP), 0)

SQLite

SELECT  DATE(NOW())

Oracle

SELECT  TRUNC(CURRENT_TIMESTAMP)

Postgresql

SELECT  CURRENT_TIMESTAMP::DATE

If you need to use culture specific formatting in your report you can either explicitly state the format of the receiving text box (e.g. dd/MM/yyyy), or you can set the language so that it shows the relevant date format for that language.

Either way this is much better handled outside of SQL as converting to varchar within SQL will impact any sorting you may do in your report.

If you cannot/will not change the datatype to DATETIME, then still convert it to a date within SQL (e.g. CONVERT(DATETIME, yourField)) before sending to report services and handle it as described above.

How to calculate an angle from three points?

The best way to deal with angle computation is to use atan2(y, x) that given a point x, y returns the angle from that point and the X+ axis in respect to the origin.

Given that the computation is

double result = atan2(P3.y - P1.y, P3.x - P1.x) -
                atan2(P2.y - P1.y, P2.x - P1.x);

i.e. you basically translate the two points by -P1 (in other words you translate everything so that P1 ends up in the origin) and then you consider the difference of the absolute angles of P3 and of P2.

The advantages of atan2 is that the full circle is represented (you can get any number between -p and p) where instead with acos you need to handle several cases depending on the signs to compute the correct result.

The only singular point for atan2 is (0, 0)... meaning that both P2 and P3 must be different from P1 as in that case doesn't make sense to talk about an angle.

import an array in python

(I know the question is old, but I think this might be good as a reference for people with similar questions)

If you want to load data from an ASCII/text file (which has the benefit or being more or less human-readable and easy to parse in other software), numpy.loadtxt is probably what you want:

If you just want to quickly save and load numpy arrays/matrices to and from a file, take a look at numpy.save and numpy.load:

TypeError: worker() takes 0 positional arguments but 1 was given

class KeyStatisticCollection(DataDownloadUtilities.DataDownloadCollection):
def GenerateAddressStrings(self):
    pass    
def worker(self):
    pass
def DownloadProc(self):
    pass

How to revert uncommitted changes including files and folders?

I think you can use the following command: git reset --hard

JS: Uncaught TypeError: object is not a function (onclick)

Please change only the name of the function; no other change is required

<script>
    function totalbandwidthresult() {
        alert("fdf");
        var fps = Number(document.calculator.fps.value);
        var bitrate = Number(document.calculator.bitrate.value);
        var numberofcameras = Number(document.calculator.numberofcameras.value);
        var encoding = document.calculator.encoding.value;
        if (encoding = "mjpeg") {
            storage = bitrate * fps;
        } else {
            storage = bitrate;
        }

        totalbandwidth = (numberofcameras * storage) / 1000;
        alert(totalbandwidth);
        document.calculator.totalbandwidthresult.value = totalbandwidth;
    }
</script>

<form name="calculator" class="formtable">
    <div class="formrow">
        <label for="rcname">RC Name</label>
        <input type="text" name="rcname">
    </div>
    <div class="formrow">
        <label for="fps">FPS</label>
        <input type="text" name="fps">
    </div>
    <div class="formrow">
        <label for="bitrate">Bitrate</label>
        <input type="text" name="bitrate">
    </div>
    <div class="formrow">
        <label for="numberofcameras">Number of Cameras</label>
        <input type="text" name="numberofcameras">
    </div>
    <div class="formrow">
        <label for="encoding">Encoding</label>
        <select name="encoding" id="encodingoptions">
            <option value="h264">H.264</option>
            <option value="mjpeg">MJPEG</option>
            <option value="mpeg4">MPEG4</option>
        </select>
    </div>Total Storage:
    <input type="text" name="totalstorage">Total Bandwidth:
    <input type="text" name="totalbandwidth">
    <input type="button" value="totalbandwidthresult" onclick="totalbandwidthresult();">
</form>

Java Map equivalent in C#

Dictionary<,> is the equivalent. While it doesn't have a Get(...) method, it does have an indexed property called Item which you can access in C# directly using index notation:

class Test {
  Dictionary<int,String> entities;

  public String getEntity(int code) {
    return this.entities[code];
  }
}

If you want to use a custom key type then you should consider implementing IEquatable<> and overriding Equals(object) and GetHashCode() unless the default (reference or struct) equality is sufficient for determining equality of keys. You should also make your key type immutable to prevent weird things happening if a key is mutated after it has been inserted into a dictionary (e.g. because the mutation caused its hash code to change).

How do I fit an image (img) inside a div and keep the aspect ratio?

I was having a lot of problems to get this working, every single solution I found didn't seem to work.

I realized that I had to set the div display to flex, so basically this is my CSS:

div{
display: flex;
}

div img{ 
max-height: 100%;
max-width: 100%;
}

Getting android.content.res.Resources$NotFoundException: exception even when the resource is present in android

This can happen due to a different language in the phone for which your code doesn't have the asset for. For example your preference.xml is placed in xml-en and you are trying to run your app in a phone which has French selected, the app will crash.

Can you run GUI applications in a Docker container?

Docker with BRIDGE network. for Ubuntu 16.04 with display manager lightdm:

cd /etc/lightdm/lightdm.conf.d
sudo nano user.conf

[Seat:*]
xserver-allow-tcp=true
xserver-command=X -listen tcp

you can use more private permissions

xhost +

docker run --volume="$HOME/.Xauthority:/root/.Xauthority:rw" --env="DISPLAY=$HOST_IP_IN_BRIDGE_NETWORK:0" --net=bridge $container_name

Javascript change Div style

Better change the class of the element (.regular is black, .alert is red):

function abc(){
  var myDiv = document.getElementById("test");
  if (myDiv.className == 'alert') {
    myDiv.className = 'regular';
  } else {
    myDiv.className = 'alert';
  }
}

In nodeJs is there a way to loop through an array without using array size?

In ES5 there is no efficient way to iterate over a sparse array without using the length property. In ES6 you can use for...of. Take this examples:

_x000D_
_x000D_
'use strict';_x000D_
_x000D_
var arr = ['one', 'two', undefined, 3, 4],_x000D_
    output;_x000D_
_x000D_
arr[6] = 'five';_x000D_
_x000D_
output = '';_x000D_
arr.forEach(function (val) {_x000D_
    output += val + ' ';_x000D_
});_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var i = 0; i < arr.length; i++) {_x000D_
    output += arr[i] + ' ';_x000D_
}_x000D_
console.log(output);_x000D_
_x000D_
output = '';_x000D_
for (var val of arr) {_x000D_
    output += val + ' ';_x000D_
};_x000D_
console.log(output);
_x000D_
<!-- results pane console output; see http://meta.stackexchange.com/a/242491 -->_x000D_
<script src="//gh-canon.github.io/stack-snippet-console/console.min.js"></script>
_x000D_
_x000D_
_x000D_

All array methods which you can use to iterate safely over dense arrays use the length property of an object created by calling ToObject internaly. See for instance the algorithm used in the forEach method: http://www.ecma-international.org/ecma-262/5.1/#sec-15.4.4.18 However in es6, you can use for...of safely for iterating over sparse arrays.

See also Are Javascript arrays sparse?.

Why do Twitter Bootstrap tables always have 100% width?

<table style="width: auto;" ... works fine. Tested in Chrome 38 , IE 11 and Firefox 34.

jsfiddle : http://jsfiddle.net/rpaul/taqodr8o/

How to pass arguments and redirect stdin from a file to program run in gdb?

You can do this:

gdb --args path/to/executable -every -arg you can=think < of

The magic bit being --args.

Just type run in the gdb command console to start debugging.

What is the facade design pattern?

Regarding your queries:

Is Facade a class which contains a lot of other classes?

Yes. It is a wrapper for many sub-systems in application.

What makes it a design pattern? For me, it is like a normal class

All design patterns too are normal classes. @Unmesh Kondolikar rightly answered this query.

Can you explain me about this Facade, I am new to design patterns.

According to GoF, Facade design pattern is defind as :

Provide a unified interface to a set of interfaces in a subsystem. Facade Pattern defines a higher-level interface that makes the subsystem easier to use

The Facade pattern is typically used when:

  1. A simple interface is required to access a complex system.
  2. The abstractions and implementations of a subsystem are tightly coupled.
  3. Need an entry point to each level of layered software.
  4. System is very complex or difficult to understand.

Let's take a real word example of cleartrip website.

This website provides options to book

  1. Flights
  2. Hotels
  3. Flights + Hotels

Code snippet:

import java.util.*;

public class TravelFacade{
    FlightBooking flightBooking;
    TrainBooking trainBooking;
    HotelBooking hotelBooking;

    enum BookingType {
        Flight,Train,Hotel,Flight_And_Hotel,Train_And_Hotel;
    }; 

    public TravelFacade(){
        flightBooking = new FlightBooking();
        trainBooking = new TrainBooking();
        hotelBooking = new HotelBooking();        
    }
    public void book(BookingType type, BookingInfo info){
        switch(type){
            case Flight:
                // book flight;
                flightBooking.bookFlight(info);
                return;
            case Hotel:
                // book hotel;
                hotelBooking.bookHotel(info);
                return;
            case Train:
                // book Train;
                trainBooking.bookTrain(info);
                return;
            case Flight_And_Hotel:
                // book Flight and Hotel
                flightBooking.bookFlight(info);
                hotelBooking.bookHotel(info);
                return;
             case Train_And_Hotel:
                // book Train and Hotel
                trainBooking.bookTrain(info);
                hotelBooking.bookHotel(info);
                return;                
        }
    }
}
class BookingInfo{
    String source;
    String destination;
    Date    fromDate;
    Date     toDate;
    List<PersonInfo> list;
}
class PersonInfo{
    String name;
    int       age;
    Address address;
}
class Address{

}
class FlightBooking{
    public FlightBooking(){

    }
    public void bookFlight(BookingInfo info){

    }
}
class HotelBooking{
    public HotelBooking(){

    }
    public void bookHotel(BookingInfo info){

    }
}
class TrainBooking{
    public TrainBooking(){

    }
    public void bookTrain(BookingInfo info){

    }
}

Explanation:

  1. FlightBooking, TrainBooking and HotelBooking are different sub-systems of large system : TravelFacade

  2. TravelFacade offers a simple interface to book one of below options

    Flight Booking
    Train Booking 
    Hotel Booking
    Flight + Hotel booking 
    Train + Hotel booking
    
  3. book API from TravelFacade internally calls below APIs of sub-systems

    flightBooking.bookFlight
    trainBooking.bookTrain(info);
    hotelBooking.bookHotel(info);
    
  4. In this way, TravelFacade provides simpler and easier API with-out exposing sub-system APIs.

Key takeaways : ( from journaldev article by Pankaj Kumar)

  1. Facade pattern is more like a helper for client applications
  2. Facade pattern can be applied at any point of development, usually when the number of interfaces grow and system gets complex.
  3. Subsystem interfaces are not aware of Facade and they shouldn’t have any reference of the Facade interface
  4. Facade pattern should be applied for similar kind of interfaces, its purpose is to provide a single interface rather than multiple interfaces that does the similar kind of jobs

Have a look at sourcemaking article too for better understanding.

How to get URL parameters with Javascript?

function getURLParameter(name) {
  return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.search) || [null, ''])[1].replace(/\+/g, '%20')) || null;
}

So you can use:

myvar = getURLParameter('myvar');

Best dynamic JavaScript/JQuery Grid

you can try http://datatables.net/

DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table. Key features:

  • Variable length pagination
  • On-the-fly filtering
  • Multi-column sorting with data type detection
  • Smart handling of column widths
  • Display data from almost any data source
  • DOM, Javascript array, Ajax file and server-side processing (PHP, C#, Perl, Ruby, AIR, Gears etc)
  • Scrolling options for table viewport
  • Fully internationalisable
  • jQuery UI ThemeRoller support
  • Rock solid - backed by a suite of 2600+ unit tests
  • Wide variety of plug-ins inc. TableTools, FixedColumns, KeyTable and more
  • It's free!
  • State saving
  • Hidden columns
  • Dynamic creation of tables
  • Ajax auto loading of data
  • Custom DOM positioning
  • Single column filtering
  • Alternative pagination types
  • Non-destructive DOM interaction
  • Sorting column(s) highlighting
  • Advanced data source options
  • Extensive plug-in support
  • Sorting, type detection, API functions, pagination and filtering
  • Fully themeable by CSS
  • Solid documentation
  • 110+ pre-built examples
  • Full support for Adobe AIR

How do I make a PHP form that submits to self?

  1. change
    <input type="submit" value="Submit" />
    to
    <input type="submit" value="Submit" name='submit'/>

  2. change
    <form method="post" action="<?php echo $PHP_SELF;?>">
    to
    <form method="post" action="">

  3. It will perform the code in if only when it is submitted.
  4. It will always show the form (html code).
  5. what exactly is your question?

How to remove elements/nodes from angular.js array

Using the indexOf function was not cutting it on my collection of REST resources.

I had to create a function that retrieves the array index of a resource sitting in a collection of resources:

factory.getResourceIndex = function(resources, resource) {
  var index = -1;
  for (var i = 0; i < resources.length; i++) {
    if (resources[i].id == resource.id) {
      index = i;
    }
  }
  return index;
}

$scope.unassignedTeams.splice(CommonService.getResourceIndex($scope.unassignedTeams, data), 1);

MySQL - UPDATE query based on SELECT Query

You can use:

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

Fully change package name including company domain

1) Open the project folder in Android Studio.
2) Select app folder -> Right click, and select refactor.
3) Click on move. It will ask to which package name type you own full package name and it will ask to create a new package yes create new automatically it ask for gradle to sync.

Concatenate columns in Apache Spark DataFrame

val newDf =
  df.withColumn(
    "NEW_COLUMN",
    concat(
      when(col("COL1").isNotNull, col("COL1")).otherwise(lit("null")),
      when(col("COL2").isNotNull, col("COL2")).otherwise(lit("null"))))

Note: For this code to work you need to put the parentheses "()" in the "isNotNull" function. -> The correct one is "isNotNull()".

val newDf =
  df.withColumn(
    "NEW_COLUMN",
    concat(
      when(col("COL1").isNotNull(), col("COL1")).otherwise(lit("null")),
      when(col("COL2").isNotNull(), col("COL2")).otherwise(lit("null"))))

Reverse ip, find domain names on ip address

This worked for me to get domain in intranet

https://gist.github.com/jrothmanshore/2656003

It's a powershell script. Run it in PowerShell

.\ip_lookup.ps1 <ip>

Boolean operators && and ||

&& and || are what is called "short circuiting". That means that they will not evaluate the second operand if the first operand is enough to determine the value of the expression.

For example if the first operand to && is false then there is no point in evaluating the second operand, since it can't change the value of the expression (false && true and false && false are both false). The same goes for || when the first operand is true.

You can read more about this here: http://en.wikipedia.org/wiki/Short-circuit_evaluation From the table on that page you can see that && is equivalent to AndAlso in VB.NET, which I assume you are referring to.

Can we use join for two different database tables?

SQL Server allows you to join tables from different databases as long as those databases are on the same server. The join syntax is the same; the only difference is that you must fully specify table names.

Let's suppose you have two databases on the same server - Db1 and Db2. Db1 has a table called Clients with a column ClientId and Db2 has a table called Messages with a column ClientId (let's leave asside why those tables are in different databases).

Now, to perform a join on the above-mentioned tables you will be using this query:

select *
from Db1.dbo.Clients c
join Db2.dbo.Messages m on c.ClientId = m.ClientId

How to prevent going back to the previous activity?

Put

finish();

immediately after ActivityStart to stop the activity preventing any way of going back to it. Then add

onCreate(){
    getActionBar().setDisplayHomeAsUpEnabled(false);
    ...
}

to the activity you are starting.

jQuery AutoComplete Trigger Change Event

I was trying to do the same, but without keeping a variable of autocomplete. I walk throught this calling change handler programatically on the select event, you only need to worry about the actual value of input.

$("#CompanyList").autocomplete({ 
    source: context.companies, 
    change: handleCompanyChanged,
    select: function(event,ui){
        $("#CompanyList").trigger('blur');
        $("#CompanyList").val(ui.item.value);
        handleCompanyChanged();
    }
});

Convert RGB values to Integer

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.

Android XML Percent Symbol

Try using a backslash in front of it, like below:

\%

Two Divs on the same row and center align both of them

Better way till now:

  1. If you give display:inline-block; to inner divs then child elements of inner divs will also get this property and disturb alignment of inner divs.

  2. Better way is to use two different classes for inner divs with width, margin and float.

Best way till now:

Use flexbox.

http://css-tricks.com/snippets/css/a-guide-to-flexbox/

WooCommerce - get category for product page

A WC product may belong to none, one or more WC categories. Supposing you just want to get one WC category id.

global $post;
$terms = get_the_terms( $post->ID, 'product_cat' );
foreach ($terms as $term) {
    $product_cat_id = $term->term_id;
    break;
}

Please look into the meta.php file in the "templates/single-product/" folder of the WooCommerce plugin.

<?php echo $product->get_categories( ', ', '<span class="posted_in">' . _n( 'Category:', 'Categories:', sizeof( get_the_terms( $post->ID, 'product_cat' ) ), 'woocommerce' ) . ' ', '.</span>' ); ?>

HTTP GET in VBS

Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.

Why do I get permission denied when I try use "make" to install something?

The problem is frequently with 'secure' setup of mountpoints, such as /tmp

If they are mounted noexec (check with cat /etc/mtab and or sudo mount) then there is no permission to execute any binaries or build scripts from within the (temporary) folder.

E.g. to remount temporarily:

 sudo mount -o remount,exec /tmp

Or to change permanently, remove noexec in /etc/fstab

Normalize data in pandas

This is how you do it column-wise:

[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

CTRL+R, CTRL+W : Toggle showing whitespace

or under the Edit Menu:

  • Edit -> Advanced -> View White Space

[BTW, it also appears you are using Tabs. It's common practice to have the IDE turn Tabs into spaces (often 4), via Options.]

Remove an onclick listener

    /**
 * Remove an onclick listener
 *
 * @param view
 * @author [email protected]
 * @website https://github.com/androidmalin
 * @data 2016-05-16
 */
public static void unBingListener(View view) {
    if (view != null) {
        try {
            if (view.hasOnClickListeners()) {
                view.setOnClickListener(null);

            }

            if (view.getOnFocusChangeListener() != null) {
                view.setOnFocusChangeListener(null);

            }

            if (view instanceof ViewGroup && !(view instanceof AdapterView)) {
                ViewGroup viewGroup = (ViewGroup) view;
                int viewGroupChildCount = viewGroup.getChildCount();
                for (int i = 0; i < viewGroupChildCount; i++) {
                    unBingListener(viewGroup.getChildAt(i));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Is object empty?

var x= {}
var y= {x:'hi'}
console.log(Object.keys(x).length===0)
console.log(Object.keys(y).length===0)

true
false

http://jsfiddle.net/j7ona6hz/1/

What is an optional value in Swift?

An optional in Swift is a type that can hold either a value or no value. Optionals are written by appending a ? to any type:

var name: String?

You can refer to this link to get knowledge in deep: https://medium.com/@agoiabeladeyemi/optionals-in-swift-2b141f12f870

How to export and import a .sql file from command line with options?

You can use this script to export or import any database from terminal given at this link: https://github.com/Ridhwanluthra/mysql_import_export_script/blob/master/mysql_import_export_script.sh

echo -e "Welcome to the import/export database utility\n"
echo -e "the default location of mysqldump file is: /opt/lampp/bin/mysqldump\n"
echo -e "the default location of mysql file is: /opt/lampp/bin/mysql\n"
read -p 'Would like you like to change the default location [y/n]: ' location_change
read -p "Please enter your username: " u_name
read -p 'Would you like to import or export a database: [import/export]: ' action
echo

mysqldump_location=/opt/lampp/bin/mysqldump
mysql_location=/opt/lampp/bin/mysql

if [ "$action" == "export" ]; then
    if [ "$location_change" == "y" ]; then
        read -p 'Give the location of mysqldump that you want to use: ' mysqldump_location
        echo
    else
        echo -e "Using default location of mysqldump\n"
    fi
    read -p 'Give the name of database in which you would like to export: ' db_name
    read -p 'Give the complete path of the .sql file in which you would like to export the database: ' sql_file
    $mysqldump_location -u $u_name -p $db_name > $sql_file
elif [ "$action" == "import" ]; then
    if [ "$location_change" == "y" ]; then
        read -p 'Give the location of mysql that you want to use: ' mysql_location
        echo
    else
        echo -e "Using default location of mysql\n"
    fi
    read -p 'Give the complete path of the .sql file you would like to import: ' sql_file
    read -p 'Give the name of database in which to import this file: ' db_name
    $mysql_location -u $u_name -p $db_name < $sql_file
else
    echo "please select a valid command"
fi

TSQL Pivot without aggregate function

Try this:

SELECT CUSTOMER_ID, MAX(FIRSTNAME) AS FIRSTNAME, MAX(LASTNAME) AS LASTNAME ...

FROM
(

SELECT CUSTOMER_ID, 
       CASE WHEN DBCOLUMNNAME='FirstName' then DATA ELSE NULL END AS FIRSTNAME,
       CASE WHEN DBCOLUMNNAME='LastName' then DATA ELSE NULL END AS LASTNAME,
        ... and so on ...
GROUP BY CUSTOMER_ID

) TEMP

GROUP BY CUSTOMER_ID

How to debug ORA-01775: looping chain of synonyms?

I'm using the following sql to find entries in all_synonyms where there is no corresponding object for the object_name (in user_objects):

 select * 
   from all_synonyms 
   where table_owner = 'SCOTT' 
     and synonym_name not like '%/%'
     and table_name not in (
       select object_name from user_objects
         where object_type in (
           'TABLE', 'VIEW', 'PACKAGE', 'SEQUENCE',
           'PROCEDURE', 'FUNCTION', 'TYPE'
         )
    );

How to copy text from a div to clipboard

Both examples work like a charm :)

  1. JAVASCRIPT:

    _x000D_
    _x000D_
    function CopyToClipboard(containerid) {_x000D_
      if (document.selection) {_x000D_
        var range = document.body.createTextRange();_x000D_
        range.moveToElementText(document.getElementById(containerid));_x000D_
        range.select().createTextRange();_x000D_
        document.execCommand("copy");_x000D_
      } else if (window.getSelection) {_x000D_
        var range = document.createRange();_x000D_
        range.selectNode(document.getElementById(containerid));_x000D_
        window.getSelection().addRange(range);_x000D_
        document.execCommand("copy");_x000D_
        alert("Text has been copied, now paste in the text-area")_x000D_
      }_x000D_
    }
    _x000D_
    <button id="button1" onclick="CopyToClipboard('div1')">Click to copy</button>_x000D_
    <br /><br />_x000D_
    <div id="div1">Text To Copy </div>_x000D_
    <br />_x000D_
    <textarea placeholder="Press ctrl+v to Paste the copied text" rows="5" cols="20"></textarea>
    _x000D_
    _x000D_
    _x000D_

  2. JQUERY (relies on Adobe Flash): https://paulund.co.uk/jquery-copy-to-clipboard

Update GCC on OSX

You can install your GCC manually

either through

sudo port install gcc46

or your download the source code from one of the mirrors from here for example here

tar xzvf gcc-4.6.0.tar.gz cd gcc-4.6.0 ./configure make

well if you have multiple version, then through you can choose one

port select --list gcc

remember port on mac is called macport https://www.macports.org/install.php and add add the bin into your path export PATH=$PATH:/opt/local/bin

Eclipse "this compilation unit is not on the build path of a java project"

You may want to try running eclipse with the -clean startup option - it tries re-building eclipse's metadata of the workspace.

SQLAlchemy IN clause

Just an addition to the answers above.

If you want to execute a SQL with an "IN" statement you could do this:

ids_list = [1,2,3]
query = "SELECT id, name FROM user WHERE id IN %s" 
args = [(ids_list,)] # Don't forget the "comma", to force the tuple
conn.execute(query, args)

Two points:

  • There is no need for Parenthesis for the IN statement(like "... IN(%s) "), just put "...IN %s"
  • Force the list of your ids to be one element of a tuple. Don't forget the " , " : (ids_list,)

EDIT Watch out that if the length of list is one or zero this will raise an error!

Php $_POST method to get textarea value

Use htmlspecialchars():

echo htmlspecialchars($_POST['contact_list']);

You can even improve your form processing by stripping all tags with strip_tags() and remove all white spaces with trim():

function processText($text) {
    $text = strip_tags($text);
    $text = trim($text);
    $text = htmlspecialchars($text);
    return $text;
}

echo processText($_POST['contact_list']);

Groovy Shell warning "Could not open/create prefs root node ..."

If anyone is trying to solve this on a 64-bit version of Windows, you might need to create the following key:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

Webdriver and proxy server for firefox

Preferences -> Advanced -> Network -> Connection (Configure how Firefox connects to the Internet)

Git Commit Messages: 50/72 Formatting

Regarding the “summary” line (the 50 in your formula), the Linux kernel documentation has this to say:

For these reasons, the "summary" must be no more than 70-75
characters, and it must describe both what the patch changes, as well
as why the patch might be necessary.  It is challenging to be both
succinct and descriptive, but that is what a well-written summary
should do.

That said, it seems like kernel maintainers do indeed try to keep things around 50. Here’s a histogram of the lengths of the summary lines in the git log for the kernel:

Lengths of Git summary lines (view full-sized)

There is a smattering of commits that have summary lines that are longer (some much longer) than this plot can hold without making the interesting part look like one single line. (There’s probably some fancy statistical technique for incorporating that data here but oh well… :-)

If you want to see the raw lengths:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{print length($0)}'

or a text-based histogram:

cd /path/to/repo
git shortlog  | grep -e '^      ' | sed 's/[[:space:]]\+\(.*\)$/\1/' | awk '{lens[length($0)]++;} END {for (len in lens) print len, lens[len] }' | sort -n

How to use a different version of python during NPM install?

Ok, so you've found a solution already. Just wanted to share what has been useful to me so many times;

I have created setpy2 alias which helps me switch python.

alias setpy2="mkdir -p /tmp/bin; ln -s `which python2.7` /tmp/bin/python; export PATH=/tmp/bin:$PATH"

Execute setpy2 before you run npm install. The switch stays in effect until you quit the terminal, afterwards python is set back to system default.

You can make use of this technique for any other command/tool as well.

How to set multiple commands in one yaml file with Kubernetes?

IMHO the best option is to use YAML's native block scalars. Specifically in this case, the folded style block.

By invoking sh -c you can pass arguments to your container as commands, but if you want to elegantly separate them with newlines, you'd want to use the folded style block, so that YAML will know to convert newlines to whitespaces, effectively concatenating the commands.

A full working example:

apiVersion: v1
kind: Pod
metadata:
  name: myapp
  labels:
    app: myapp
spec:
  containers:
  - name: busy
    image: busybox:1.28
    command: ["/bin/sh", "-c"]
    args:
    - >
      command_1 &&
      command_2 &&
      ... 
      command_n

"make clean" results in "No rule to make target `clean'"

It seems your makefile's name is not 'Makefile' or 'makefile'. In case it is different say 'abc' try running 'make -f abc clean'

How to use *ngIf else?

For Angular 9/8

Source Link with Examples

    export class AppComponent {
      isDone = true;
    }

1) *ngIf

    <div *ngIf="isDone">
      It's Done!
    </div>

    <!-- Negation operator-->
    <div *ngIf="!isDone">
      It's Not Done!
    </div>

2) *ngIf and Else

    <ng-container *ngIf="isDone; else elseNotDone">
      It's Done!
    </ng-container>

    <ng-template #elseNotDone>
      It's Not Done!
    </ng-template>

3) *ngIf, Then and Else

    <ng-container *ngIf="isDone;  then iAmDone; else iAmNotDone">
    </ng-container>

    <ng-template #iAmDone>
      It's Done!
    </ng-template>

    <ng-template #iAmNotDone>
      It's Not Done!
    </ng-template>

React with ES7: Uncaught TypeError: Cannot read property 'state' of undefined

You have to bind your event handlers to correct context (this):

onChange={this.setAuthorState.bind(this)}

Implementing a slider (SeekBar) in Android

How to implement a SeekBar

enter image description here

Add the SeekBar to your layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_margin="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/seekBar"
        android:max="100"
        android:progress="50"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Notes

  • max is the highest value that the seek bar can go to. The default is 100. The minimum is 0. The xml min value is only available from API 26, but you can just programmatically convert the 0-100 range to whatever you need for earlier versions.
  • progress is the initial position of the slider dot (called a "thumb").
  • For a vertical SeekBar use android:rotation="270".

Listen for changes in code

public class MainActivity extends AppCompatActivity {

    TextView tvProgressLabel;

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

        // set a change listener on the SeekBar
        SeekBar seekBar = findViewById(R.id.seekBar);
        seekBar.setOnSeekBarChangeListener(seekBarChangeListener);

        int progress = seekBar.getProgress();
        tvProgressLabel = findViewById(R.id.textView);
        tvProgressLabel.setText("Progress: " + progress);
    }

    SeekBar.OnSeekBarChangeListener seekBarChangeListener = new SeekBar.OnSeekBarChangeListener() {

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            // updated continuously as the user slides the thumb
            tvProgressLabel.setText("Progress: " + progress);
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {
            // called when the user first touches the SeekBar
        }

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // called after the user finishes moving the SeekBar
        }
    };
}

Notes

  • If you don't need to do any updates while the user is moving the seekbar, then you can just update the UI in onStopTrackingTouch.

See also

For..In loops in JavaScript - key value pairs

yes, you can have associative arrays also in javascript:

var obj = 
{
    name:'some name',
    otherProperty:'prop value',
    date: new Date()
};
for(i in obj)
{
    var propVal = obj[i]; // i is the key, and obj[i] is the value ...
}

How to add text to a WPF Label in code?

you can use TextBlock control and assign the text property.

How can I return the difference between two lists?

If you only want find missing values in b, you can do:

List toReturn = new ArrayList(a);
toReturn.removeAll(b);

return toReturn;

If you want to find out values which are present in either list you can execute upper code twice. With changed lists.

Is mathematics necessary for programming?

It depends on what you do: Web developement, business software, etc. I think for this kind of stuff, you don't need math.

If you want to do computer graphics, audio/video processing, AI, cryptography, etc. then you need a math background, otherwise you can simply not do it.

How to remove all listeners in an element?

If you’re not opposed to jquery, this can be done in one line:

jQuery 1.7+

$("#myEl").off()

jQuery < 1.7

$('#myEl').replaceWith($('#myEl').clone());

Here’s an example:

http://jsfiddle.net/LkfLezgd/3/

When should you NOT use a Rules Engine?

I'm a big fan of Business Rules Engines, since it can help you make your life much easier as a programmer. One of the first experiences I've had while working on a Data Warehouse project was to find Stored Procedures containing complicated CASE structures stretching over entire pages. It was a nightmare to debug, since it was very difficult to understand the logic applied in such long CASE structures, and to determine if you have an overlapping between a rule at page 1 of the code and another from page 5. Overall, we had more than 300 such rules embedded in the code.

When we've received a new development requirement, for something called Accounting Destination, which was involving treating more than 3000 rules, i knew something had to change. Back then I've been working on a prototype which later on become the parent of what now is a Custom Business Rule engine, capable of handling all SQL standard operators. Initially we've been using Excel as an authoring tool and , later on, we've created an ASP.net application which will allow the Business Users to define their own business rules, without the need of writing code. Now the system works fine, with very few bugs, and contains over 7000 rules for calculating this Accounting Destination. I don't think such scenario would have been possible by just hard-coding. And the users are pretty happy that they can define their own rules without IT becoming their bottleneck.

Still, there are limits to such approach:

  • You need to have capable business users which have an excellent understanding of the company business.
  • There is a significant workload on searching the entire system (in our case a Data Warehouse), in order to determine all hard-coded conditions which make sense to translate into rules to be handled by a Business Rule Engine. We've also had to take good care that these initial templates to be fully understandable by Business Users.
  • You need to have an application used for rules authoring, in which algorithms for detection of overlapping business rules is implemented. Otherwise you'll end up with a big mess, where no one understands anymore the results they get. When you have a bug in a generic component like a Custom Business Rule Engine, it can be very difficult to debug and involve extensive tests to make sure that things that worked before also work now.

More details on this topic can be found on a post I've written: http://dwhbp.com/post/2011/10/30/Implementing-a-Business-Rule-Engine.aspx

Overall, the biggest advantage of using a Business Rule Engines is that it allows the users to take back control over the Business Rule definitions and authoring, without the need of going to the IT department each time they need to modify something. It also the reduces the workload over IT development teams, which can now focus on building stuff with more added value.

Cheers,

Nicolae

Does Visual Studio have code coverage for unit tests?

As already mentioned you can use Fine Code Coverage that visualize coverlet output. If you create a xunit test project (dotnet new xunit) you'll find coverlet reference already present in csproj file because Coverlet is the default coverage tool for every .NET Core and >= .NET 5 applications.

Microsoft has an example using ReportGenerator that converts coverage reports generated by coverlet, OpenCover, dotCover, Visual Studio, NCover, Cobertura, JaCoCo, Clover, gcov or lcov into human readable reports in various formats.

Example report:

enter image description here

While the article focuses on C# and xUnit as the test framework, both MSTest and NUnit would also work.

Guide:

https://docs.microsoft.com/en-us/dotnet/core/testing/unit-testing-code-coverage?tabs=windows#generate-reports

If you want code coverage in .xml files you can run any of these commands:

dotnet test --collect:"XPlat Code Coverage"

dotnet test /p:CollectCoverage=true /p:CoverletOutputFormat=cobertura

How do you receive a url parameter with a spring controller mapping

You have a lot of variants for using @RequestParam with additional optional elements, e.g.

@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr

If you don't put required = false - param will be required by default.

defaultValue = "someValue" - the default value to use as a fallback when the request parameter is not provided or has an empty value.

If request and method param are the same - you don't need value = "someAttr"

Python speed testing - Time Difference - milliseconds

You could simply print the difference:

print tend - tstart

Sorting an IList in C#

This question inspired me to write a blog post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

I think that, ideally, the .NET Framework would include a static sorting method that accepts an IList<T>, but the next best thing is to create your own extension method. It's not too hard to create a couple of methods that will allow you to sort an IList<T> as you would a List<T>. As a bonus you can overload the LINQ OrderBy extension method using the same technique, so that whether you're using List.Sort, IList.Sort, or IEnumerable.OrderBy, you can use the exact same syntax.

public static class SortExtensions
{
    //  Sorts an IList<T> in place.
    public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
    {
        ArrayList.Adapter((IList)list).Sort(new ComparisonComparer<T>(comparison));
    }

    // Sorts in IList<T> in place, when T is IComparable<T>
    public static void Sort<T>(this IList<T> list) where T: IComparable<T>
    {
        Comparison<T> comparison = (l, r) => l.CompareTo(r);
        Sort(list, comparison);

    }

    // Convenience method on IEnumerable<T> to allow passing of a
    // Comparison<T> delegate to the OrderBy method.
    public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)
    {
        return list.OrderBy(t => t, new ComparisonComparer<T>(comparison));
    }
}

// Wraps a generic Comparison<T> delegate in an IComparer to make it easy
// to use a lambda expression for methods that take an IComparer or IComparer<T>
public class ComparisonComparer<T> : IComparer<T>, IComparer
{
    private readonly Comparison<T> _comparison;

    public ComparisonComparer(Comparison<T> comparison)
    {
        _comparison = comparison;
    }

    public int Compare(T x, T y)
    {
        return _comparison(x, y);
    }

    public int Compare(object o1, object o2)
    {
        return _comparison((T)o1, (T)o2);
    }
}

With these extensions, sort your IList just like you would a List:

IList<string> iList = new []
{
    "Carlton", "Alison", "Bob", "Eric", "David"
};

// Use the custom extensions:

// Sort in-place, by string length
iList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));

// Or use OrderBy()
IEnumerable<string> ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));

There's more info in the post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

CSS Classes & SubClasses

That is the backbone of CSS, the "cascade" in Cascading Style Sheets.

If you write your CSS rules in a single line it makes it easier to see the structure:

.area1 .item { color:red; }
.area2 .item { color:blue; }
.area2 .item span { font-weight:bold; }

Using multiple classes is also a good intermediate/advanced use of CSS, unfortunately there is a well known IE6 bug which limits this usage when writing cross browser code:

<div class="area1 larger"> .... </div>

.area1 { width:200px; }
.area1.larger { width:300px; }

IE6 IGNORES the first selector in a multi-class rule, so IE6 actually applies the .area1.larger rule as

/*.area1*/.larger { ... }

Meaning it will affect ALL .larger elements.

It's a very nasty and unfortunate bug (one of many) in IE6 that forces you to pretty much never use that feature of CSS if you want one clean cross-browser CSS file.

The solution then is to use CSS classname prefixes to avoid colliding wiht generic classnames:

.area1 { ... }
.area1.area1Larger { ... }

.area2.area2Larger { ... }

May as well use just one class, but that way you can keep the CSS in the logic you intended, while knowing that .area1Larger only affects .area1, etc.

How do I get the computer name in .NET

string name = System.Environment.MachineName;

Is there a performance difference between a for loop and a for-each loop?

From Item 46 in Effective Java by Joshua Bloch :

The for-each loop, introduced in release 1.5, gets rid of the clutter and the opportunity for error by hiding the iterator or index variable completely. The resulting idiom applies equally to collections and arrays:

// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
    doSomething(e);
}

When you see the colon (:), read it as “in.” Thus, the loop above reads as “for each element e in elements.” Note that there is no performance penalty for using the for-each loop, even for arrays. In fact, it may offer a slight performance advantage over an ordinary for loop in some circumstances, as it computes the limit of the array index only once. While you can do this by hand (Item 45), programmers don’t always do so.

Trust Store vs Key Store - creating with keytool

Keystore is used by a server to store private keys, and Truststore is used by third party client to store public keys provided by server to access. I have done that in my production application. Below are the steps for generating java certificates for SSL communication:

  1. Generate a certificate using keygen command in windows:

keytool -genkey -keystore server.keystore -alias mycert -keyalg RSA -keysize 2048 -validity 3950

  1. Self certify the certificate:

keytool -selfcert -alias mycert -keystore server.keystore -validity 3950

  1. Export certificate to folder:

keytool -export -alias mycert -keystore server.keystore -rfc -file mycert.cer

  1. Import Certificate into client Truststore:

keytool -importcert -alias mycert -file mycert.cer -keystore truststore

How to index characters in a Golang string?

Go doesn't really have a character type as such. byte is often used for ASCII characters, and rune is used for Unicode characters, but they are both just aliases for integer types (uint8 and int32). So if you want to force them to be printed as characters instead of numbers, you need to use Printf("%c", x). The %c format specification works for any integer type.

No space left on device

Such difference between the output of du -sh and df -h may happen if some large file has been deleted, but is still opened by some process. Check with the command lsof | grep deleted to see which processes have opened descriptors to deleted files. You can restart the process and the space will be freed.

Return Type for jdbcTemplate.queryForList(sql, object, classType)

queryForList returns a List of LinkedHashMap objects.

You need to cast it first like this:


    List list = jdbcTemplate.queryForList(...);
    for (Object o : list) {
       Map m = (Map) o;
       ...
    }

How to find length of digits in an integer?

All math.log10 solutions will give you problems.

math.log10 is fast but gives problem when your number is greater than 999999999999997. This is because the float have too many .9s, causing the result to round up.

The solution is to use a while counter method for numbers above that threshold.

To make this even faster, create 10^16, 10^17 so on so forth and store as variables in a list. That way, it is like a table lookup.

def getIntegerPlaces(theNumber):
    if theNumber <= 999999999999997:
        return int(math.log10(theNumber)) + 1
    else:
        counter = 15
        while theNumber >= 10**counter:
            counter += 1
        return counter

Get Mouse Position

In SWT you need not be in a listener to get at the mouse location. The Display object has the method getCursorLocation().

In vanilla SWT/JFace, call Display.getCurrent().getCursorLocation().

In an RCP application, call PlatformUI.getWorkbench().getDisplay().getCursorLocation().

For SWT applications, it is preferable to use getCursorLocation() over the MouseInfo.getPointerInfo() that others have mentioned, as the latter is implemented in the AWT toolkit that SWT was designed to replace.

How do I make the scrollbar on a div only visible when necessary?

You can try with below one:

  <div style="width: 100%; height: 100%; overflow-x: visible; overflow-y: scroll;">Text</div>

Converting ISO 8601-compliant String to java.util.Date

Do it like this:

public static void main(String[] args) throws ParseException {

    String dateStr = "2016-10-19T14:15:36+08:00";
    Date date = javax.xml.bind.DatatypeConverter.parseDateTime(dateStr).getTime();

    System.out.println(date);

}

Here is the output:

Wed Oct 19 15:15:36 CST 2016

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

It usually happens when the certificate does not match with the host name.

The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k (or --insecure) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.

More can be found in here: http://curl.haxx.se/docs/sslcerts.html

struct.error: unpack requires a string argument of length 4

The struct module mimics C structures. It takes more CPU cycles for a processor to read a 16-bit word on an odd address or a 32-bit dword on an address not divisible by 4, so structures add "pad bytes" to make structure members fall on natural boundaries. Consider:

struct {                   11
    char a;      012345678901
    short b;     ------------
    char c;      axbbcxxxdddd
    int d;
};

This structure will occupy 12 bytes of memory (x being pad bytes).

Python works similarly (see the struct documentation):

>>> import struct
>>> struct.pack('BHBL',1,2,3,4)
'\x01\x00\x02\x00\x03\x00\x00\x00\x04\x00\x00\x00'
>>> struct.calcsize('BHBL')
12

Compilers usually have a way of eliminating padding. In Python, any of =<>! will eliminate padding:

>>> struct.calcsize('=BHBL')
8
>>> struct.pack('=BHBL',1,2,3,4)
'\x01\x02\x00\x03\x04\x00\x00\x00'

Beware of letting struct handle padding. In C, these structures:

struct A {       struct B {
    short a;         int a;
    char b;          char b;
};               };

are typically 4 and 8 bytes, respectively. The padding occurs at the end of the structure in case the structures are used in an array. This keeps the 'a' members aligned on correct boundaries for structures later in the array. Python's struct module does not pad at the end:

>>> struct.pack('LB',1,2)
'\x01\x00\x00\x00\x02'
>>> struct.pack('LBLB',1,2,3,4)
'\x01\x00\x00\x00\x02\x00\x00\x00\x03\x00\x00\x00\x04'

How do I test if a variable is a number in Bash?

I tried ultrasawblade's recipe as it seemed the most practical to me, and couldn't make it work. In the end i devised another way though, based as others in parameter substitution, this time with regex replacement:

[[ "${var//*([[:digit:]])}" ]]; && echo "$var is not numeric" || echo "$var is numeric"

It removes every :digit: class character in $var and checks if we are left with an empty string, meaning that the original was only numbers.

What i like about this one is its small footprint and flexibility. In this form it only works for non-delimited, base 10 integers, though surely you can use pattern matching to suit it to other needs.

How to give Jenkins more heap space when it´s started as a service under Windows?

If you are using Jenkins templates you could have additional VM settings defined in it and this might conflicting with your system VM settings

example your tempalate may have references such as these

 <mavenOpts>-Xms512m -Xmx1024m -Xss1024k -XX:MaxPermSize=1024m -Dmaven.test.failure.ignore=false</mavenOpts> 

Ensure to align these template entries with the VM setting of your system

How to list records with date from the last 10 days?

you can use between too:

SELECT Table.date
  FROM Table 
  WHERE date between current_date and current_date - interval '10 day';

Hibernate Criteria Query to get specific columns

Use Projections to specify which columns you would like to return.

Example

SQL Query

SELECT user.id, user.name FROM user;

Hibernate Alternative

Criteria cr = session.createCriteria(User.class)
    .setProjection(Projections.projectionList()
      .add(Projections.property("id"), "id")
      .add(Projections.property("Name"), "Name"))
    .setResultTransformer(Transformers.aliasToBean(User.class));

  List<User> list = cr.list();

Asp.net - Add blank item at top of dropdownlist

You could also have a union of the blank select with the select that has content:

select '' value, '' name
union
select value, name from mytable

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

The short answer: there is no difference.

The long answer: CHARACTER VARYING is the official type name from the ANSI SQL standard, which all compliant databases are required to support. VARCHAR is a shorter alias which all modern databases also support. I prefer VARCHAR because it's shorter and because the longer name feels pedantic. However, postgres tools like pg_dump and \d will output character varying.

Get year, month or day from numpy datetime64

There's no direct way to do it yet, unfortunately, but there are a couple indirect ways:

[dt.year for dt in dates.astype(object)]

or

[datetime.datetime.strptime(repr(d), "%Y-%m-%d %H:%M:%S").year for d in dates]

both inspired by the examples here.

Both of these work for me on Numpy 1.6.1. You may need to be a bit more careful with the second one, since the repr() for the datetime64 might have a fraction part after a decimal point.

Interview Question: Merge two sorted singly linked lists without creating new nodes

Node MergeLists(Node list1, Node list2) {
  if (list1 == null) return list2;
  if (list2 == null) return list1;

  if (list1.data < list2.data) {
    list1.next = MergeLists(list1.next, list2);
    return list1;
  } else {
    list2.next = MergeLists(list2.next, list1);
    return list2;
  }
}

Integer to hex string in C++

You can try the following. It's working...

#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;

template <class T>
string to_string(T t, ios_base & (*f)(ios_base&))
{
  ostringstream oss;
  oss << f << t;
  return oss.str();
}

int main ()
{
  cout<<to_string<long>(123456, hex)<<endl;
  system("PAUSE");
  return 0;
}

Reading a plain text file in Java

This code I programmed is much faster for very large files:

public String readDoc(File f) {
    String text = "";
    int read, N = 1024 * 1024;
    char[] buffer = new char[N];

    try {
        FileReader fr = new FileReader(f);
        BufferedReader br = new BufferedReader(fr);

        while(true) {
            read = br.read(buffer, 0, N);
            text += new String(buffer, 0, read);

            if(read < N) {
                break;
            }
        }
    } catch(Exception ex) {
        ex.printStackTrace();
    }

    return text;
}

Convert a Python int into a big-endian string of bytes

Using the bitstring module:

>>> bitstring.BitArray(uint=1245427, length=24).bytes
'\x13\x00\xf3'

Note though that for this method you need to specify the length in bits of the bitstring you are creating.

Internally this is pretty much the same as Alex's answer, but the module has a lot of extra functionality available if you want to do more with your data.

Launch an app from within another (iPhone)

No it's not. Besides the documented URL handlers, there's no way to communicate with/launch another app.

Removing special characters VBA Excel

Here is how removed special characters.

I simply applied regex

Dim strPattern As String: strPattern = "[^a-zA-Z0-9]" 'The regex pattern to find special characters
Dim strReplace As String: strReplace = "" 'The replacement for the special characters
Set regEx = CreateObject("vbscript.regexp") 'Initialize the regex object    
Dim GCID As String: GCID = "Text #N/A" 'The text to be stripped of special characters

' Configure the regex object
With regEx
    .Global = True
    .MultiLine = True
    .IgnoreCase = False
    .Pattern = strPattern
End With

' Perform the regex replacement
GCID = regEx.Replace(GCID, strReplace)

How to pass an array into a function, and return the results with an array

i know a Class is a bit the overkill

class Foo
{

 private $sum = NULL;

 public function __construct($array)
 {
   $this->sum[] = $array;
   return $this;
 }

 public function getSum()
 {
   $sum = $this->sum;
   for($i=0;$i<count($sum);$i++)
   {
      // get the last array index
      $res[$i] = $sum[$i] + $sum[count($sum)-$i];
   }
   return $res;
 }


}


$fo = new Foo($myarray)->getSum();

Format y axis as percent

Based on the answer of @erwanp, you can use the formatted string literals of Python 3,

x = '2'
percentage = f'{x}%' # 2%

inside the FuncFormatter() and combined with a lambda expression.

All wrapped:

ax.yaxis.set_major_formatter(FuncFormatter(lambda y, _: f'{y}%'))

What is the function __construct used for?

Its another way to declare the constructor. You can also use the class name, for ex:

class Cat
{
    function Cat()
    {
        echo 'meow';
    }
}

and

class Cat
{
    function __construct()
    {
        echo 'meow';
    }
}

Are equivalent. They are called whenever a new instance of the class is created, in this case, they will be called with this line:

$cat = new Cat();

Golang append an item to a slice

In order to make your code work without having to return the slice from Test, you can pass a pointer like this:

package main

import (
    "fmt"
)

var a = make([]int, 7, 8)

func Test(slice *[]int) {
    *slice = append(*slice, 100)

    fmt.Println(*slice)
}

func main() {

    for i := 0; i < 7; i++ {
        a[i] = i
    }

    Test(&a)

    fmt.Println(a)
}

Laravel Checking If a Record Exists

This will check if particular email address exist in the table:

if (isset(User::where('email', Input::get('email'))->value('email')))
{
    // Input::get('email') exist in the table 
}

Fixing "Lock wait timeout exceeded; try restarting transaction" for a 'stuck" Mysql table?

This started happening to me when my database size grew and I was doing a lot of transactions on it.

Truth is there is probably some way to optimize either your queries or your DB but try these 2 queries for a work around fix.

Run this:

SET GLOBAL innodb_lock_wait_timeout = 5000; 

And then this:

SET innodb_lock_wait_timeout = 5000; 

While loop to test if a file exists in bash

When you say "doesn't work", how do you know it doesn't work?

You might try to figure out if the file actually exists by adding:

while [ ! -f /tmp/list.txt ]
do
  sleep 2 # or less like 0.2
done
ls -l /tmp/list.txt

You might also make sure that you're using a Bash (or related) shell by typing 'echo $SHELL'. I think that CSH and TCSH use a slightly different semantic for this loop.

"You have mail" message in terminal, os X

It means that a process or script you have created is sending mail to an account on your local machine (for example, a mail server running on localhost application).

Manage this mail with these commands:

t <message list>        type messages
n                       goto and type next message
e <message list>        edit messages
f <message list>        give head lines of messages
d <message list>        delete messages
s <message list>        file append messages to file
u <message list>        undelete messages
R <message list>        reply to message senders
r <message list>        reply to message senders and all recipients
pre <message list>      make messages go back to /var/mail
m <user list>           mail to specific users
q                       quit, saving unresolved messages in mbox
x                       quit, do not remove system mailbox
h                       print out active message headers
!                       shell escape
cd [directory]          chdir to directory or home if none given

A consists of integers, ranges of same, or user names separated by spaces. If omitted, Mail uses the last message typed.

A consists of user names or aliases separated by spaces. Aliases are defined in .mailrc in your home directory.

AngularJS - Access to child scope

While jm-'s answer is the best way to handle this case, for future reference it is possible to access child scopes using a scope's $$childHead, $$childTail, $$nextSibling and $$prevSibling members. These aren't documented so they might change without notice, but they're there if you really need to traverse scopes.

// get $$childHead first and then iterate that scope's $$nextSiblings
for(var cs = scope.$$childHead; cs; cs = cs.$$nextSibling) {
    // cs is child scope
}

Fiddle

Rails 4 LIKE query - ActiveRecord adds quotes

Instead of using the conditions syntax from Rails 2, use Rails 4's where method instead:

def self.search(search, page = 1 )
  wildcard_search = "%#{search}%"

  where("name ILIKE :search OR postal_code LIKE :search", search: wildcard_search)
    .page(page)
    .per_page(5)
end

NOTE: the above uses parameter syntax instead of ? placeholder: these both should generate the same sql.

def self.search(search, page = 1 )
  wildcard_search = "%#{search}%"

  where("name ILIKE ? OR postal_code LIKE ?", wildcard_search, wildcard_search)
    .page(page)
    .per_page(5)
end

NOTE: using ILIKE for the name - postgres case insensitive version of LIKE

How to force a web browser NOT to cache images

I use PHP's file modified time function, for example:

echo <img  src='Images/image.png?" . filemtime('Images/image.png') . "'  />";

If you change the image then the new image is used rather than the cached one, due to having a different modified timestamp.

Java : Sort integer array without using Arrays.sort()

This will surely help you.

int n[] = {4,6,9,1,7};

    for(int i=n.length;i>=0;i--){
        for(int j=0;j<n.length-1;j++){
            if(n[j] > n[j+1]){
                swapNumbers(j,j+1,n);
            }
        }

    }
    printNumbers(n);
}
private static void swapNumbers(int i, int j, int[] array) {

    int temp;
    temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}

private static void printNumbers(int[] input) {

    for (int i = 0; i < input.length; i++) {
        System.out.print(input[i] + ", ");
    }
    System.out.println("\n");
}

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

  1. @SpringBootApplication: checked, didn't work.
  2. spring-boot-starter-web in Pom file: checked, didn't work.
  3. Switch from IntelliJ CE to IntelliJ Ultimate, problem solved.

Top 5 time-consuming SQL queries in Oracle

It depends which version of oracle you have, for 9i and below Statspack is what you are after, 10g and above, you want awr , both these tools will give you the top sql's and lots of other stuff.

Angular 4: How to include Bootstrap?

If you are using Sass/Scss, then follow this,

Do npm install

npm install bootstrap --save

and add import statement to your sass/scss file,

@import '~bootstrap/dist/css/bootstrap.css'

What is cardinality in Databases?

Cardinality of a set is the namber of the elements in set for we have a set a > a,b,c < so ths set contain 3 elements 3 is the cardinality of that set

Add new row to excel Table (VBA)

Tbl.ListRows.Add doesn't work for me and I believe lot others are facing the same problem. I use the following workaround:

    'First check if the last row is empty; if not, add a row
    If table.ListRows.count > 0 Then
        Set lastRow = table.ListRows(table.ListRows.count).Range
        For col = 1 To lastRow.Columns.count
            If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
                lastRow.Cells(1, col).EntireRow.Insert
                'Cut last row and paste to second last
                lastRow.Cut Destination:=table.ListRows(table.ListRows.count - 1).Range
                Exit For
            End If
        Next col
    End If

    'Populate last row with the form data
    Set lastRow = table.ListRows(table.ListRows.count).Range
    Range("E7:E10").Copy
    lastRow.PasteSpecial Transpose:=True
    Range("E7").Select
    Application.CutCopyMode = False

Hope it helps someone out there.

MySQL delete multiple rows in one query conditions unique to each row

A slight extension to the answer given, so, hopefully useful to the asker and anyone else looking.

You can also SELECT the values you want to delete. But watch out for the Error 1093 - You can't specify the target table for update in FROM clause.

DELETE FROM
    orders_products_history
WHERE
    (branchID, action) IN (
    SELECT
        branchID,
        action
    FROM
        (
        SELECT
            branchID,
            action
        FROM
            orders_products_history
        GROUP BY
            branchID,
            action
        HAVING
            COUNT(*) > 10000
        ) a
    );

I wanted to delete all history records where the number of history records for a single action/branch exceed 10,000. And thanks to this question and chosen answer, I can.

Hope this is of use.

Richard.