Programs & Examples On #Server tags

How to get a MemoryStream from a Stream in .NET?

public static void Do(Stream in)
{
    _ms = new MemoryStream();
    byte[] buffer = new byte[65536];
    while ((int read = input.Read(buffer, 0, buffer.Length))>=0)
        _ms.Write (buffer, 0, read);
}

How do you calculate the variance, median, and standard deviation in C++ or Java?

To calculate the mean, loop through the list/array of numbers, keeping track of the partial sums and the length. Then return the sum/length.

double sum = 0.0;
int length = 0;

for( double number : numbers ) {
    sum += number;
    length++;
}

return sum/length;

Variance is calculated similarly. Standard deviation is simply the square root of the variance:

double stddev = Math.sqrt( variance );

How can I delete a query string parameter in JavaScript?

This returns the URL w/o ANY GET Parameters:

var href = document.location.href;
var search = document.location.search;
var pos = href.indexOf( search );
if ( pos !== -1 ){
    href = href.slice( 0, pos );
    console.log( href );
}

How to use dashes in HTML-5 data-* attributes in ASP.NET MVC

In mvc 4 Could be rendered with Underscore(" _ ")

Razor:

@Html.ActionLink("Vote", "#", new { id = item.FileId, }, new { @class = "votes", data_fid = item.FileId, data_jid = item.JudgeID, })

Rendered Html

<a class="votes" data-fid="18587" data-jid="9" href="/Home/%23/18587">Vote</a>

Configure Nginx with proxy_pass

Give this a try...

server {
    listen   80;
    server_name  dev.int.com;
    access_log off;
    location / {
        proxy_pass http://IP:8080;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:8080/jira  /;
        proxy_connect_timeout 300;
    }

    location ~ ^/stash {
        proxy_pass http://IP:7990;
        proxy_set_header    Host            $host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-for $remote_addr;
        port_in_redirect off;
        proxy_redirect   http://IP:7990/  /stash;
        proxy_connect_timeout 300;
    }

    error_page   500 502 503 504  /50x.html;
    location = /50x.html {
        root   /usr/local/nginx/html;
    }
}

Where do I get servlet-api.jar from?

You can find a recent servlet-api.jar in Tomcat 6 or 7 lib directory. If you don't have Tomcat on your machine, download the binary distribution of version 6 or 7 from http://tomcat.apache.org/download-70.cgi

How to subtract 30 days from the current datetime in mysql?

To anyone who doesn't want to use DATE_SUB, use CURRENT_DATE:

SELECT CURRENT_DATE - INTERVAL 30 DAY

Python unittest - opposite of assertRaises?

I am the original poster and I accepted the above answer by DGH without having first used it in the code.

Once I did use I realised that it needed a little tweaking to actually do what I needed it to do (to be fair to DGH he/she did say "or something similar" !).

I thought it was worth posting the tweak here for the benefit of others:

    try:
        a = Application("abcdef", "")
    except pySourceAidExceptions.PathIsNotAValidOne:
        pass
    except:
        self.assertTrue(False)

What I was attempting to do here was to ensure that if an attempt was made to instantiate an Application object with a second argument of spaces the pySourceAidExceptions.PathIsNotAValidOne would be raised.

I believe that using the above code (based heavily on DGH's answer) will do that.

Watch multiple $scope attributes

$watch first parameter can be angular expression or function. See documentation on $scope.$watch. It contains a lot of useful info about how $watch method works: when watchExpression is called, how angular compares results, etc.

Simple excel find and replace for formulas

It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way

=((E9-E8)/E8) 

became

=((R[-1]C-R[-2]C)/R[-2]C)

and

(EXP((LN(E9/E8)/14.32))-1)

became

=(EXP((LN(R[-1]C/R[-2]C)/14.32))-1)

In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!

Is there any way I can define a variable in LaTeX?

This works for me: \newcommand{\variablename}{the text}

For eg: \newcommand\m{100}

So when you type " \m\ is my mark " in the source code,

the pdf output displays as :

100 is my mark

Stripping everything but alphanumeric chars from a string in Python

Regular expressions to the rescue:

import re
re.sub(r'\W+', '', your_string)

By Python definition '\W == [^a-zA-Z0-9_], which excludes all numbers, letters and _

Remove characters from a String in Java

String id = id.substring(0,id.length()-4)

How to get an object's methods?

You can use console.dir(object) to write that objects properties to the console.

Add Whatsapp function to website, like sms, tel

Rahul's answer gives me an error: You seem to be trying to send a WhatsApp message to a phone number that is not registered with WhatsApp..., even though I'm sending it to a registered WhatsApp number.

This, however works:

<li><a href="intent:0123456789#Intent;scheme=smsto;package=com.whatsapp;action=android.intent.action.SENDTO;end"><i class="fa fa-whatsapp"></i>+237 655 421 621</li>

Java finished with non-zero exit value 2 - Android Gradle

in my case problem was build tools version which was 23.0.0 rc3 and i changed to 22.0.1 and my problem fixed.

LINQ to SQL Left Outer Join

Not quite - since each "left" row in a left-outer-join will match 0-n "right" rows (in the second table), where-as yours matches only 0-1. To do a left outer join, you need SelectMany and DefaultIfEmpty, for example:

var query = from c in db.Customers
            join o in db.Orders
               on c.CustomerID equals o.CustomerID into sr
            from x in sr.DefaultIfEmpty()
            select new {
               CustomerID = c.CustomerID, ContactName = c.ContactName,
               OrderID = x == null ? -1 : x.OrderID };   

(or via the extension methods)

Is there a math nCr function in python?

The following program calculates nCr in an efficient manner (compared to calculating factorials etc.)

import operator as op
from functools import reduce

def ncr(n, r):
    r = min(r, n-r)
    numer = reduce(op.mul, range(n, n-r, -1), 1)
    denom = reduce(op.mul, range(1, r+1), 1)
    return numer // denom  # or / in Python 2

As of Python 3.8, binomial coefficients are available in the standard library as math.comb:

>>> from math import comb
>>> comb(10,3)
120

How to stop console from closing on exit?

Yes, in VS2010 they changed this behavior somewhy.
Open your project and navigate to the following menu: Project -> YourProjectName Properties -> Configuration Properties -> Linker -> System. There in the field SubSystem use the drop-down to select Console (/SUBSYSTEM:CONSOLE) and apply the change.
"Start without debugging" should do the right thing now.

Or, if you write in C++ or in C, put

system("pause");

at the end of your program, then you'll get "Press any key to continue..." even when running in debug mode.

Why can't I duplicate a slice with `copy()`?

The builtin copy(dst, src) copies min(len(dst), len(src)) elements.

So if your dst is empty (len(dst) == 0), nothing will be copied.

Try tmp := make([]int, len(arr)) (Go Playground):

arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)

Output (as expected):

[1 2 3]
[1 2 3]

Unfortunately this is not documented in the builtin package, but it is documented in the Go Language Specification: Appending to and copying slices:

The number of elements copied is the minimum of len(src) and len(dst).

Edit:

Finally the documentation of copy() has been updated and it now contains the fact that the minimum length of source and destination will be copied:

Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

Android: How can I validate EditText input?

You can get desired behavior by listening when user hit "Done" button on keyboard, also checkout other tips about working with EditText in my post "Android form validation - the right way"

Sample code:

mTextView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
    @Override
    public boolean onEditorAction(TextView view, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_DONE) {                    
            validateAndSubmit();
            return true;
        }
        return false;
    }});  

jQuery .slideRight effect

Another solution is by using .animate() and appropriate CSS.

e.g.

   $('#mydiv').animate({ marginLeft: "100%"} , 4000);

JS Fiddle

postgresql return 0 if returned value is null

use coalesce

COALESCE(value [, ...])
The COALESCE function returns the first of its arguments that is not null.  
Null is returned only if all arguments are null. It is often
used to substitute a default value for null values when data is
retrieved for display.

Edit

Here's an example of COALESCE with your query:

SELECT AVG( price )
FROM(
      SELECT *, cume_dist() OVER ( ORDER BY price DESC ) FROM web_price_scan
      WHERE listing_Type = 'AARM'
        AND u_kbalikepartnumbers_id = 1000307
        AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
        AND COALESCE( price, 0 ) > ( SELECT AVG( COALESCE( price, 0 ) )* 0.50
                                     FROM ( SELECT *, cume_dist() OVER ( ORDER BY price DESC )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) g
                                    WHERE cume_dist < 0.50
                                  )
        AND COALESCE( price, 0 ) < ( SELECT AVG( COALESCE( price, 0 ) ) *2
                                     FROM( SELECT *, cume_dist() OVER ( ORDER BY price desc )
                                           FROM web_price_scan
                                           WHERE listing_Type='AARM'
                                             AND u_kbalikepartnumbers_id = 1000307
                                             AND ( EXTRACT( DAY FROM ( NOW() - dateEnded ) ) ) * 24 < 48
                                         ) d
                                     WHERE cume_dist < 0.50)
     )s
HAVING COUNT(*) > 5

IMHO COALESCE should not be use with AVG because it modifies the value. NULL means unknown and nothing else. It's not like using it in SUM. In this example, if we replace AVG by SUM, the result is not distorted. Adding 0 to a sum doesn't hurt anyone but calculating an average with 0 for the unknown values, you don't get the real average.

In that case, I would add price IS NOT NULL in WHERE clause to avoid these unknown values.

What is the difference between an int and a long in C++?

When compiling for x64, the difference between int and long is somewhere between 0 and 4 bytes, depending on what compiler you use.

GCC uses the LP64 model, which means that ints are 32-bits but longs are 64-bits under 64-bit mode.

MSVC for example uses the LLP64 model, which means both ints and longs are 32-bits even in 64-bit mode.

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

Tomcat base URL redirection

Tested and Working procedure:

Goto the file path ..\apache-tomcat-7.0.x\webapps\ROOT\index.jsp

remove the whole content or declare the below lines of code at the top of the index.jsp

<% response.sendRedirect("http://yourRedirectionURL"); %>

Please note that in jsp file you need to start the above line with <% and end with %>

How can I get a web site's favicon?

Updated 2020

Here are three services you can use in 2020 onwards

<img height="16" width="16" src='https://icons.duckduckgo.com/ip3/www.google.com.ico' />

<img height="16" width="16" src='http://www.google.com/s2/favicons?domain=www.google.com' />

<img height="16" width="16" src='https://api.statvoo.com/favicon/?url=google.com' />

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '...' is therefore not allowed access

you have to put the headers keys/values in options method response. for example if you have resource at http://mydomain.com/myresource then, in your server code you write

//response handler
void handleRequest(Request request, Response response) {
    if(request.method == "OPTIONS") {
       response.setHeader("Access-Control-Allow-Origin","http://clientDomain.com")
       response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
       response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    }



}

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()


    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret


End Sub

OR

 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

Entity Framework and SQL Server View

We had the same problem and this is the solution:

To force entity framework to use a column as a primary key, use ISNULL.

To force entity framework not to use a column as a primary key, use NULLIF.

An easy way to apply this is to wrap the select statement of your view in another select.

Example:

SELECT
  ISNULL(MyPrimaryID,-999) MyPrimaryID,
  NULLIF(AnotherProperty,'') AnotherProperty
  FROM ( ... ) AS temp

How to urlencode data for curl command?

This may be the best one:

after=$(echo -e "$before" | od -An -tx1 | tr ' ' % | xargs printf "%s")

Convert HH:MM:SS string to seconds only in javascript

This can be done quite resiliently with the following:

'01:02:03'.split(':').reduce((acc,time) => (60 * acc) + +time);

This is because each unit of time within the hours, minutes and seconds is a multiple of 60 greater than the smaller unit. Time is split into hour minutes and seconds components, then reduced to seconds by using the accumulated value of the higher units multiplied by 60 as it goes through each unit.

The +time is used to cast the time to a number.

It basically ends up doing: (60 * ((60 * HHHH) + MM)) + SS

If only seconds is passed then the result would be a string, so to fix that we could cast the entire result to an int:

+('03'.split(':').reduce((acc,time) => (60 * acc) + +time));

How do I query between two dates using MySQL?

DATE() is a MySQL function that extracts only the date part of a date or date/time expression

SELECT * FROM table_name WHERE DATE(date_field) BETWEEN '2016-12-01' AND '2016-12-10';

How can I scroll up more (increase the scroll buffer) in iTerm2?

macOS default termianl

macOS 10.15.7

  1. open Terminal
  2. click Prefrences...
  3. select Window tab
  4. just change Scrollback to Limit number of rows to: what your wanted.

my screenshots

enter image description here

enter image description here

enter image description here

Commenting in a Bash script inside a multiline command

$IFS comment hacks

This hack uses parameter expansion on $IFS, which is used to separate words in commands:

$ echo foo${IFS}bar
foo bar

Similarly:

$ echo foo${IFS#comment}bar
foo bar

Using this, you can put a comment on a command line with contination:

$ echo foo${IFS# Comment here} \
> bar
foo bar

but the comment will need to be before the \ continuation.

Note that parameter expansion is performed inside the comment:

$ ls file
ls: cannot access 'file': No such file or directory
$ echo foo${IFS# This command will create file: $(touch file)}bar
foo bar
$ ls file
file

Rare exception

The only rare case this fails is if $IFS previously started with the exact text which is removed via the expansion (ie, after the # character):

$ IFS=x
$ echo foo${IFS#y}bar
foo bar
$ echo foo${IFS#x}bar
foobar

Note the final foobar has no space, illustrating the issue.

Since $IFS contains only whitespace by default, it's extremely unlikely you'll run into this problem.


Credit to @pjh's comment which sparked off this answer.

Is there a simple, elegant way to define singletons?

Creating a singleton decorator (aka an annotation) is an elegant way if you want to decorate (annotate) classes going forward. Then you just put @singleton before your class definition.

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
    ...

' << ' operator in verilog

<< is a binary shift, shifting 1 to the left 8 places.

4'b0001 << 1 => 4'b0010

>> is a binary right shift adding 0's to the MSB.
>>> is a signed shift which maintains the value of the MSB if the left input is signed.

4'sb1011 >>  1 => 0101
4'sb1011 >>> 1 => 1101

Three ways to indicate left operand is signed:

module shift;
  logic        [3:0] test1 = 4'b1000;
  logic signed [3:0] test2 = 4'b1000;

  initial begin
    $display("%b", $signed(test1) >>> 1 ); //Explicitly set as signed
    $display("%b", test2          >>> 1 ); //Declared as signed type
    $display("%b", 4'sb1000       >>> 1 ); //Signed constant
    $finish;
  end
endmodule

How to use org.apache.commons package?

You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.

For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.

If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.

For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.

If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.

List files committed for a revision

From remote repo:

svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/

Remove characters from C# string

Lots of good answers here, here's my addition along with several unit tests that can be used to help test correctness, my solution is similar to @Rianne's above but uses an ISet to provide O(1) lookup time on the replacement characters (and also similar to @Albin Sunnanbo's Linq solution).

    using System;
    using System.Collections.Generic;
    using System.Linq;

    /// <summary>
    /// Returns a string with the specified characters removed.
    /// </summary>
    /// <param name="source">The string to filter.</param>
    /// <param name="removeCharacters">The characters to remove.</param>
    /// <returns>A new <see cref="System.String"/> with the specified characters removed.</returns>
    public static string Remove(this string source, IEnumerable<char> removeCharacters)
    {
        if (source == null)
        {
            throw new  ArgumentNullException("source");
        }

        if (removeCharacters == null)
        {
            throw new ArgumentNullException("removeCharacters");
        }

        // First see if we were given a collection that supports ISet
        ISet<char> replaceChars = removeCharacters as ISet<char>;

        if (replaceChars == null)
        {
            replaceChars = new HashSet<char>(removeCharacters);
        }

        IEnumerable<char> filtered = source.Where(currentChar => !replaceChars.Contains(currentChar));

        return new string(filtered.ToArray());
    }

NUnit (2.6+) tests here

using System;
using System.Collections;
using System.Collections.Generic;
using NUnit.Framework;

[TestFixture]
public class StringExtensionMethodsTests
{
    [TestCaseSource(typeof(StringExtensionMethodsTests_Remove_Tests))]
    public void Remove(string targetString, IEnumerable<char> removeCharacters, string expected)
    {
        string actual = StringExtensionMethods.Remove(targetString, removeCharacters);

        Assert.That(actual, Is.EqualTo(expected));
    }

    [TestCaseSource(typeof(StringExtensionMethodsTests_Remove_ParameterValidation_Tests))]
    public void Remove_ParameterValidation(string targetString, IEnumerable<char> removeCharacters)
    {
        Assert.Throws<ArgumentNullException>(() => StringExtensionMethods.Remove(targetString, removeCharacters));
    }
}

internal class StringExtensionMethodsTests_Remove_Tests : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        yield return new TestCaseData("My name @is ,Wan.;'; Wan", new char[] { '@', ',', '.', ';', '\'' }, "My name is Wan Wan").SetName("StringUsingCharArray");
        yield return new TestCaseData("My name @is ,Wan.;'; Wan", new HashSet<char> { '@', ',', '.', ';', '\'' }, "My name is Wan Wan").SetName("StringUsingISetCollection");
        yield return new TestCaseData(string.Empty, new char[1], string.Empty).SetName("EmptyStringNoReplacementCharactersYieldsEmptyString");
        yield return new TestCaseData(string.Empty, new char[] { 'A', 'B', 'C' }, string.Empty).SetName("EmptyStringReplacementCharsYieldsEmptyString");
        yield return new TestCaseData("No replacement characters", new char[1], "No replacement characters").SetName("StringNoReplacementCharactersYieldsString");
        yield return new TestCaseData("No characters will be replaced", new char[] { 'Z' }, "No characters will be replaced").SetName("StringNonExistantReplacementCharactersYieldsString");
        yield return new TestCaseData("AaBbCc", new char[] { 'a', 'C' }, "ABbc").SetName("CaseSensitivityReplacements");
        yield return new TestCaseData("ABC", new char[] { 'A', 'B', 'C' }, string.Empty).SetName("AllCharactersRemoved");
        yield return new TestCaseData("AABBBBBBCC", new char[] { 'A', 'B', 'C' }, string.Empty).SetName("AllCharactersRemovedMultiple");
        yield return new TestCaseData("Test That They Didn't Attempt To Use .Except() which returns distinct characters", new char[] { '(', ')' }, "Test That They Didn't Attempt To Use .Except which returns distinct characters").SetName("ValidateTheStringIsNotJustDistinctCharacters");
    }
}

internal class StringExtensionMethodsTests_Remove_ParameterValidation_Tests : IEnumerable
{
    public IEnumerator GetEnumerator()
    {
        yield return new TestCaseData(null, null);
        yield return new TestCaseData("valid string", null);
        yield return new TestCaseData(null, new char[1]);
    }
}

HTML5 input type range show range value

an even better way would be to catch the input event on the input itself rather than on the whole form (performance wise) :

<input type="range" id="rangeInput" name="rangeInput" min="0" max="20" value="0"
       oninput="amount.value=rangeInput.value">                                                       

<output id="amount" name="amount" for="rangeInput">0</output>

Here's a fiddle (with the id added as per Ryan's comment).

Mongoose query where value is not null

total count the documents where the value of the field is not equal to the specified value.

async function getRegisterUser() {
    return Login.count({"role": { $ne: 'Super Admin' }}, (err, totResUser) => {
        if (err) {
            return err;
        }
        return totResUser;
    })
}

Function in JavaScript that can be called only once

Tossing my hat in the ring for fun, added advantage of memoizing

const callOnce = (fn, i=0, memo) => () => i++ ? memo : (memo = fn());
// usage
const myExpensiveFunction = () => { return console.log('joe'),5; }
const memoed = callOnce(myExpensiveFunction);
memoed(); //logs "joe", returns 5
memoed(); // returns 5
memoed(); // returns 5
...

How do I change the font color in an html table?

table td{
  color:#0000ff;
}

<table>
  <tbody>
    <tr>
    <td>
      <select name="test">
        <option value="Basic">Basic : $30.00 USD - yearly</option>
        <option value="Sustaining">Sustaining : $60.00 USD - yearly</option>
        <option value="Supporting">Supporting : $120.00 USD - yearly</option>
      </select>
    </td>
    </tr>
  </tbody>
</table>

Replace text in HTML page with jQuery

You could use the following to replace the first occurrence of a word within the body of the page:

var replaced = $("body").html().replace('-9o0-9909','The new string');
$("body").html(replaced);

If you wanted to replace all occurrences of a word, you need to use regex and declare it global /g:

var replaced = $("body").html().replace(/-1o9-2202/g,'The ALL new string');
$("body").html(replaced);

If you wanted a one liner:

$("body").html($("body").html().replace(/12345-6789/g,'<b>abcde-fghi</b>'));

You are basically taking all of the HTML within the <body> tags of the page into a string variable, using replace() to find and change the first occurrence of the found string with a new string. Or if you want to find and replace all occurrences of the string introduce a little regex to the mix.

See a demo here - look at the HTML top left to see the original text, the jQuery below, and the output to the bottom right.

how to access downloads folder in android?

You should add next permission:

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

And then here is usages in code:

val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)

Copying files from one directory to another in Java

Apache commons FileUtils will be handy, if you want only to move files from the source to target directory rather than copy the whole directory, you can do:

for (File srcFile: srcDir.listFiles()) {
    if (srcFile.isDirectory()) {
        FileUtils.copyDirectoryToDirectory(srcFile, dstDir);
    } else {
        FileUtils.copyFileToDirectory(srcFile, dstDir);
    }
}

If you want to skip directories, you can do:

for (File srcFile: srcDir.listFiles()) {
    if (!srcFile.isDirectory()) {
        FileUtils.copyFileToDirectory(srcFile, dstDir);
    }
}

Read file from aws s3 bucket using node fs

With the new version of sdk, the accepted answer does not work - it does not wait for the object to be downloaded. The following code snippet will help with the new version:

// dependencies

const AWS = require('aws-sdk');

// get reference to S3 client

const s3 = new AWS.S3();

exports.handler = async (event, context, callback) => {

var bucket = "TestBucket"

var key = "TestKey"

   try {

      const params = {
            Bucket: Bucket,
            Key: Key
        };

       var theObject = await s3.getObject(params).promise();

    } catch (error) {
        console.log(error);
        return;
    }  
}

Changing the default title of confirm() in JavaScript?

Yes, this is impossible to modify the title of it. If you still want to have your own title, you can try to use other pop-up windows instead.

How to disable spring security for particular url

If you want to ignore multiple API endpoints you can use as follow:

 @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.csrf().disable().authorizeRequests() 
            .antMatchers("/api/v1/**").authenticated()
            .antMatchers("api/v1/authenticate**").permitAll()
            .antMatchers("**").permitAll()
            .and().exceptionHandling().and().sessionManagement()
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

Combining Two Images with OpenCV

in OpenCV 3.0 you can use it easily as follow:

#combine 2 images same as to concatenate images with two different sizes
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty martrix (Mat)
res = np.zeros(shape=(max(h1, h2), w1 + w2, 3), dtype=np.uint8)
# assign BGR values to concatenate images
for i in range(res.shape[2]):
    # assign img1 colors
    res[:h1, :w1, i] = np.ones([img1.shape[0], img1.shape[1]]) * img1[:, :, i]
    # assign img2 colors
    res[:h2, w1:w1 + w2, i] = np.ones([img2.shape[0], img2.shape[1]]) * img2[:, :, i]

output_img = res.astype('uint8')

String escape into XML

George, it's simple. Always use the XML APIs to handle XML. They do all the escaping and unescaping for you.

Never create XML by appending strings.

Argument of type 'X' is not assignable to parameter of type 'X'

I was getting this one on this case

...
.then((error: any, response: any) => {
  console.info('document error: ', error);
  console.info('documenr response: ', response);
  return new MyModel();
})
...

on this case making parameters optional would make ts stop complaining

.then((error?: any, response?: any) => {

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

I'm facing the same problem trying to geocode 140 addresses.

My workaround was adding usleep(100000) for each loop of next geocoding request. If status of the request is OVER_QUERY_LIMIT, the usleep is increased by 50000 and request is repeated, and so on.

And of cause all received data (lat/long) are stored in XML file not to run request every time the page is loading.

AJAX Mailchimp signup form integration

You don't need an API key, all you have to do is plop the standard mailchimp generated form into your code ( customize the look as needed ) and in the forms "action" attribute change post?u= to post-json?u= and then at the end of the forms action append &c=? to get around any cross domain issue. Also it's important to note that when you submit the form you must use GET rather than POST.

Your form tag will look something like this by default:

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post?u=xxxxx&id=xxxx" method="post" ... >

change it to look something like this

<form action="http://xxxxx.us#.list-manage1.com/subscribe/post-json?u=xxxxx&id=xxxx&c=?" method="get" ... >

Mail Chimp will return a json object containing 2 values: 'result' - this will indicate if the request was successful or not ( I've only ever seen 2 values, "error" and "success" ) and 'msg' - a message describing the result.

I submit my forms with this bit of jQuery:

$(document).ready( function () {
    // I only have one form on the page but you can be more specific if need be.
    var $form = $('form');

    if ( $form.length > 0 ) {
        $('form input[type="submit"]').bind('click', function ( event ) {
            if ( event ) event.preventDefault();
            // validate_input() is a validation function I wrote, you'll have to substitute this with your own.
            if ( validate_input($form) ) { register($form); }
        });
    }
});

function register($form) {
    $.ajax({
        type: $form.attr('method'),
        url: $form.attr('action'),
        data: $form.serialize(),
        cache       : false,
        dataType    : 'json',
        contentType: "application/json; charset=utf-8",
        error       : function(err) { alert("Could not connect to the registration server. Please try again later."); },
        success     : function(data) {
            if (data.result != "success") {
                // Something went wrong, do something to notify the user. maybe alert(data.msg);
            } else {
                // It worked, carry on...
            }
        }
    });
}

C# equivalent of the IsNull() function in SQL Server

This is meant half as a joke, since the question is kinda silly.

public static bool IsNull (this System.Object o)
{
   return (o == null);
}

This is an extension method, however it extends System.Object, so every object you use now has an IsNull() method.

Then you can save tons of code by doing:

if (foo.IsNull())

instead of the super lame:

if (foo == null)

What does it mean to inflate a view from an xml file?

"Inflating" a view means taking the layout XML and parsing it to create the view and viewgroup objects from the elements and their attributes specified within, and then adding the hierarchy of those views and viewgroups to the parent ViewGroup. When you call setContentView(), it attaches the views it creates from reading the XML to the activity. You can also use LayoutInflater to add views to another ViewGroup, which can be a useful tool in a lot of circumstances.

Getting a list of values from a list of dicts

Assuming every dict has a value key, you can write (assuming your list is named l)

[d['value'] for d in l]

If value might be missing, you can use

[d['value'] for d in l if 'value' in d]

Extract only right most n letters from a string

Here's the solution I use... It checks that the input string's length isn't lower than the asked length. The solutions I see posted above don't take this into account unfortunately - which can lead to crashes.

    /// <summary>
    /// Gets the last x-<paramref name="amount"/> of characters from the given string.
    /// If the given string's length is smaller than the requested <see cref="amount"/> the full string is returned.
    /// If the given <paramref name="amount"/> is negative, an empty string will be returned.
    /// </summary>
    /// <param name="string">The string from which to extract the last x-<paramref name="amount"/> of characters.</param>
    /// <param name="amount">The amount of characters to return.</param>
    /// <returns>The last x-<paramref name="amount"/> of characters from the given string.</returns>
    public static string GetLast(this string @string, int amount)
    {
        if (@string == null) {
            return @string;
        }

        if (amount < 0) {
            return String.Empty;
        }

        if (amount >= @string.Length) {
            return @string;
        } else {
            return @string.Substring(@string.Length - amount);
        }
    }

Postman Chrome: What is the difference between form-data, x-www-form-urlencoded and raw

Here are some supplemental examples to see the raw text that Postman passes in the request. You can see this by opening the Postman console:

enter image description here

form-data

Header

content-type: multipart/form-data; boundary=--------------------------590299136414163472038474

Body

key1=value1key2=value2

x-www-form-urlencoded

Header

Content-Type: application/x-www-form-urlencoded

Body

key1=value1&key2=value2

Raw text/plain

Header

Content-Type: text/plain

Body

This is some text.

Raw json

Header

Content-Type: application/json

Body

{"key1":"value1","key2":"value2"}

How to describe table in SQL Server 2008?

The sp_help built-in procedure is the SQL Server's closest thing to Oracle's DESC function IMHO

sp_help MyTable

Use

sp_help "[SchemaName].[TableName]" 

or

sp_help "[InstanceName].[SchemaName].[TableName]"

in case you need to qualify the table name further

What is a callback function?

I believe this "callback" jargon has been mistakenly used in a lot of places. My definition would be something like:

A callback function is a function that you pass to someone and let them call it at some point of time.

I think people just read the first sentence of the wiki definition:

a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code.

I've been working with lots of APIs, see various of bad examples. Many people tend to name a function pointer (a reference to executable code) or anonymous functions(a piece of executable code) "callback", if they are just functions why do you need another name for this?

Actually only the second sentence in wiki definition reveals the differences between a callback function and a normal function:

This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

so the difference is who you are going to pass the function and how your passed in function is going to be called. If you just define a function and pass it to another function and called it directly in that function body, don't call it a callback. The definition says your passed in function is gonna be called by "lower-level" function.

I hope people can stop using this word in ambiguous context, it can't help people to understand better only worse.

How to run an EXE file in PowerShell with parameters with spaces and quotes

This worked for me:

PowerShell.exe -Command "& ""C:\Some Script\Path With Spaces.ps1"""

The key seems to be that the whole command is enclosed in outer quotes, the "&" ampersand is used to specify another child command file is being executed, then finally escaped (doubled-double-) quotes around the path/file name with spaces in you wanted to execute in the first place.

This is also completion of the only workaround to the MS connect issue that -File does not pass-back non-zero return codes and -Command is the only alternative. But until now it was thought a limitation of -Command was that it didn't support spaces. I've updated that feedback item too.

http://connect.microsoft.com/PowerShell/feedback/details/750653/powershell-exe-doesn-t-return-correct-exit-codes-when-using-the-file-option

Execute raw SQL using Doctrine 2

I had the same problem. You want to look the connection object supplied by the entity manager:

$conn = $em->getConnection();

You can then query/execute directly against it:

$statement = $conn->query('select foo from bar');
$num_rows_effected = $conn->exec('update bar set foo=1');

See the docs for the connection object at http://www.doctrine-project.org/api/dbal/2.0/doctrine/dbal/connection.html

How does it work - requestLocationUpdates() + LocationRequest/Listener

I use this one:

LocationManager.requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener)

For example, using a 1s interval:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);

the time is in milliseconds, the distance is in meters.

This automatically calls:

public void onLocationChanged(Location location) {
    //Code here, location.getAccuracy(), location.getLongitude() etc...
}

I also had these included in the script but didnt actually use them:

public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}

In short:

public class GPSClass implements LocationListener {

    public void onLocationChanged(Location location) {
        // Called when a new location is found by the network location provider.
        Log.i("Message: ","Location changed, " + location.getAccuracy() + " , " + location.getLatitude()+ "," + location.getLongitude());
    }

    public void onStatusChanged(String provider, int status, Bundle extras) {}
    public void onProviderEnabled(String provider) {}
    public void onProviderDisabled(String provider) {}

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,1000,0,this);
    }
}

Show pop-ups the most elegant way

Angular-ui comes with dialog directive.Use it and set templateurl to whatever page you want to include.That is the most elegant way and i have used it in my project as well. You can pass several other parameters for dialog as per need.

Removing the password from a VBA project

I found this here that describes how to set the VBA Project Password. You should be able to modify it to unset the VBA Project Password.

This one does not use SendKeys.

Let me know if this helps! JFV

Python Pandas - Find difference between two data frames

Perhaps a simpler one-liner, with identical or different column names. Worked even when df2['Name2'] contained duplicate values.

newDf = df1.set_index('Name1')
           .drop(df2['Name2'], errors='ignore')
           .reset_index(drop=False)

Remove spacing between table cells and rows

Add border-collapse: collapse into the style attribute value of the inner table element. You could alternatively add the attribute cellspacing=0 there, but then you would have a double border between the cells.

I.e.:

<table class="main-story-image" style="float: left; width: 180px; margin: 0 25px 25px 25px; border-collapse: collapse">

Java Object Null Check for method

If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use

if(null != books[i]){/*do stuff*/}

Example:

public static double calculateInventoryTotal(Book[] books){
    Objects.requireNotNull(books, "Books must not be null");

    double total = 0;

    for (int i = 0; i < books.length; i++){
        if(null != book[i]){
            total += books[i].getPrice();
        }
    }

    return total;
}

Is there an alternative to string.Replace that is case-insensitive?

The regular expression method should work. However what you can also do is lower case the string from the database, lower case the %variables% you have, and then locate the positions and lengths in the lower cased string from the database. Remember, positions in a string don't change just because its lower cased.

Then using a loop that goes in reverse (its easier, if you do not you will have to keep a running count of where later points move to) remove from your non-lower cased string from the database the %variables% by their position and length and insert the replacement values.

CodeIgniter - File upload required validation

CodeIgniter file upload optionally ...works perfectly..... :)

---------- controller ---------

function file()
{
 $this->load->view('includes/template', $data);
}

function valid_file()
{
 $this->form_validation->set_rules('userfile', 'File', 'trim|xss_clean');

 if ($this->form_validation->run()==FALSE) 
 {
    $this->file();
 }
 else
 {
  $config['upload_path']   = './documents/';
  $config['allowed_types'] = 'gif|jpg|png|docx|doc|txt|rtf';
  $config['max_size']      = '1000';
  $config['max_width']     = '1024';
  $config['max_height']    = '768';

  $this->load->library('upload', $config);

  if ( !$this->upload->do_upload('userfile',FALSE))
  {
    $this->form_validation->set_message('checkdoc', $data['error'] = $this->upload->display_errors());

    if($_FILES['userfile']['error'] != 4)
    {
        return false;
    }

  }
  else
  {
    return true;
  }
}

i just use this lines which makes it optionally,

if($_FILES['userfile']['error'] != 4)
{
 return false;
}

$_FILES['userfile']['error'] != 4 is for file required to upload.

you can make it unnecessary by using $_FILES['userfile']['error'] != 4, then it will pass this error for file required and works great with other types of errors if any by using return false , hope it works for u ....

How to remove indentation from an unordered list item?

Can you provide a link ? thanks I can take a look Most likely your css selector isnt strong enough or can you try

padding:0!important;

'gulp' is not recognized as an internal or external command

If you have mysql install in your windows 10 try uninstall every myqsl app from your computer. Its work for me. exactly when i installed the mysql in my computer gulp command and some other commands stop working and then i have tried everything but not nothing worked for me.

Days between two dates?

Do you mean full calendar days, or groups of 24 hours?

For simply 24 hours, assuming you're using Python's datetime, then the timedelta object already has a days property:

days = (a - b).days

For calendar days, you'll need to round a down to the nearest day, and b up to the nearest day, getting rid of the partial day on either side:

roundedA = a.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
roundedB = b.replace(hour = 0, minute = 0, second = 0, microsecond = 0)
days = (roundedA - roundedB).days

Looping over arrays, printing both index and value

you can always use iteration param:

ITER=0
for I in ${FOO[@]}
do  
    echo ${I} ${ITER}
    ITER=$(expr $ITER + 1)
done

selecting rows with id from another table

Try this (subquery):

SELECT * FROM terms WHERE id IN 
   (SELECT term_id FROM terms_relation WHERE taxonomy = "categ")

Or you can try this (JOIN):

SELECT t.* FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

If you want to receive all fields from two tables:

SELECT t.id, t.name, t.slug, tr.description, tr.created_at, tr.updated_at 
  FROM terms AS t 
   INNER JOIN terms_relation AS tr 
   ON t.id = tr.term_id AND tr.taxonomy = "categ"

Yes/No message box using QMessageBox

If you want to make it in python you need check this code in your workbench. also write like this. we created a popup box with python.

msgBox = QMessageBox()
msgBox.setText("The document has been modified.")
msgBox.setInformativeText("Do you want to save your changes?")
msgBox.setStandardButtons(QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel)
msgBox.setDefaultButton(QMessageBox.Save)
ret = msgBox.exec_()

C++ -- expected primary-expression before ' '

You don't need "string" in your call to wordLengthFunction().

int wordLength = wordLengthFunction(string word);

should be

int wordLength = wordLengthFunction(word);

How to reload current page without losing any form data?

Register an event listener for keyup event:

document.getElementById("input").addEventListener("keyup", function(e){
  var someVarName = input.value;
  sessionStorage.setItem("someVarKey", someVarName);
  input.value = sessionStorage.getItem("someVarKey");
});

send mail from linux terminal in one line

You can use an echo with a pipe to avoid prompts or confirmation.

echo "This is the body" | mail -s "This is the subject" [email protected]

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

numpy get index where value is true

A simple and clean way: use np.argwhere to group the indices by element, rather than dimension as in np.nonzero(a) (i.e., np.argwhere returns a row for each non-zero element).

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.argwhere(a>4)
array([[5],
       [6],
       [7],
       [8],
       [9]])

np.argwhere(a) is the same as np.transpose(np.nonzero(a)).

Note: You cannot use a(np.argwhere(a>4)) to get the corresponding values in a. The recommended way is to use a[(a>4).astype(bool)] or a[(a>4) != 0] rather than a[np.nonzero(a>4)] as they handle 0-d arrays correctly. See the documentation for more details. As can be seen in the following example, a[(a>4).astype(bool)] and a[(a>4) != 0] can be simplified to a[a>4].

Another example:

>>> a = np.array([5,-15,-8,-5,10])
>>> a
array([  5, -15,  -8,  -5,  10])
>>> a > 4
array([ True, False, False, False,  True])
>>> a[a > 4]
array([ 5, 10])
>>> a = np.add.outer(a,a)
>>> a
array([[ 10, -10,  -3,   0,  15],
       [-10, -30, -23, -20,  -5],
       [ -3, -23, -16, -13,   2],
       [  0, -20, -13, -10,   5],
       [ 15,  -5,   2,   5,  20]])
>>> a = np.argwhere(a>4)
>>> a
array([[0, 0],
       [0, 4],
       [3, 4],
       [4, 0],
       [4, 3],
       [4, 4]])
>>> [print(i,j) for i,j in a]
0 0
0 4
3 4
4 0
4 3
4 4

Align nav-items to right side in bootstrap-4

In Bootstrap 4 alpha-6 version, As navbar is using flex model, you can use justify-content-end in parent's div and remove mr-auto.

<div class="collapse navbar-collapse justify-content-end" id="navbarText">
  <ul class="navbar-nav">
    <li class="nav-item active">
      <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
    </li>
    <li class="nav-item">
      <a class="nav-link" href="#">Link</a>
    </li>
    <li class="nav-item">
      <a class="nav-link disabled" href="#">Disabled</a>
    </li>
  </ul>
</div>

This works like a charm :)

Modifying CSS class property values on the fly with JavaScript / jQuery

Contrary to some of the answers here, editing the stylesheet itself with Javascript is not only possible, but higher performance. Simply doing $('.myclass').css('color: red') will end up looping through every item matching the selector and individually setting the style attribute. This is really inefficient and if you have hundreds of elements, it's going to cause problems.

Changing classes on the items is a better idea, but you still suffer from the same problem in that you're changing an attribute on N items, which could be a large number. A better solution might be to change the class on one single parent item or a small number of parents and then hit the target items using the "Cascade" in css. This serves in most situations, but not all.

Sometimes you need to change the CSS of a lot of items to something dynamic, or there's no good way for you to do so by hitting a small number of parents. Changing the stylesheet itself, or adding a small new one to override the existing css is an extremely efficient way to change the display of items. You're only interacting with the DOM in one spot and the browser can handle deploying those changes really efficiently.

jss is one library that helps make it easier to directly edit the stylesheet from javascript.

How to loop through file names returned by find?

find <path> -xdev -type f -name *.txt -exec ls -l {} \;

This will list the files and give details about attributes.

Cycles in an Undirected Graph

By the way, if you happen to know that it is connected, then simply it is a tree (thus no cycles) if and only if |E|=|V|-1. Of course that's not a small amount of information :)

Ternary operators in JavaScript without an "else"

First of all, a ternary expression is not a replacement for an if/else construct - it's an equivalent to an if/else construct that returns a value. That is, an if/else clause is code, a ternary expression is an expression, meaning that it returns a value.

This means several things:

  • use ternary expressions only when you have a variable on the left side of the = that is to be assigned the return value
  • only use ternary expressions when the returned value is to be one of two values (or use nested expressions if that is fitting)
  • each part of the expression (after ? and after : ) should return a value without side effects (the expression x = true returns true as all expressions return the last value, but it also changes x without x having any effect on the returned value)

In short - the 'correct' use of a ternary expression is

var resultofexpression = conditionasboolean ? truepart: falsepart;

Instead of your example condition ? x=true : null ;, where you use a ternary expression to set the value of x, you can use this:

 condition && (x = true);

This is still an expression and might therefore not pass validation, so an even better approach would be

 void(condition && x = true);

The last one will pass validation.

But then again, if the expected value is a boolean, just use the result of the condition expression itself

var x = (condition); // var x = (foo == "bar");

UPDATE

In relation to your sample, this is probably more appropriate:

defaults.slideshowWidth = defaults.slideshowWidth || obj.find('img').width()+'px';

How to check programmatically if an application is installed or not in Android?

A cool answer to other problems. If you do not want to differentiate "com.myapp.debug" and "com.myapp.release" for example !

public static boolean isAppInstalled(final Context context, final String packageName) {
    final List<ApplicationInfo> appsInfo = context.getPackageManager().getInstalledApplications(0);
    for (final ApplicationInfo appInfo : appsInfo) {
        if (appInfo.packageName.contains(packageName)) return true;
    }
    return false;
}

How to check if a socket is connected/disconnected in C#?

Following the advice from NibblyPig and zendar, I came up with the code below, which works on every test I made. I ended up needing both the ping, and the poll. The ping will let me know if the cable has been disconnected, or the physical layer otherwise disrupted (router powered off, etc). But sometimes after reconnect I get a RST, the ping is ok, but the tcp state is not.

#region CHECKS THE SOCKET'S HEALTH
    if (_tcpClient.Client.Connected)
    {
            //Do a ping test to see if the server is reachable
            try
            {
                Ping pingTest = new Ping()
                PingReply reply = pingTest.Send(ServeripAddress);
                if (reply.Status != IPStatus.Success) ConnectionState = false;
            } catch (PingException) { ConnectionState = false; }

            //See if the tcp state is ok
            if (_tcpClient.Client.Poll(5000, SelectMode.SelectRead) && (_tcpClient.Client.Available == 0))
            {
                ConnectionState = false;
            }
        }
    }
    else { ConnectionState = false; }
#endregion

Convert string[] to int[] in one line of code using LINQ

var asIntegers = arr.Select(s => int.Parse(s)).ToArray(); 

Have to make sure you are not getting an IEnumerable<int> as a return

How to make an unaware datetime timezone aware in python

I agree with the previous answers, and is fine if you are ok to start in UTC. But I think it is also a common scenario for people to work with a tz aware value that has a datetime that has a non UTC local timezone.

If you were to just go by name, one would probably infer replace() will be applicable and produce the right datetime aware object. This is not the case.

the replace( tzinfo=... ) seems to be random in its behaviour. It is therefore useless. Do not use this!

localize is the correct function to use. Example:

localdatetime_aware = tz.localize(datetime_nonaware)

Or a more complete example:

import pytz
from datetime import datetime
pytz.timezone('Australia/Melbourne').localize(datetime.now())

gives me a timezone aware datetime value of the current local time:

datetime.datetime(2017, 11, 3, 7, 44, 51, 908574, tzinfo=<DstTzInfo 'Australia/Melbourne' AEDT+11:00:00 DST>)

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

How to get cookie expiration date / creation date from javascript?

One possibility is to delete to cookie you are looking for the expiration date from and rewrite it. Then you'll know the expiration date.

What are libtool's .la file for?

According to http://blog.flameeyes.eu/2008/04/14/what-about-those-la-files, they're needed to handle dependencies. But using pkg-config may be a better option:

In a perfect world, every static library needing dependencies would have its own .pc file for pkg-config, and every package trying to statically link to that library would be using pkg-config --static to get the libraries to link to.

Why are iframes considered dangerous and a security risk?

The IFRAME element may be a security risk if your site is embedded inside an IFRAME on hostile site. Google "clickjacking" for more details. Note that it does not matter if you use <iframe> or not. The only real protection from this attack is to add HTTP header X-Frame-Options: DENY and hope that the browser knows its job.

In addition, IFRAME element may be a security risk if any page on your site contains an XSS vulnerability which can be exploited. In that case the attacker can expand the XSS attack to any page within the same domain that can be persuaded to load within an <iframe> on the page with XSS vulnerability. This is because content from the same origin (same domain) is allowed to access the parent content DOM (practically execute JavaScript in the "host" document). The only real protection methods from this attack is to add HTTP header X-Frame-Options: DENY and/or always correctly encode all user submitted data (that is, never have an XSS vulnerability on your site - easier said than done).

That's the technical side of the issue. In addition, there's the issue of user interface. If you teach your users to trust that URL bar is supposed to not change when they click links (e.g. your site uses a big iframe with all the actual content), then the users will not notice anything in the future either in case of actual security vulnerability. For example, you could have an XSS vulnerability within your site that allows the attacker to load content from hostile source within your iframe. Nobody could tell the difference because the URL bar still looks identical to previous behavior (never changes) and the content "looks" valid even though it's from hostile domain requesting user credentials.

If somebody claims that using an <iframe> element on your site is dangerous and causes a security risk, he does not understand what <iframe> element does, or he is speaking about possibility of <iframe> related vulnerabilities in browsers. Security of <iframe src="..."> tag is equal to <img src="..." or <a href="..."> as long there are no vulnerabilities in the browser. And if there's a suitable vulnerability, it might be possible to trigger it even without using <iframe>, <img> or <a> element, so it's not worth considering for this issue.

However, be warned that content from <iframe> can initiate top level navigation by default. That is, content within the <iframe> is allowed to automatically open a link over current page location (the new location will be visible in the address bar). The only way to avoid that is to add sandbox attribute without value allow-top-navigation. For example, <iframe sandbox="allow-forms allow-scripts" ...>. Unfortunately, sandbox also disables all plugins, always. For example, Youtube content cannot be sandboxed because Flash player is still required to view all Youtube content. No browser supports using plugins and disallowing top level navigation at the same time.

Note that X-Frame-Options: DENY also protects from rendering performance side-channel attack that can read content cross-origin (also known as "Pixel perfect Timing Attacks").

How can I send the "&" (ampersand) character via AJAX?

The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:

$.ajax({
  type: "POST",
  url: "/link.json",
  data: { value: poststr },
  error: function(){ alert('some error occured'); }
});

If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.

What is JavaScript garbage collection?

Reference types do not store the object directly into the variable to which it is assigned, so the object variable in the example below, doesn’t actually contain the object instance. Instead, it holds a pointer (or reference) to the location in memory, where the object exists.

var object = new Object();

if you assign one reference typed variable to another, each variable gets a copy of the pointer, and both still reference to the same object in memory.

var object1 = new Object();
var object2 = object1;

Two variables pointing to one object

JavaScript is a garbage-collected language, so you don’t really need to worry about memory allocations when you use reference types. However, it’s best to dereference objects that you no longer need so that the garbage collector can free up that memory. The best way to do this is to set the object variable to null.

var object1 = new Object();
// do something
object1 = null; // dereference

Dereferencing objects is especially important in very large applications that use millions of objects.

from The Principles of Object-Oriented JavaScript - NICHOLAS C. ZAKAS

How to animate CSS Translate

There are jQuery-plugins that help you achieve this like: http://ricostacruz.com/jquery.transit/

How to swap two variables in JavaScript

Use a third variable like this:

var a = 1,
    b = 2,
    c = a;

a = b; // must be first or a and b end up being both 1
b = c;

DEMO - Using a third variable


Check if a specific value exists at a specific key in any subarray of a multidimensional array

function checkMultiArrayValue($array) {
        global $test;
        foreach ($array as $key => $item) {

            if(!empty($item) && is_array($item)) {
                checkMultiArrayValue($item);
            }else {
                if($item)
                 $test[$key] = $item;

            }
        }
        return $test;   
    }

 $multiArray = array(    
                0 =>  array(  
                      "country"   => "",  
                      "price"    => 4,  
                      "discount-price" => 0,  
               ),);

$test = checkMultiArrayValue($multiArray);
echo "<pre>"
print_r($test);

Will return array who have index and value

How to change onClick handler dynamically?

Use .onclick (all lowercase). Like so:

document.getElementById("foo").onclick = function () {
  alert('foo'); // do your stuff
  return false; // <-- to suppress the default link behaviour
};

Actually, you'll probably find yourself way better off using some good library (I recommend jQuery for several reasons) to get you up and running, and writing clean javascript.

Cross-browser (in)compatibilities are a right hell to deal with for anyone - let alone someone who's just starting.

Export data from R to Excel

Another option is the openxlsx-package. It doesn't depend on and can read, edit and write Excel-files. From the description from the package:

openxlsx simplifies the the process of writing and styling Excel xlsx files from R and removes the dependency on Java

Example usage:

library(openxlsx)

# read data from an Excel file or Workbook object into a data.frame
df <- read.xlsx('name-of-your-excel-file.xlsx')

# for writing a data.frame or list of data.frames to an xlsx file
write.xlsx(df, 'name-of-your-excel-file.xlsx')

Besides these two basic functions, the openxlsx-package has a host of other functions for manipulating Excel-files.

For example, with the writeDataTable-function you can create formatted tables in an Excel-file.

Java AES encryption and decryption

You state that you want to encrypt/decrypt a password. I'm not sure exactly of what your specific use case is but, generally, passwords are not stored in a form where they can be decrypted. General practice is to salt the password and use suitably powerful one-way hash (such as PBKDF2).

Take a look at the following link for more information.

http://crackstation.net/hashing-security.htm

How to convert HH:mm:ss.SSS to milliseconds?

Using JODA:

PeriodFormatter periodFormat = new PeriodFormatterBuilder()
  .minimumParsedDigits(2)
  .appendHour() // 2 digits minimum
  .appendSeparator(":")
  .minimumParsedDigits(2)
  .appendMinute() // 2 digits minimum
  .appendSeparator(":")
  .minimumParsedDigits(2)
  .appendSecond()
  .appendSeparator(".")
  .appendMillis3Digit()
  .toFormatter();
Period result = Period.parse(string, periodFormat);
return result.toStandardDuration().getMillis();

How to uninstall an older PHP version from centOS7

Subscribing to the IUS Community Project Repository

cd ~
curl 'https://setup.ius.io/' -o setup-ius.sh

Run the script:

sudo bash setup-ius.sh

Upgrading mod_php with Apache

This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section.

Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted.

sudo yum remove php-cli mod_php php-common

Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted.

sudo yum install mod_php70u php70u-cli php70u-mysqlnd

Finally, restart Apache to load the new version of mod_php:

sudo apachectl restart

You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl:

systemctl status httpd

Passing multiple values to a single PowerShell script parameter

The easiest way is probably to use two parameters: One for hosts (can be an array), and one for vlan.

param([String[]] $Hosts, [String] $VLAN)

Instead of

foreach ($i in $args)

you can use

foreach ($hostName in $Hosts)

If there is only one host, the foreach loop will iterate only once. To pass multiple hosts to the script, pass it as an array:

myScript.ps1 -Hosts host1,host2,host3 -VLAN 2

...or something similar.

Decimal or numeric values in regular expression validation

Below is the perfect one for mentioned requirement :

^[0-9]{1,3}(,[0-9]{3})*(([\\.,]{1}[0-9]*)|())$

How to make git mark a deleted and a new file as a file move?

Here's a quick and dirty solution for one, or a few, renamed and modified files that are uncommitted.

Let's say the file was named foo and now it's named bar:

  1. Rename bar to a temp name:

    mv bar side
    
  2. Checkout foo:

    git checkout HEAD foo
    
  3. Rename foo to bar with Git:

    git mv foo bar
    
  4. Now rename your temporary file back to bar.

    mv side bar
    

This last step is what gets your changed content back into the file.

While this can work, if the moved file is too different in content from the original git will consider it more efficient to decide this is a new object. Let me demonstrate:

$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md
    modified:   work.js

$ git add README.md work.js # why are the changes unstaged, let's add them.
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    deleted:    README
    new file:   README.md
    modified:   work.js

$ git stash # what? let's go back a bit
Saved working directory and index state WIP on dir: f7a8685 update
HEAD is now at f7a8685 update
$ git status
On branch workit
Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .idea/

nothing added to commit but untracked files present (use "git add" to track)
$ git stash pop
Removing README
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README
    modified:   work.js

Dropped refs/stash@{0} (1ebca3b02e454a400b9fb834ed473c912a00cd2f)
$ git add work.js
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README

$ git add README # hang on, I want it removed
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    deleted:    README
    new file:   README.md
    modified:   work.js

$ mv README.md Rmd # Still? Try the answer I found.
$ git checkout README
error: pathspec 'README' did not match any file(s) known to git.
$ git checkout HEAD README # Ok the answer needed fixing.
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    new file:   README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    deleted:    README.md
    modified:   work.js

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Rmd

$ git mv README README.md
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   work.js

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    Rmd

$ mv Rmd README.md
$ git status
On branch workit
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   .gitignore
    renamed:    README -> README.md
    modified:   work.js

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   README.md
    modified:   work.js

$ # actually that's half of what I wanted; \
  # and the js being modified twice? Git prefers it in this case.

How to convert a char to a String?

I am converting Char Array to String

Char[] CharArray={ 'A', 'B', 'C'};
String text = String.copyValueOf(CharArray);

gradient descent using python and numpy

Following @thomas-jungblut implementation in python, i did the same for Octave. If you find something wrong please let me know and i will fix+update.

Data comes from a txt file with the following rows:

1 10 1000
2 20 2500
3 25 3500
4 40 5500
5 60 6200

think about it as a very rough sample for features [number of bedrooms] [mts2] and last column [rent price] which is what we want to predict.

Here is the Octave implementation:

%
% Linear Regression with multiple variables
%

% Alpha for learning curve
alphaNum = 0.0005;

% Number of features
n = 2;

% Number of iterations for Gradient Descent algorithm
iterations = 10000

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% No need to update after here
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

DATA = load('CHANGE_WITH_DATA_FILE_PATH');

% Initial theta values
theta = ones(n + 1, 1);

% Number of training samples
m = length(DATA(:, 1));

% X with one mor column (x0 filled with '1's)
X = ones(m, 1);
for i = 1:n
  X = [X, DATA(:,i)];
endfor

% Expected data must go always in the last column  
y = DATA(:, n + 1)

function gradientDescent(x, y, theta, alphaNum, iterations)
  iterations = [];
  costs = [];

  m = length(y);

  for iteration = 1:10000
    hypothesis = x * theta;

    loss = hypothesis - y;

    % J(theta)    
    cost = sum(loss.^2) / (2 * m);

    % Save for the graphic to see if the algorithm did work
    iterations = [iterations, iteration];
    costs = [costs, cost];

    gradient = (x' * loss) / m; % /m is for the average

    theta = theta - (alphaNum * gradient);
  endfor    

  % Show final theta values
  display(theta)

  % Show J(theta) graphic evolution to check it worked, tendency must be zero
  plot(iterations, costs);

endfunction

% Execute gradient descent
gradientDescent(X, y, theta, alphaNum, iterations);

How should I make my VBA code compatible with 64-bit Windows?

This work for me:

#If VBA7 And Win64 Then
    Private Declare PtrSafe Function ShellExecuteA Lib "Shell32.dll" _
        (ByVal hwnd As Long, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
       ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As Long) As Long
#Else

    Private Declare Function ShellExecuteA Lib "Shell32.dll" _
        (ByVal hwnd As Long, _
        ByVal lpOperation As String, _
        ByVal lpFile As String, _
        ByVal lpParameters As String, _
        ByVal lpDirectory As String, _
        ByVal nShowCmd As Long) As Long
#End If

Thanks Jon49 for insight.

How does the @property decorator work in Python?

This following:

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, _x_set, _x_del, 
                    "I'm the 'x' property.")

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x

    def _x_set(self, value):
        self._x = value

    def _x_del(self):
        del self._x

    x = property(_x_get, doc="I'm the 'x' property.")
    x = x.setter(_x_set)
    x = x.deleter(_x_del)

Is the same as:

class C(object):
    def __init__(self):
        self._x = None

    def _x_get(self):
        return self._x
    x = property(_x_get, doc="I'm the 'x' property.")

    def _x_set(self, value):
        self._x = value
    x = x.setter(_x_set)

    def _x_del(self):
        del self._x
    x = x.deleter(_x_del)

Which is the same as :

class C(object):
    def __init__(self):
        self._x = None

    @property
    def x(self):
        """I'm the 'x' property."""
        return self._x

    @x.setter
    def x(self, value):
        self._x = value

    @x.deleter
    def x(self):
        del self._x

How to write a link like <a href="#id"> which link to the same page in PHP?

try this

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html>
    <body>
        <a href="#name">click me</a>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br>
        <div name="name" id="name">here</div>
    </body>
    </html>

Immutable vs Mutable types

Mutable means that it can change/mutate. Immutable the opposite.

Some Python data types are mutable, others not.

Let's find what are the types that fit in each category and see some examples.


Mutable

In Python there are various mutable types:

  • lists

  • dict

  • set

Let's see the following example for lists.

list = [1, 2, 3, 4, 5]

If I do the following to change the first element

list[0] = '!'
#['!', '2', '3', '4', '5']

It works just fine, as lists are mutable.

If we consider that list, that was changed, and assign a variable to it

y = list

And if we change an element from the list such as

list[0] = 'Hello'
#['Hello', '2', '3', '4', '5']

And if one prints y it will give

['Hello', '2', '3', '4', '5']

As both list and y are referring to the same list, and we have changed the list.


Immutable

In some programming languages one can define a constant such as the following

const a = 10

And if one calls, it would give an error

a = 20

However, that doesn't exist in Python.

In Python, however, there are various immutable types:

  • None

  • bool

  • int

  • float

  • str

  • tuple

Let's see the following example for strings.

Taking the string a

a = 'abcd'

We can get the first element with

a[0]
#'a'

If one tries to assign a new value to the element in the first position

a[0] = '!'

It will give an error

'str' object does not support item assignment

When one says += to a string, such as

a += 'e'
#'abcde'

It doesn't give an error, because it is pointing a to a different string.

It would be the same as the following

a = a + 'f'

And not changing the string.

Some Pros and Cons of being immutable

• The space in memory is known from the start. It would not require extra space.

• Usually, it makes things more efficiently. Finding, for example, the len() of a string is much faster, as it is part of the string object.

Free easy way to draw graphs and charts in C++?

Cern's ROOT produces some pretty nice stuff, I use it to display Neural Network data a lot.

Detect enter press in JTextField

For each text field in your frame, invoke the addKeyListener method. Then implement and override the keyPressed method, as others have indicated. Now you can press enter from any field in your frame to activate your action.

@Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_ENTER){
                //perform action
            }
        }

Uncaught ReferenceError: $ is not defined error in jQuery

Scripts are loaded in the order you have defined them in the HTML.

Therefore if you first load:

<script type="text/javascript" src="./javascript.js"></script>

without loading jQuery first, then $ is not defined.

You need to first load jQuery so that you can use it.

I would also recommend placing your scripts at the bottom of your HTML for performance reasons.

Is null check needed before calling instanceof?

Using a null reference as the first operand to instanceof returns false.

Bad Gateway 502 error with Apache mod_proxy and Tomcat

You can use proxy-initial-not-pooled

See http://httpd.apache.org/docs/2.2/mod/mod_proxy_http.html :

If this variable is set no pooled connection will be reused if the client connection is an initial connection. This avoids the "proxy: error reading status line from remote server" error message caused by the race condition that the backend server closed the pooled connection after the connection check by the proxy and before data sent by the proxy reached the backend. It has to be kept in mind that setting this variable downgrades performance, especially with HTTP/1.0 clients.

We had this problem, too. We fixed it by adding

SetEnv proxy-nokeepalive 1
SetEnv proxy-initial-not-pooled 1

and turning keepAlive on all servers off.

mod_proxy_http is fine in most scenarios but we are running it with heavy load and we still got some timeout problems we do not understand.

But see if the above directive fits your needs.

Stop jQuery .load response from being cached

You can replace the jquery load function with a version that has cache set to false.

(function($) {
  var _load = jQuery.fn.load;
  $.fn.load = function(url, params, callback) {
  if ( typeof url !== "string" && _load ) {
        return _load.apply( this, arguments );
  }
    var selector, type, response,
      self = this,
      off = url.indexOf(" ");

    if (off > -1) {
      selector = stripAndCollapse(url.slice(off));
      url = url.slice(0, off);
    }

    // If it's a function
    if (jQuery.isFunction(params)) {

      // We assume that it's the callback
      callback = params;
      params = undefined;

      // Otherwise, build a param string
    } else if (params && typeof params === "object") {
      type = "POST";
    }

    // If we have elements to modify, make the request
    if (self.length > 0) {
      jQuery.ajax({
        url: url,

        // If "type" variable is undefined, then "GET" method will be used.
        // Make value of this field explicit since
        // user can override it through ajaxSetup method
        type: type || "GET",
        dataType: "html",
        cache: false,
        data: params
      }).done(function(responseText) {

        // Save response for use in complete callback
        response = arguments;

        self.html(selector ?

          // If a selector was specified, locate the right elements in a dummy div
          // Exclude scripts to avoid IE 'Permission Denied' errors
          jQuery("<div>").append(jQuery.parseHTML(responseText)).find(selector) :

          // Otherwise use the full result
          responseText);

        // If the request succeeds, this function gets "data", "status", "jqXHR"
        // but they are ignored because response was set above.
        // If it fails, this function gets "jqXHR", "status", "error"
      }).always(callback && function(jqXHR, status) {
        self.each(function() {
          callback.apply(this, response || [jqXHR.responseText, status, jqXHR]);
        });
      });
    }

    return this;
  }
})(jQuery);

Place this somewhere global where it will run after jquery loads and you should be all set. Your existing load code will no longer be cached.

javascript setTimeout() not working

Please change your code as follows:

<script>
    var button = document.getElementById("reactionTester");
    var start = document.getElementById("start");
    function init() {
        var startInterval/*in milliseconds*/ = Math.floor(Math.random()*30)*1000;
        setTimeout(startTimer,startInterval); 
    }
    function startTimer(){
        document.write("hey");
    }
</script>

See if that helps. Basically, the difference is references the 'startTimer' function instead of executing it.

Java Regex Capturing Groups

Your understanding is correct. However, if we walk through:

  • (.*) will swallow the whole string;
  • it will need to give back characters so that (\\d+) is satistifed (which is why 0 is captured, and not 3000);
  • the last (.*) will then capture the rest.

I am not sure what the original intent of the author was, however.

ExecuteNonQuery: Connection property has not been initialized.

Opening and closing the connection takes a lot of time. And use the "using" as another member suggested. I changed your code slightly, but put the SQL creation and opening and closing OUTSIDE your loop. Which should speed up the execution a bit.

  static void Main()
        {
            EventLog alog = new EventLog();
            alog.Log = "Application";
            alog.MachineName = ".";
            /*  ALSO: USE the USING Statement as another member suggested
            using (SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True")
            {

                using (SqlCommand comm = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1))
                {
                    // add the code in here
                    // AND REMEMBER: connection1.Open();

                }
            }*/
            SqlConnection connection1 = new SqlConnection(@"Data Source=.\sqlexpress;Initial Catalog=syslog2;Integrated Security=True");
            SqlDataAdapter cmd = new SqlDataAdapter();
            // Do it one line
            cmd.InsertCommand = new SqlCommand("INSERT INTO Application VALUES (@EventLog, @TimeGenerated, @EventType, @SourceName, @ComputerName, @InstanceId, @Message) ", connection1);
            // OR YOU CAN DO IN SEPARATE LINE :
            // cmd.InsertCommand.Connection = connection1;
            connection1.Open();

            // CREATE YOUR SQLCONNECTION ETC OUTSIDE YOUR FOREACH LOOP
            foreach (EventLogEntry entry in alog.Entries)
            {
                cmd.InsertCommand.Parameters.Add("@EventLog", SqlDbType.VarChar).Value = alog.Log;
                cmd.InsertCommand.Parameters.Add("@TimeGenerated", SqlDbType.DateTime).Value = entry.TimeGenerated;
                cmd.InsertCommand.Parameters.Add("@EventType", SqlDbType.VarChar).Value = entry.EntryType;
                cmd.InsertCommand.Parameters.Add("@SourceName", SqlDbType.VarChar).Value = entry.Source;
                cmd.InsertCommand.Parameters.Add("@ComputerName", SqlDbType.VarChar).Value = entry.MachineName;
                cmd.InsertCommand.Parameters.Add("@InstanceId", SqlDbType.VarChar).Value = entry.InstanceId;
                cmd.InsertCommand.Parameters.Add("@Message", SqlDbType.VarChar).Value = entry.Message;
                int rowsAffected = cmd.InsertCommand.ExecuteNonQuery();
            }
            connection1.Close(); // AND CLOSE IT ONCE, AFTER THE LOOP
        }

Navigate to another page with a button in angular 2

You can use routerLink in the following manner,

<input type="button" value="Add Bulk Enquiry" [routerLink]="['../addBulkEnquiry']" class="btn">

or use <button [routerLink]="['./url']"> in your case, for more info you could read the entire stacktrace on github https://github.com/angular/angular/issues/9471

the other methods are also correct but they create a dependency on the component file.

Hope your concern is resolved.

Java difference between FileWriter and BufferedWriter

BufferedWriter is more efficient. It saves up small writes and writes in one larger chunk if memory serves me correctly. If you are doing lots of small writes then I would use BufferedWriter. Calling write calls to the OS which is slow so having as few writes as possible is usually desirable.

How to pass multiple parameters in json format to a web service using jquery?

I think the best way is:

data: "{'Ids':['2','2']}"

To read this values Ids[0], Ids[1].

TortoiseSVN icons not showing up under Windows 7

I tried everything here (and some otherplaces), and what worked for me (after doing all of these, the registry changes are mandatory I think) was to change the setting for Icon Overlays\Status Cache from Default to Shell, and I also checked "Show overlays and context menu only in explorer". Not sure which of those two did it but it works now.

Using Intent in an Android application to show another activity

Use this code:

Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
finish();

context: refer to current activity context,

please make sure that you have added activity in android manifest file.

Following code for adding activity in android manifest file

<Activity name=".SecondActivity">
</Activity>

adding a datatable in a dataset

Just give any name to the DataTable Like:

DataTable dt = new DataTable();
dt = SecondDataTable.Copy();    
dt .TableName = "New Name";
DataSet.Tables.Add(dt );

How to get video duration, dimension and size in PHP?

If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.

$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!

 if (file_exists($vid)) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $vid); // check mime type
    finfo_close($finfo);

    if (preg_match('/video\/*/', $mime_type)) {

        $video_attributes = _get_video_attributes($vid, $ffmpeg_path);

        print_r('Codec: ' . $video_attributes['codec'] . '<br/>');

        print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');

        print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
                . $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');

        print_r('Size:  ' . _human_filesize(filesize($vid)));

    } else {
        print_r('File is not a video.');
    }
} else {
    print_r('File does not exist.');
}

function _get_video_attributes($video, $ffmpeg) {

    $command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

.NET Console Application Exit Event

For the CTRL+C case, you can use this:

// Tell the system console to handle CTRL+C by calling our method that
// gracefully shuts down.
Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);


static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)
{
            Console.WriteLine("Shutting down...");
            // Cleanup here
            System.Threading.Thread.Sleep(750);
}

Datagridview: How to set a cell in editing mode?

private void DgvRoomInformation_CellEnter(object sender, DataGridViewCellEventArgs e)
{
  if (DgvRoomInformation.CurrentCell.ColumnIndex == 4)  //example-'Column index=4'
  {
    DgvRoomInformation.BeginEdit(true);   
  }
}

PHP: Split a string in to an array foreach char

Since str_split() function is not multibyte safe, an easy solution to split UTF-8 encoded string is to use preg_split() with u (PCRE_UTF8) modifier.

preg_split( '//u', $str, null, PREG_SPLIT_NO_EMPTY )

How to multiply duration by integer?

My turn:

https://play.golang.org/p/RifHKsX7Puh

package main

import (
    "fmt"
    "time"
)

func main() {
    var n int = 77
    v := time.Duration( 1.15 * float64(n) ) * time.Second

    fmt.Printf("%v %T", v, v)
}

It helps to remember the simple fact, that underlyingly the time.Duration is a mere int64, which holds nanoseconds value.

This way, conversion to/from time.Duration becomes a formality. Just remember:

  • int64
  • always nanosecs

Change width of select tag in Twitter Bootstrap

For me Pawan's css class combined with display: inline-block (so the selects don't stack) works best. And I wrap it in a media-query, so it stays Mobile Friendly:

@media (min-width: $screen-xs) {

    .selectwidthauto {
         width:auto !important;
         display: inline-block;
    }

}

How to remove an element from an array in Swift

The let keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var instead, e.g:

var animals = ["cats", "dogs", "chimps", "moose"]

animals.remove(at: 2)  //["cats", "dogs", "moose"]

A non-mutating alternative that will keep the original collection unchanged is to use filter to create a new collection without the elements you want removed, e.g:

let pets = animals.filter { $0 != "chimps" }

Mips how to store user input string

Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:

         .text
         .globl __start
    __start:
         la $a0,str1 #Load and print string asking for string
         li $v0,4
         syscall

         li $v0,8 #take in input
         la $a0, buffer #load byte space into address
         li $a1, 20 # allot the byte space for string
         move $t0,$a0 #save string to t0
         syscall

         la $a0,str2 #load and print "you wrote" string
         li $v0,4
         syscall

         la $a0, buffer #reload byte space to primary address
         move $a0,$t0 # primary address = t0 address (load pointer)
         li $v0,4 # print string
         syscall

         li $v0,10 #end program
         syscall


               .data
             buffer: .space 20
             str1:  .asciiz "Enter string(max 20 chars): "
             str2:  .asciiz "You wrote:\n"
             ###############################
             #Output:
             #Enter string(max 20 chars): qwerty 123
             #You wrote:
             #qwerty 123
             #Enter string(max 20 chars):   new world oreddeYou wrote:
             #  new world oredde //lol special character
             ###############################

How to set upload_max_filesize in .htaccess?

php_value memory_limit 30M
php_value post_max_size 100M
php_value upload_max_filesize 30M

Use all 3 in .htaccess after everything at last line. php_value post_max_size must be more than than the remaining two.

Check/Uncheck checkbox with JavaScript

function setCheckboxValue(checkbox,value) {
    if (checkbox.checked!=value)
        checkbox.click();
}

What's the difference between an Angular component and module

Component is the template(view) + a class (Typescript code) containing some logic for the view + metadata(to tell angular about from where to get data it needs to display the template).

Modules basically group the related components, services together so that you can have chunks of functionality which can then run independently. For example, an app can have modules for features, for grouping components for a particular feature of your app, such as a dashboard, which you can simply grab and use inside another application.

Import data into Google Colaboratory

The simplest way I've made is :

  1. Make repository on github with your dataset
  2. Clone Your repository with ! git clone --recursive [GITHUB LINK REPO]
  3. Find where is your data ( !ls command )
  4. Open file with pandas as You do it in normal jupyter notebook.

what is an illegal reflective access

If you want to go with the add-open option, here's a command to find which module provides which package ->

java --list-modules | tr @ " " | awk '{ print $1 }' | xargs -n1 java -d

the name of the module will be shown with the @ while the name of the packages without it

NOTE: tested with JDK 11

IMPORTANT: obviously is better than the provider of the package does not do the illegal access

How can I simulate a click to an anchor tag?

None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):

var clicker = null;
$('a').click(function(e){ 
    clicker=$(this); // capture the clicked dom object
    /* ... do something ... */
    e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.

Stop executing further code in Java

Either return; from the method early, or throw an exception.

There is no other way to prevent further code from being executed short of exiting the process completely.

Django TemplateDoesNotExist?

If you encounter this problem when you add an app from scratch. It is probably because that you miss some settings. Three steps is needed when adding an app.

1?Create the directory and template file.

Suppose you have a project named mysite and you want to add an app named your_app_name. Put your template file under mysite/your_app_name/templates/your_app_name as following.

+-- mysite
¦   +-- settings.py
¦   +-- urls.py
¦   +-- wsgi.py
+-- your_app_name
¦   +-- admin.py
¦   +-- apps.py
¦   +-- models.py
¦   +-- templates
¦   ¦   +-- your_app_name
¦   ¦       +-- my_index.html
¦   +-- urls.py
¦   +-- views.py

2?Add your app to INSTALLED_APPS.

Modify settings.py

INSTALLED_APPS = [
    ...
    'your_app_name',
    ...
]

3?Add your app directory to DIRS in TEMPLATES.

Modify settings.py.

TEMPLATES = [
    {
        ...
        'DIRS': [os.path.join(BASE_DIR, 'templates'),
                 os.path.join(BASE_DIR, 'your_app_name', 'templates', 'your_app_name'),
                ...
                ]
    }
]

javax.crypto.IllegalBlockSizeException : Input length must be multiple of 16 when decrypting with padded cipher

The algorithm you are using, "AES", is a shorthand for "AES/ECB/NoPadding". What this means is that you are using the AES algorithm with 128-bit key size and block size, with the ECB mode of operation and no padding.

In other words: you are only able to encrypt data in blocks of 128 bits or 16 bytes. That's why you are getting that IllegalBlockSizeException exception.

If you want to encrypt data in sizes that are not multiple of 16 bytes, you are either going to have to use some kind of padding, or a cipher-stream. For instance, you could use CBC mode (a mode of operation that effectively transforms a block cipher into a stream cipher) by specifying "AES/CBC/NoPadding" as the algorithm, or PKCS5 padding by specifying "AES/ECB/PKCS5", which will automatically add some bytes at the end of your data in a very specific format to make the size of the ciphertext multiple of 16 bytes, and in a way that the decryption algorithm will understand that it has to ignore some data.

In any case, I strongly suggest that you stop right now what you are doing and go study some very introductory material on cryptography. For instance, check Crypto I on Coursera. You should understand very well the implications of choosing one mode or another, what are their strengths and, most importantly, their weaknesses. Without this knowledge, it is very easy to build systems which are very easy to break.


Update: based on your comments on the question, don't ever encrypt passwords when storing them at a database!!!!! You should never, ever do this. You must HASH the passwords, properly salted, which is completely different from encrypting. Really, please, don't do what you are trying to do... By encrypting the passwords, they can be decrypted. What this means is that you, as the database manager and who knows the secret key, you will be able to read every password stored in your database. Either you knew this and are doing something very, very bad, or you didn't know this, and should get shocked and stop it.

How to open a file for both reading and writing?

Here's how you read a file, and then write to it (overwriting any existing data), without closing and reopening:

with open(filename, "r+") as f:
    data = f.read()
    f.seek(0)
    f.write(output)
    f.truncate()

Access-Control-Allow-Origin wildcard subdomains, ports and protocols

in my case using angular

in my HTTP interceptor , i set

with Credentials: true.

in the header of the request

Return index of highest value in an array

Other answers may have shorter code but this one should be the most efficient and is easy to understand.

/**
 * Get key of the max value
 *
 * @var array $array
 * @return mixed
*/
function array_key_max_value($array)
{
    $max = null;
    $result = null;
    foreach ($array as $key => $value) {
        if ($max === null || $value > $max) {
            $result = $key;
            $max = $value;
        }
    }

    return $result;
}

Equal height rows in a flex container

The answer is NO.

The reason is provided in the flexbox specification:

6. Flex Lines

In a multi-line flex container, the cross size of each line is the minimum size necessary to contain the flex items on the line.

In other words, when there are multiple lines in a row-based flex container, the height of each line (the "cross size") is the minimum height necessary to contain the flex items on the line.

Equal height rows, however, are possible in CSS Grid Layout:

Otherwise, consider a JavaScript alternative.

how to loop through each row of dataFrame in pyspark

Using list comprehensions in python, you can collect an entire column of values into a list using just two lines:

df = sqlContext.sql("show tables in default")
tableList = [x["tableName"] for x in df.rdd.collect()]

In the above example, we return a list of tables in database 'default', but the same can be adapted by replacing the query used in sql().

Or more abbreviated:

tableList = [x["tableName"] for x in sqlContext.sql("show tables in default").rdd.collect()]

And for your example of three columns, we can create a list of dictionaries, and then iterate through them in a for loop.

sql_text = "select name, age, city from user"
tupleList = [{name:x["name"], age:x["age"], city:x["city"]} 
             for x in sqlContext.sql(sql_text).rdd.collect()]
for row in tupleList:
    print("{} is a {} year old from {}".format(
        row["name"],
        row["age"],
        row["city"]))

How to dynamically insert a <script> tag via jQuery after page load?

A simpler way is:

$('head').append('<script type="text/javascript" src="your.js"></script>');

You can also use this form to load css.

Copying from one text file to another using Python

The oneliner:

open("out1.txt", "w").writelines([l for l in open("in.txt").readlines() if "tests/file/myword" in l])

Recommended with with:

with open("in.txt") as f:
    lines = f.readlines()
    lines = [l for l in lines if "ROW" in l]
    with open("out.txt", "w") as f1:
        f1.writelines(lines)

Using less memory:

with open("in.txt") as f:
    with open("out.txt", "w") as f1:
        for line in f:
            if "ROW" in line:
                f1.write(line) 

Connecting to SQL Server Express - What is my server name?

This was provided after installation of Sql Express 2019

Server=localhost\SQLEXPRESS;Database=master;Trusted_Connection=True;

So just use 'localhost\SQLEXPRESS' in server name and windows authentication worked for me.

enter image description here

Int to byte array

If you came here from Google

Alternative answer to an older question refers to John Skeet's Library that has tools for letting you write primitive data types directly into a byte[] with an Index offset. Far better than BitConverter if you need performance.

Older thread discussing this issue here

John Skeet's Libraries are here

Just download the source and look at the MiscUtil.Conversion namespace. EndianBitConverter.cs handles everything for you.

In c# is there a method to find the max of 3 numbers?

Maximum element value in priceValues[] is maxPriceValues :

double[] priceValues = new double[3];
priceValues [0] = 1;
priceValues [1] = 2;
priceValues [2] = 3;
double maxPriceValues = priceValues.Max();

Why is SQL server throwing this error: Cannot insert the value NULL into column 'id'?

@curt is correct, but I've noticed that sometimes even this fails with NULL disallowed errors, and it seems to be intermittent. I avoided the error at all times, by also setting the Indenty Seed to 1 and IDENTITY(1, 1) NOT FOR REPLICATION.

ReactJS: Maximum update depth exceeded error

In this case , this code

{<td><span onClick={this.toggle()}>Details</span></td>}

causes toggle function to call immediately and re render it again and again thus making infinite calls.

so passing only the reference to that toggle method will solve the problem.

so ,

{<td><span onClick={this.toggle}>Details</span></td>}

will be the solution code.

If you want to use the () , you should use an arrow function like this

{<td><span onClick={()=> this.toggle()}>Details</span></td>}

In case you want to pass parameters you should choose the last option and you can pass parameters like this

{<td><span onClick={(arg)=>this.toggle(arg)}>Details</span></td>}

In the last case it doesn't call immediately and don't cause the re render of the function, hence avoiding infinite calls.

How can I force component to re-render with hooks in React?

This is possible with useState or useReducer, since useState uses useReducer internally:

const [, updateState] = React.useState();
const forceUpdate = React.useCallback(() => updateState({}), []);

forceUpdate isn't intended to be used under normal circumstances, only in testing or other outstanding cases. This situation may be addressed in a more conventional way.

setCount is an example of improperly used forceUpdate, setState is asynchronous for performance reasons and shouldn't be forced to be synchronous just because state updates weren't performed correctly. If a state relies on previously set state, this should be done with updater function,

If you need to set the state based on the previous state, read about the updater argument below.

<...>

Both state and props received by the updater function are guaranteed to be up-to-date. The output of the updater is shallowly merged with state.

setCount may not be an illustrative example because its purpose is unclear but this is the case for updater function:

setCount(){
  this.setState(({count}) => ({ count: count + 1 }));
  this.setState(({count2}) => ({ count2: count + 1 }));
  this.setState(({count}) => ({ count2: count + 1 }));
}

This is translated 1:1 to hooks, with the exception that functions that are used as callbacks should better be memoized:

   const [state, setState] = useState({ count: 0, count2: 100 });

   const setCount = useCallback(() => {
     setState(({count}) => ({ count: count + 1 }));
     setState(({count2}) => ({ count2: count + 1 }));
     setState(({count}) => ({ count2: count + 1 }));
   }, []);

How can I find the length of a number?

You should go for the simplest one (stringLength), readability always beats speed. But if you care about speed here are some below.

Three different methods all with varying speed.

// 34ms
let weissteinLength = function(n) { 
    return (Math.log(Math.abs(n)+1) * 0.43429448190325176 | 0) + 1;
}

// 350ms
let stringLength = function(n) {
    return n.toString().length;
}

// 58ms
let mathLength = function(n) {
    return Math.ceil(Math.log(n + 1) / Math.LN10);
}

// Simple tests below if you care about performance.

let iterations = 1000000;
let maxSize = 10000;

// ------ Weisstein length.

console.log("Starting weissteinLength length.");
let startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    weissteinLength(Math.random() * maxSize);
}

console.log("Ended weissteinLength length. Took : " + (Date.now() - startTime ) + "ms");


// ------- String length slowest.

console.log("Starting string length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    stringLength(Math.random() * maxSize);
}

console.log("Ended string length. Took : " + (Date.now() - startTime ) + "ms");


// ------- Math length.

console.log("Starting math length.");
startTime = Date.now();

for (let index = 0; index < iterations; index++) {
    mathLength(Math.random() * maxSize);
}

How to list the certificates stored in a PKCS12 keystore with keytool?

You can also use openssl to accomplish the same thing:

$ openssl pkcs12 -nokeys -info \
    -in </path/to/file.pfx> \
    -passin pass:<pfx's password>

MAC Iteration 2048
MAC verified OK
PKCS7 Encrypted data: pbeWithSHA1And40BitRC2-CBC, Iteration 2048
Certificate bag
Bag Attributes
    localKeyID: XX XX XX XX XX XX XX XX XX XX XX XX XX 48 54 A0 47 88 1D 90
    friendlyName: jedis-server
subject=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXX/CN=something1
issuer=/C=US/ST=NC/L=Raleigh/O=XXX Security/OU=XXXX/CN=something1
-----BEGIN CERTIFICATE-----
...
...
...
-----END CERTIFICATE-----
PKCS7 Data
Shrouded Keybag: pbeWithSHA1And3-KeyTripleDES-CBC, Iteration 2048

Angular 2 change event - model changes

Use the (ngModelChange) event to detect changes on the model

Should I use != or <> for not equal in T-SQL?

Although they function the same way, != means exactly "not equal to", while <> means greater than and less than the value stored.

Consider >= or <=, and this will make sense when factoring in your indexes to queries... <> will run faster in some cases (with the right index), but in some other cases (index free) they will run just the same.

This also depends on how your databases system reads the values != and <>. The database provider may just shortcut it and make them function the same, so there isn't any benefit either way.PostgreSQL and SQL Server do not shortcut this; it is read as it appears above.

Entity Framework Code First - two Foreign Keys from same table

I know it's a several years old post and you may solve your problem with above solution. However, i just want to suggest using InverseProperty for someone who still need. At least you don't need to change anything in OnModelCreating.

The below code is un-tested.

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty("HomeTeam")]
    public virtual ICollection<Match> HomeMatches { get; set; }

    [InverseProperty("GuestTeam")]
    public virtual ICollection<Match> GuestMatches { get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public virtual Team HomeTeam { get; set; }
    public virtual Team GuestTeam { get; set; }
}

You can read more about InverseProperty on MSDN: https://msdn.microsoft.com/en-us/data/jj591583?f=255&MSPPError=-2147217396#Relationships

Export a graph to .eps file with R

Yes, open a postscript() device with a filename ending in .eps, do your plot(s) and call dev.off().

Difference between jQuery’s .hide() and setting CSS to display: none

.hide() stores the previous display property just before setting it to none, so if it wasn't the standard display property for the element you're a bit safer, .show() will use that stored property as what to go back to. So...it does some extra work, but unless you're doing tons of elements, the speed difference should be negligible.

A python class that acts like dict

Don’t inherit from Python built-in dict, ever! for example update method woldn't use __setitem__, they do a lot for optimization. Use UserDict.

from collections import UserDict

class MyDict(UserDict):
    def __delitem__(self, key):
        pass
    def __setitem__(self, key, value):
        pass

Adding a SVN repository in Eclipse

Do you have any working repositories in this instance of eclipse?

I've had problems in the past with the default Subclipse subversion client on Windows, you need to make sure the native subversion client is installed and correctly configured (I've got TortoiseSVN to work in the past) if you want to use the default client adapter.

On a recent install I tried the "beta" drivers (I have Eclipse Ganymede and "SVNKit (Pure Java) SVNKit v1.2.0.4502") that you can optionally install with Subclipse and they worked pretty much straight out of the box, although a colleague found he had to go through a few hoops to make sure Eclipse installed them (and their dependancies) correctly.

Here are the packages that appear in "Help" -> "Software Updates" -> "Installed Software":

Subclipse                  1.4.0
Subversion Client Adapter  1.5.0.1
SVNKit Client Adapter      1.5.0.1
SVNKit Library             1.2.0.4502

These are probably a little out of date now, and the latest version will probably work better, but this is what I can see working right now.

Search for highest key/index in an array

You can get the maximum key this way:

<?php
$arr = array("a"=>"test", "b"=>"ztest");
$max = max(array_keys($arr));
?>

Use the auto keyword in C++ STL

The auto keyword gets the type from the expression on the right of =. Therefore it will work with any type, the only requirement is to initialize the auto variable when declaring it so that the compiler can deduce the type.

Examples:

auto a = 0.0f;  // a is float
auto b = std::vector<int>();  // b is std::vector<int>()

MyType foo()  { return MyType(); }

auto c = foo();  // c is MyType

jQuery - setting the selected value of a select control via its text description

This accepted answer does not seem correct, while .val('newValue') is correct for the function, trying to retrieve a select by its name does not work for me, I had to use the id and classname to get my element

c# dictionary one key many values

You could use a Dictionary<TKey, List<TValue>>.

That would allow each key to reference a list of values.

What is the IntelliJ shortcut key to create a javadoc comment?

Typing /** + then pressing Enter above a method signature will create Javadoc stubs for you.

Java: How to insert CLOB into oracle database

passing the xml content as string.

table1 

ID   int
XML  CLOB



import oracle.jdbc.OraclePreparedStatement;
/*
Your Code
*/
 void insert(int id, String xml){
    try {
        String sql = "INSERT INTO table1(ID,XML) VALUES ("
                + id
                + "', ? )";
        PreparedStatement ps = conn.prepareStatement(sql);
        ((OraclePreparedStatement) ps).setStringForClob(1, xml);
        ps.execute();
        result = true;
        } catch (Exception e) {
        e.printStackTrace();
    }
  }

What is the use of rt.jar file in java?

Your question is already answered here :

Basically, rt.jar contains all of the compiled class files for the base Java Runtime ("rt") Environment. Normally, javac should know the path to this file

Also, a good link on what happens if we try to include our class file in rt.jar.

Cast IList to List

    public async Task<List<TimeAndAttendanceShift>> FindEntitiesByExpression(Expression<Func<TimeAndAttendanceShift, bool>> predicate)
    {
        IList<TimeAndAttendanceShift> result = await _dbContext.Set<TimeAndAttendanceShift>().Where(predicate).ToListAsync<TimeAndAttendanceShift>();

        return result.ToList<TimeAndAttendanceShift>();
    }

Python Decimals format

Just use Python's standard string formatting methods:

>>> "{0:.2}".format(1.234232)
'1.2'
>>> "{0:.3}".format(1.234232)
'1.23'

If you are using a Python version under 2.6, use

>>> "%f" % 1.32423
'1.324230'
>>> "%.2f" % 1.32423
'1.32'
>>> "%d" % 1.32423
'1'

Excel Macro - Select all cells with data and format as table

Try this one for current selection:

Sub A_SelectAllMakeTable2()
    Dim tbl As ListObject
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

or equivalent of your macro (for Ctrl+Shift+End range selection):

Sub A_SelectAllMakeTable()
    Dim tbl As ListObject
    Dim rng As Range

    Set rng = Range(Range("A1"), Range("A1").SpecialCells(xlLastCell))
    Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, rng, , xlYes)
    tbl.TableStyle = "TableStyleMedium15"
End Sub

How to extract epoch from LocalDate and LocalDateTime?

'Millis since unix epoch' represents an instant, so you should use the Instant class:

private long toEpochMilli(LocalDateTime localDateTime)
{
  return localDateTime.atZone(ZoneId.systemDefault())
    .toInstant().toEpochMilli();
}

How do I find Waldo with Mathematica?

I've found Waldo!

waldo had been found

How I've done it

First, I'm filtering out all colours that aren't red

waldo = Import["http://www.findwaldo.com/fankit/graphics/IntlManOfLiterature/Scenes/DepartmentStore.jpg"];
red = Fold[ImageSubtract, #[[1]], Rest[#]] &@ColorSeparate[waldo];

Next, I'm calculating the correlation of this image with a simple black and white pattern to find the red and white transitions in the shirt.

corr = ImageCorrelate[red, 
   Image@Join[ConstantArray[1, {2, 4}], ConstantArray[0, {2, 4}]], 
   NormalizedSquaredEuclideanDistance];

I use Binarize to pick out the pixels in the image with a sufficiently high correlation and draw white circle around them to emphasize them using Dilation

pos = Dilation[ColorNegate[Binarize[corr, .12]], DiskMatrix[30]];

I had to play around a little with the level. If the level is too high, too many false positives are picked out.

Finally I'm combining this result with the original image to get the result above

found = ImageMultiply[waldo, ImageAdd[ColorConvert[pos, "GrayLevel"], .5]]

Redirect to external URL with return in laravel

You can use Redirect::away($url)

What is the recommended project structure for spring boot rest projects?

config - class which will read from property files

cache - caching mechanism class files

constants - constant defined class

controller - controller class

exception - exception class

model - pojos classes will be present

security - security classes

service - Impl classes

util - utility classes

validation - validators classes

bootloader - main class

how to convert from int to char*?

See this answer https://stackoverflow.com/a/23010605/2760919

For your case, just change the type in snprintf from long ("%ld") to int ("%n").

Updating state on props change in React Form

You Probably Don't Need Derived State

1. Set a key from the parent

When a key changes, React will create a new component instance rather than update the current one. Keys are usually used for dynamic lists but are also useful here.

2. Use getDerivedStateFromProps / componentWillReceiveProps

If key doesn’t work for some reason (perhaps the component is very expensive to initialize)

By using getDerivedStateFromProps you can reset any part of state but it seems a little buggy at this time (v16.7)!, see the link above for the usage

How to make a div with a circular shape?

Demo

css

div {
    width: 100px;
    height: 100px;
    border-radius: 50%;
    background: red;
}

html

<div></div>

How to show loading spinner in jQuery?

There are a couple of ways. My preferred way is to attach a function to the ajaxStart/Stop events on the element itself.

$('#loadingDiv')
    .hide()  // Hide it initially
    .ajaxStart(function() {
        $(this).show();
    })
    .ajaxStop(function() {
        $(this).hide();
    })
;

The ajaxStart/Stop functions will fire whenever you do any Ajax calls.

Update: As of jQuery 1.8, the documentation states that .ajaxStart/Stop should only be attached to document. This would transform the above snippet to:

var $loading = $('#loadingDiv').hide();
$(document)
  .ajaxStart(function () {
    $loading.show();
  })
  .ajaxStop(function () {
    $loading.hide();
  });

Given a view, how do I get its viewController?

For debug purposes only, you can call _viewDelegate on views to get their view controllers. This is private API, so not safe for App Store, but for debugging it is useful.

Other useful methods:

  • _viewControllerForAncestor - get the first controller that manages a view in the superview chain. (thanks n00neimp0rtant)
  • _rootAncestorViewController - get the ancestor controller whose view hierarchy is set in the window currently.

Create <div> and append <div> dynamically

var iDiv = document.createElement('div');

iDiv.id = 'block';
iDiv.className = 'block';
document.getElementsByTagName('body')[0].appendChild(iDiv);

var div2 = document.createElement('div');

div2.className = 'block-2';
iDiv.appendChild(div2);

Aborting a shell script if any command returns a non-zero value

I am just throwing in another one for reference since there was an additional question to Mark Edgars input and here is an additional example and touches on the topic overall:

[[ `cmd` ]] && echo success_else_silence

Which is the same as cmd || exit errcode as someone showed.

For example, I want to make sure a partition is unmounted if mounted:

[[ `mount | grep /dev/sda1` ]] && umount /dev/sda1

Date constructor returns NaN in IE, but works in Firefox and Chrome

The Date constructor accepts any value. If the primitive [[value]] of the argument is number, then the Date that is created has that value. If primitive [[value]] is String, then the specification only guarantees that the Date constructor and the parse method are capable of parsing the result of Date.prototype.toString and Date.prototype.toUTCString()

A reliable way to set a Date is to construct one and use the setFullYear and setTime methods.

An example of that appears here: http://jibbering.com/faq/#parseDate

ECMA-262 r3 does not define any date formats. Passing string values to the Date constructor or Date.parse has implementation-dependent outcome. It is best avoided.


Edit: The entry from comp.lang.javascript FAQ is: An Extended ISO 8601 local date format YYYY-MM-DD can be parsed to a Date with the following:-

/**Parses string formatted as YYYY-MM-DD to a Date object.
 * If the supplied string does not match the format, an 
 * invalid Date (value NaN) is returned.
 * @param {string} dateStringInRange format YYYY-MM-DD, with year in
 * range of 0000-9999, inclusive.
 * @return {Date} Date object representing the string.
 */

  function parseISO8601(dateStringInRange) {
    var isoExp = /^\s*(\d{4})-(\d\d)-(\d\d)\s*$/,
        date = new Date(NaN), month,
        parts = isoExp.exec(dateStringInRange);

    if(parts) {
      month = +parts[2];
      date.setFullYear(parts[1], month - 1, parts[3]);
      if(month != date.getMonth() + 1) {
        date.setTime(NaN);
      }
    }
    return date;
  }

Parse JSON String to JSON Object in C#.NET

Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

There is a System.Json.dll you should add to your project References.

-Jesse

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

I have found PercentEscaper class from google-http-java-client library, that can be used to implement encodeURIComponent quite easily.

PercentEscaper from google-http-java-client javadoc google-http-java-client home

Where to install Android SDK on Mac OS X?

From http://developer.android.com/sdk/index.html, it seems that you can install the SDK anywhere, so long as you

  1. "execute the android tool in the <sdk>/tools/ folder"
  2. Add the <sdk>/tools directory to your system path

More info can be found here: http://developer.android.com/sdk/installing.html

How to Maximize window in chrome using webDriver (python)

I do the following:

from selenium import webdriver
browser = webdriver.Chrome('C:\chromedriver.exe')
browser.maximize_window()

Call a stored procedure with another in Oracle

Sure, you just call it from within the SP, there's no special syntax.

Ex:

   PROCEDURE some_sp
   AS
   BEGIN
      some_other_sp('parm1', 10, 20.42);
   END;

If the procedure is in a different schema than the one the executing procedure is in, you need to prefix it with schema name.

   PROCEDURE some_sp
   AS
   BEGIN
      other_schema.some_other_sp('parm1', 10, 20.42);
   END;

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Most of the answers here have dealt with how to mange EOFError exceptions, which is really handy if you're unsure about whether the pickled object is empty or not.

However, if you're surprised that the pickle file is empty, it could be because you opened the filename through 'wb' or some other mode that could have over-written the file.

for example:

filename = 'cd.pkl'
with open(filename, 'wb') as f:
    classification_dict = pickle.load(f)

This will over-write the pickled file. You might have done this by mistake before using:

...
open(filename, 'rb') as f:

And then got the EOFError because the previous block of code over-wrote the cd.pkl file.

When working in Jupyter, or in the console (Spyder) I usually write a wrapper over the reading/writing code, and call the wrapper subsequently. This avoids common read-write mistakes, and saves a bit of time if you're going to be reading the same file multiple times through your travails

How can I convert an RGB image into grayscale in Python?

You can also use scikit-image, which provides some functions to convert an image in ndarray, like rgb2gray.

from skimage import color
from skimage import io

img = color.rgb2gray(io.imread('image.png'))

Notes: The weights used in this conversion are calibrated for contemporary CRT phosphors: Y = 0.2125 R + 0.7154 G + 0.0721 B

Alternatively, you can read image in grayscale by:

from skimage import io
img = io.imread('image.png', as_gray=True)