Programs & Examples On #Subversive

The Subversive project aims to provide Subversion (SVN) integration for Eclipse. The Subversive plug-in gives you the ability to work with SVN version control system from the Eclipse workbench.

How to change credentials for SVN repository in Eclipse?

It's too simple to change username and password in Eclipse.

Just follow the following steps:

In your Eclipse,

Goto Window -> Show View -> Other -> (Type as) SVN Repositories -> click that(SVN Repositories) -> Right Click SVN Repositories -> Location Properties -> General tab change the following details for credentials.,

that's it.

Unbound classpath container in Eclipse

The problem happens when you

  • Import project folders into the eclipse workspace.(when projects use different Jre).
  • Update or Reinstall eclipse
  • Change Jre or Build related Settings.
  • Or by there is a configuration mismatch.

You get two errors for each misconfigured files.

  • The project cannot be built until build path errors are resolved.
  • Unbound classpath container: 'JRE System Library.

If the no. of projects having problem is few:

  1. Select each project and apply Quick fix(Ctrl+1)
  2. Either Replace the project's JRE with default JRE or Specify Alternate JRE (or JDK).

You can do the same by right-click project-->Properties(from context menu)-->Java Build Path-->Libraries-->select current unbound library -->Remove-->Add Libraries-->Jre System library-->select default or alternate Jre.

Or directly choose Build Path-->Add libraries in project's context menu.


But the best way to get rid of such problem when you have many projects is:

EITHER

  1. Open the current workspace (in which your project is) in File Explorer.
  2. Delete all org.eclipse.jdt.core.prefs file present in .settings folder of your imported projects.(Be careful while deleting. Don't delete any files or folders inside .metadata folder.)**
  3. Now,Select the .classpath files of projects (those with errors) and open them in a powerful text editor(such as Notepad++).
  4. Find the line similar to <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/> and replace it with <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
  5. Save all the files. And Refresh or restart Eclipse IDE. All the problems are gone.

OR

Get the JRE used by the projects and install on your computer and then specify it..

How do I check out an SVN project into Eclipse as a Java project?

Here are the steps:

  • Install the subclipse plugin (provides svn connectivity in eclipse) and connect to the repository. Instructions here: http://subclipse.tigris.org/install.html
  • Go to File->New->Other->Under the SVN category, select Checkout Projects from SVN.
  • Select your project's root folder and select checkout as a project in the workspace.

It seems you are checking the .project file into the source repository. I would suggest not checking in the .project file so users can have their own version of the file. Also, if you use the subclipse plugin it allows you to check out and configure a source folder as a java project. This process creates the correct .project for you(with the java nature),

Rolling back bad changes with svn in Eclipse

In Eclipse Ganymede (Subclipse)

Select project/file that contains bad change, and from pop-up menu choose:

Team -> Show History

Revisions related to that project/file will be shown in History tab.

Find revision where "bad changes" were committed and from pop-up menu choose:

Revert Changes from Revision X

This will merge changes in file(s) modified within bad revision, with revision prior to bad revision.

There are two scenarios from here:

  1. If you committed no changes for that file (bad revision is last revision for that file), it will simply remove changes made in bad revision. Those changes are merged to your working copy so you have to commit them.

  2. If you committed some changes for that file (bad revision is not last revision for that file), you will have to manually resolve conflict. Let say that you have file readme.txt with, and bad revision number is 33. Also, you've made another commit for that file in revision 34. After you choose Revert Changes from Revision 33 you will have following in your working copy:

readme.txt.merge-left.r33 - bad revision

readme.txt.merge-right.r32 - before bad revision

readme.txt.working - working copy version (same as in r34 if you don't have any uncommitted changes)

Original readme.txt will be marked conflicted, and will contain merged version (where changes from bad revision are removed) with some markers (<<<<<<< .working etc). If you just want to remove changes from bad revision and keep changes made after that, then all you have to do is remove markers. Otherwise, you can copy contents from one of 3 files mentioned above to original file. Whatever you choose, when you are done, mark conflict resolved by

Team - Mark Resolved

Temporary files will be removed and your file will be marked changed. As in 1, you have to commit changes.

Note that this does not remove revision from revision history in svn repository. You simply made new revision where changes from bad revision are removed.

Stored procedure - return identity as output parameter or scalar

Another option would be as the return value for the stored procedure (I don't suggest this though, as that's usually best for error values).

I've included it as both when it's inserting a single row in cases where the stored procedure was being consumed by both other SQL procedures and a front-end which couldn't work with OUTPUT parameters (IBATIS in .NET I believe):

CREATE PROCEDURE My_Insert
    @col1            VARCHAR(20),
    @new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO My_Table (col1)
    VALUES (@col1)

    SELECT @new_identity = SCOPE_IDENTITY()

    SELECT @new_identity AS id

    RETURN
END

The output parameter is easier to work with in T-SQL when calling from other stored procedures IMO, but some programming languages have poor or no support for output parameters and work better with result sets.

Using Spring MVC Test to unit test multipart POST request

Have a look at this example taken from the spring MVC showcase, this is the link to the source code:

@RunWith(SpringJUnit4ClassRunner.class)
public class FileUploadControllerTests extends AbstractContextControllerTests {

    @Test
    public void readString() throws Exception {

        MockMultipartFile file = new MockMultipartFile("file", "orig", null, "bar".getBytes());

        webAppContextSetup(this.wac).build()
            .perform(fileUpload("/fileupload").file(file))
            .andExpect(model().attribute("message", "File 'orig' uploaded successfully"));
    }

}

How to read a single character from the user?

Here's a link to a site that says how you can read a single character in Windows, Linux and OSX: http://code.activestate.com/recipes/134892/

class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()


class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch


class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()


getch = _Getch()

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

How to copy a file along with directory structure/path using python?

To create all intermediate-level destination directories you could use os.makedirs() before copying:

import os
import shutil

srcfile = 'a/long/long/path/to/file.py'
dstroot = '/home/myhome/new_folder'


assert not os.path.isabs(srcfile)
dstdir =  os.path.join(dstroot, os.path.dirname(srcfile))

os.makedirs(dstdir) # create all directories, raise an error if it already exists
shutil.copy(srcfile, dstdir)

Round a double to 2 decimal places

Rounding a double is usually not what one wants. Instead, use String.format() to represent it in the desired format.

Could not find an implementation of the query pattern

You must have forgotten to add a using statement to the file like this:

using System.Linq;

Difference between socket and websocket?

WebSocket is just another application level protocol over TCP protocol, just like HTTP.

Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.

In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.

Play a Sound with Python

I just released a simple python wrapper around sox that will play a sound with Python. It's very easy to install as you need Python 2.6 or greater, sox (easy to get binaries for most architectures) and the wrapper ( https://github.com/standarddeviant/sound4python ). If you don't have sox, go here: http://sourceforge.net/projects/sox/files/sox/

You would play audio with it by:

from sound4python import sound
import random
a = []
for idx in xrange(1*16000):
    a.append(random.randint(-16384,16384))
sound(a)

Keep in mind, the only parts actually involved in playing audio are just these:

from sound4python import sound
...
sound(a)    

Two way sync with rsync

Since the original question also involves a desktop and laptop and example involving music files (hence he's probably using a GUI), I'd also mention one of the best bi-directional, multi-platform, free and open source programs to date: FreeFileSync.

It's GUI based, very fast and intuitive, comes with filtering and many other options, including the ability to remote connect, to view and interactively manage "collisions" (in example, files with similar timestamps) and to switch between bidirectional transfer, mirroring and so on.

How does facebook, gmail send the real time notification?

One important issue with long polling is error handling. There are two types of errors:

  1. The request might timeout in which case the client should reestablish the connection immediately. This is a normal event in long polling when no messages have arrived.

  2. A network error or an execution error. This is an actual error which the client should gracefully accept and wait for the server to come back on-line.

The main issue is that if your error handler reestablishes the connection immediately also for a type 2 error, the clients would DOS the server.

Both answers with code sample miss this.

function longPoll() { 
        var shouldDelay = false;

        $.ajax({
            url: 'poll.php',
            async: true,            // by default, it's async, but...
            dataType: 'json',       // or the dataType you are working with
            timeout: 10000,          // IMPORTANT! this is a 10 seconds timeout
            cache: false

        }).done(function (data, textStatus, jqXHR) {
             // do something with data...

        }).fail(function (jqXHR, textStatus, errorThrown ) {
            shouldDelay = textStatus !== "timeout";

        }).always(function() {
            // in case of network error. throttle otherwise we DOS ourselves. If it was a timeout, its normal operation. go again.
            var delay = shouldDelay ? 10000: 0;
            window.setTimeout(longPoll, delay);
        });
}
longPoll(); //fire first handler

Powershell folder size of folders without listing Subdirectories

This simple solution worked for me as well.

powershell -c "Get-ChildItem -Recurse 'directory_path' | Measure-Object -Property Length -Sum"

How to align absolutely positioned element to center?

If you want to center align an element without knowing it's width and height do:

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);

Example:

_x000D_
_x000D_
*{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
}_x000D_
section{_x000D_
  background:red;_x000D_
  height: 100vh;_x000D_
  width: 100vw;_x000D_
}_x000D_
div{  _x000D_
  width: 80vw;_x000D_
  height: 80vh;_x000D_
  background: white;_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
}
_x000D_
<section>_x000D_
  <div>_x000D_
    <h1>Popup</h1>_x000D_
  </div>_x000D_
</section>
_x000D_
_x000D_
_x000D_

How to SELECT in Oracle using a DBLINK located in a different schema?

I had the same problem I used the solution offered above - I dropped the SYNONYM, created a VIEW with the same name as the synonym. it had a select using the dblink , and gave GRANT SELECT to the other schema It worked great.

error code 1292 incorrect date value mysql

With mysql 5.7, date value like 0000-00-00 00:00:00 is not allowed.

If you want to allow it, you have to update your my.cnf like:

sudo nano /etc/mysql/my.cnf

find

[mysqld]

Add after:

sql_mode="NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Restart mysql service:

sudo service mysql restart

Done!

Why can't I reference my class library?

I had stumbled upon a similar issue recently. I am working in Visual Studio 2015 with Resharper Ultimate 2016.1.2. I was trying to add a new class to my code base while trying to reference a class from another assembly but Resharper would throw an error for that package.

With some help of a co-worker, I figured out that the referenced class existed in the global namespace and wasn't accessible from the new class since it was hidden by another entity of same name that existed in current namespace.

Adding a 'global::' keyword before the required namespace helped me to reference the class I was actually looking for. More details on this can be found on the page listed below:

https://msdn.microsoft.com/en-us/library/c3ay4x3d.aspx

T-SQL: Deleting all duplicate rows but keeping one

You didn't say what version you were using, but in SQL 2005 and above, you can use a common table expression with the OVER Clause. It goes a little something like this:

WITH cte AS (
  SELECT[foo], [bar], 
     row_number() OVER(PARTITION BY foo, bar ORDER BY baz) AS [rn]
  FROM TABLE
)
DELETE cte WHERE [rn] > 1

Play around with it and see what you get.

(Edit: In an attempt to be helpful, someone edited the ORDER BY clause within the CTE. To be clear, you can order by anything you want here, it needn't be one of the columns returned by the cte. In fact, a common use-case here is that "foo, bar" are the group identifier and "baz" is some sort of time stamp. In order to keep the latest, you'd do ORDER BY baz desc)

Difference between Key, Primary Key, Unique Key and Index in MySQL

Unique Keys: The columns in which no two rows are similar

Primary Key: Collection of minimum number of columns which can uniquely identify every row in a table (i.e. no two rows are similar in all the columns constituting primary key). There can be more than one primary key in a table. If there exists a unique-key then it is primary key (not "the" primary key) in the table. If there does not exist a unique key then more than one column values will be required to identify a row like (first_name, last_name, father_name, mother_name) can in some tables constitute primary key.

Index: used to optimize the queries. If you are going to search or sort the results on basis of some column many times (eg. mostly people are going to search the students by name and not by their roll no.) then it can be optimized if the column values are all "indexed" for example with a binary tree algorithm.

Git fetch remote branch

Simply try:

git pull origin your_branch_name

JSON.stringify doesn't work with normal Javascript array

I posted a fix for this here

You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):

// Upgrade for JSON.stringify, updated to allow arrays
(function(){
    // Convert array to object
    var convArrToObj = function(array){
        var thisEleObj = new Object();
        if(typeof array == "object"){
            for(var i in array){
                var thisEle = convArrToObj(array[i]);
                thisEleObj[i] = thisEle;
            }
        }else {
            thisEleObj = array;
        }
        return thisEleObj;
    };
    var oldJSONStringify = JSON.stringify;
    JSON.stringify = function(input){
        if(oldJSONStringify(input) == '[]')
            return oldJSONStringify(convArrToObj(input));
        else
            return oldJSONStringify(input);
    };
})();

How to get rid of punctuation using NLTK tokenizer?

Take a look at the other tokenizing options that nltk provides here. For example, you can define a tokenizer that picks out sequences of alphanumeric characters as tokens and drops everything else:

from nltk.tokenize import RegexpTokenizer

tokenizer = RegexpTokenizer(r'\w+')
tokenizer.tokenize('Eighty-seven miles to go, yet.  Onward!')

Output:

['Eighty', 'seven', 'miles', 'to', 'go', 'yet', 'Onward']

how do you increase the height of an html textbox

Increasing the font size on a text box will usually expand its size automatically.

<input type="text" style="font-size:16pt;">

If you want to set a height that is not proportional to the font size, I would recommend using something like the following. This prevents browsers like IE from rendering the text inside at the top rather than vertically centered.

.form-text{
    padding:15px 0;
}

PHP sessions that have already been started

Try

<?php
    if(!isset($_SESSION)) 
    { 
        session_start(); 
    } 
?>

Pytorch tensor to numpy array

Your question is very poorly worded. Your code (sort of) already does what you want. What exactly are you confused about? x.numpy() answer the original title of your question:

Pytorch tensor to numpy array

you need improve your question starting with your title.

Anyway, just in case this is useful to others. You might need to call detach for your code to work. e.g.

RuntimeError: Can't call numpy() on Variable that requires grad.

So call .detach(). Sample code:

# creating data and running through a nn and saving it

import torch
import torch.nn as nn

from pathlib import Path
from collections import OrderedDict

import numpy as np

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

num_samples = 3
Din, Dout = 1, 1
lb, ub = -1, 1

x = torch.torch.distributions.Uniform(low=lb, high=ub).sample((num_samples, Din))

f = nn.Sequential(OrderedDict([
    ('f1', nn.Linear(Din,Dout)),
    ('out', nn.SELU())
]))
y = f(x)

# save data
y.numpy()
x_np, y_np = x.detach().cpu().numpy(), y.detach().cpu().numpy()
np.savez(path / 'db', x=x_np, y=y_np)

print(x_np)

cpu goes after detach. See: https://discuss.pytorch.org/t/should-it-really-be-necessary-to-do-var-detach-cpu-numpy/35489/5


Also I won't make any comments on the slicking since that is off topic and that should not be the focus of your question. See this:

Understanding slice notation

phpmailer error "Could not instantiate mail function"

Seems in my case it was just SERVER REJECTION. Please check your mail server log / smtp connection accessibility.

Integer value in TextView

It might be cleaner for some people to work with an Integer object so you can just call toString() directly on the object:

Integer length = my_text_view.getText().getLength();
counter_text_view.setText( length.toString() );

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

it happened for me when I deleted the jdk and installed new one somehow the project kept seeing the old one as invalid but couldn't change, so right click on your module -> Open Module Settings -> and choose Compile Sdk Version.

What are some reasons for jquery .focus() not working?

Only "keyboard focusable" elements can be focused with .focus(). div aren't meant to be natively focusable. You have to add tabindex="0" attributes to it to achieve that. input, button, a etc... are natively focusable.

C++11 thread-safe queue

According to the standard condition_variables are allowed to wakeup spuriously, even if the event hasn't occured. In case of a spurious wakeup it will return cv_status::no_timeout (since it woke up instead of timing out), even though it hasn't been notified. The correct solution for this is of course to check if the wakeup was actually legit before proceding.

The details are specified in the standard §30.5.1 [thread.condition.condvar]:

—The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) speci?ed by abs_time, or spuriously.

...

Returns: cv_status::timeout if the absolute timeout (30.2.4) speci?edby abs_time expired, other-ise cv_status::no_timeout.

How to get every first element in 2 dimensional list

You can get it like

[ x[0] for x in a]

which will return a list of the first element of each list in a

Where is Python's sys.path initialized from?

"Initialized from the environment variable PYTHONPATH, plus an installation-dependent default"

-- http://docs.python.org/library/sys.html#sys.path

Split output of command by columns using Bash?

Using array variables

set $(ps | egrep "^11383 "); echo $4

or

A=( $(ps | egrep "^11383 ") ) ; echo ${A[3]}

Is it possible to set a number to NaN or infinity?

Is it possible to set a number to NaN or infinity?

Yes, in fact there are several ways. A few work without any imports, while others require import, however for this answer I'll limit the libraries in the overview to standard-library and NumPy (which isn't standard-library but a very common third-party library).

The following table summarizes the ways how one can create a not-a-number or a positive or negative infinity float:

+-------------------------------------------------------------------+
¦   result ¦ NaN          ¦ Infinity           ¦ -Infinity          ¦
¦ module   ¦              ¦                    ¦                    ¦
¦----------+--------------+--------------------+--------------------¦
¦ built-in ¦ float("nan") ¦ float("inf")       ¦ -float("inf")      ¦
¦          ¦              ¦ float("infinity")  ¦ -float("infinity") ¦
¦          ¦              ¦ float("+inf")      ¦ float("-inf")      ¦
¦          ¦              ¦ float("+infinity") ¦ float("-infinity") ¦
+----------+--------------+--------------------+--------------------¦
¦ math     ¦ math.nan     ¦ math.inf           ¦ -math.inf          ¦
+----------+--------------+--------------------+--------------------¦
¦ cmath    ¦ cmath.nan    ¦ cmath.inf          ¦ -cmath.inf         ¦
+----------+--------------+--------------------+--------------------¦
¦ numpy    ¦ numpy.nan    ¦ numpy.PINF         ¦ numpy.NINF         ¦
¦          ¦ numpy.NaN    ¦ numpy.inf          ¦ -numpy.inf         ¦
¦          ¦ numpy.NAN    ¦ numpy.infty        ¦ -numpy.infty       ¦
¦          ¦              ¦ numpy.Inf          ¦ -numpy.Inf         ¦
¦          ¦              ¦ numpy.Infinity     ¦ -numpy.Infinity    ¦
+-------------------------------------------------------------------+

A couple remarks to the table:

  • The float constructor is actually case-insensitive, so you can also use float("NaN") or float("InFiNiTy").
  • The cmath and numpy constants return plain Python float objects.
  • The numpy.NINF is actually the only constant I know of that doesn't require the -.
  • It is possible to create complex NaN and Infinity with complex and cmath:

    +------------------------------------------------------------------------------------------+
    ¦   result ¦ NaN+0j         ¦ 0+NaNj          ¦ Inf+0j              ¦ 0+Infj               ¦
    ¦ module   ¦                ¦                 ¦                     ¦                      ¦
    ¦----------+----------------+-----------------+---------------------+----------------------¦
    ¦ built-in ¦ complex("nan") ¦ complex("nanj") ¦ complex("inf")      ¦ complex("infj")      ¦
    ¦          ¦                ¦                 ¦ complex("infinity") ¦ complex("infinityj") ¦
    +----------+----------------+-----------------+---------------------+----------------------¦
    ¦ cmath    ¦ cmath.nan ¹    ¦ cmath.nanj      ¦ cmath.inf ¹         ¦ cmath.infj           ¦
    +------------------------------------------------------------------------------------------+
    

    The options with ¹ return a plain float, not a complex.

is there any function to check whether a number is infinity or not?

Yes there is - in fact there are several functions for NaN, Infinity, and neither Nan nor Inf. However these predefined functions are not built-in, they always require an import:

+--------------------------------------------------------------+
¦      for ¦ NaN         ¦ Infinity or    ¦ not NaN and        ¦
¦          ¦             ¦ -Infinity      ¦ not Infinity and   ¦
¦ module   ¦             ¦                ¦ not -Infinity      ¦
¦----------+-------------+----------------+--------------------¦
¦ math     ¦ math.isnan  ¦ math.isinf     ¦ math.isfinite      ¦
+----------+-------------+----------------+--------------------¦
¦ cmath    ¦ cmath.isnan ¦ cmath.isinf    ¦ cmath.isfinite     ¦
+----------+-------------+----------------+--------------------¦
¦ numpy    ¦ numpy.isnan ¦ numpy.isinf    ¦ numpy.isfinite     ¦
+--------------------------------------------------------------+

Again a couple of remarks:

  • The cmath and numpy functions also work for complex objects, they will check if either real or imaginary part is NaN or Infinity.
  • The numpy functions also work for numpy arrays and everything that can be converted to one (like lists, tuple, etc.)
  • There are also functions that explicitly check for positive and negative infinity in NumPy: numpy.isposinf and numpy.isneginf.
  • Pandas offers two additional functions to check for NaN: pandas.isna and pandas.isnull (but not only NaN, it matches also None and NaT)
  • Even though there are no built-in functions, it would be easy to create them yourself (I neglected type checking and documentation here):

    def isnan(value):
        return value != value  # NaN is not equal to anything, not even itself
    
    infinity = float("infinity")
    
    def isinf(value):
        return abs(value) == infinity 
    
    def isfinite(value):
        return not (isnan(value) or isinf(value))
    

To summarize the expected results for these functions (assuming the input is a float):

+----------------------------------------------------------------------+
¦          input ¦ NaN   ¦ Infinity   ¦ -Infinity   ¦ something else   ¦
¦ function       ¦       ¦            ¦             ¦                  ¦
¦----------------+-------+------------+-------------+------------------¦
¦ isnan          ¦ True  ¦ False      ¦ False       ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isinf          ¦ False ¦ True       ¦ True        ¦ False            ¦
+----------------+-------+------------+-------------+------------------¦
¦ isfinite       ¦ False ¦ False      ¦ False       ¦ True             ¦
+----------------------------------------------------------------------+

Is it possible to set an element of an array to NaN in Python?

In a list it's no problem, you can always include NaN (or Infinity) there:

>>> [math.nan, math.inf, -math.inf, 1]  # python list
[nan, inf, -inf, 1]

However if you want to include it in an array (for example array.array or numpy.array) then the type of the array must be float or complex because otherwise it will try to downcast it to the arrays type!

>>> import numpy as np
>>> float_numpy_array = np.array([0., 0., 0.], dtype=float)
>>> float_numpy_array[0] = float("nan")
>>> float_numpy_array
array([nan,  0.,  0.])

>>> import array
>>> float_array = array.array('d', [0, 0, 0])
>>> float_array[0] = float("nan")
>>> float_array
array('d', [nan, 0.0, 0.0])

>>> integer_numpy_array = np.array([0, 0, 0], dtype=int)
>>> integer_numpy_array[0] = float("nan")
ValueError: cannot convert float NaN to integer

Pytorch reshape tensor dimension

torch.reshape() is made to dupe the numpy reshape method.

It came after the view() and torch.resize_() and it is inside the dir(torch) package.

import torch
x=torch.arange(24)
print(x, x.shape)
x_view = x.view(1,2,3,4) # works on is_contiguous() tensor
print(x_view.shape)
x_reshaped = x.reshape(1,2,3,4) # works on any tensor
print(x_reshaped.shape)
x_reshaped2 = torch.reshape(x_reshaped, (-1,)) # part of torch package, while view() and resize_() are not
print(x_reshaped2.shape)

Out:

tensor([ 0,  1,  2,  3,  4,  5,  6,  7,  8,  9, 10, 11, 12, 13, 14, 15, 16, 17,
        18, 19, 20, 21, 22, 23]) torch.Size([24])
torch.Size([1, 2, 3, 4])
torch.Size([1, 2, 3, 4])
torch.Size([24])

But did you know it can also work as a replacement for squeeze() and unsqueeze()

x = torch.tensor([1, 2, 3, 4])
print(x.shape)
x1 = torch.unsqueeze(x, 0)
print(x1.shape)
x2 = torch.unsqueeze(x1, 1)
print(x2.shape)
x3=x.reshape(1,1,4)
print(x3.shape)
x4=x.reshape(4)
print(x4.shape)
x5=x3.squeeze()
print(x5.shape)

Out:

torch.Size([4])
torch.Size([1, 4])
torch.Size([1, 1, 4])
torch.Size([1, 1, 4])
torch.Size([4])
torch.Size([4])

In PANDAS, how to get the index of a known value?

To get the index by value, simply add .index[0] to the end of a query. This will return the index of the first row of the result...

So, applied to your dataframe:

In [1]: a[a['c2'] == 1].index[0]     In [2]: a[a['c1'] > 7].index[0]   
Out[1]: 0                            Out[2]: 4                         

Where the query returns more than one row, the additional index results can be accessed by specifying the desired index, e.g. .index[n]

In [3]: a[a['c2'] >= 7].index[1]     In [4]: a[(a['c2'] > 1) & (a['c1'] < 8)].index[2]  
Out[3]: 4                            Out[4]: 3 

Using a dictionary to select function to execute

You can just use

myDict = {
    "P1": (lambda x: function1()),
    "P2": (lambda x: function2()),
    ...,
    "Pn": (lambda x: functionn())}
myItems = ["P1", "P2", ..., "Pn"]

for item in myItems:
    myDict[item]()

jQuery selector for inputs with square brackets in the name attribute

Per the jQuery documentation, try this:

$('input[inputName\\[\\]=someValue]')

[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:

$('input[name="inputName[]"][value="someValue"]')

How to select rows with no matching entry in another table?

You can do something like this

   SELECT IFNULL(`price`.`fPrice`,100) as fPrice,product.ProductId,ProductName 
          FROM `products` left join `price` ON 
          price.ProductId=product.ProductId AND (GeoFancingId=1 OR GeoFancingId 
          IS NULL) WHERE Status="Active" AND Delete="No"

pytest cannot import module while python can

The answer above not work for me. I just solved it by appending the absolute path of the module which not found to the sys.path at top of the test_xxx.py (your test module), like:

import sys
sys.path.append('path')

What does LINQ return when the results are empty

var lst = new List<int>() { 1, 2, 3 };
var ans = lst.Where( i => i > 3 );

(ans == null).Dump();  // False
(ans.Count() == 0 ).Dump();  // True

(Dump is from LinqPad)

CreateProcess error=2, The system cannot find the file specified

The complete first argument of exec is being interpreted as the executable. Use

p = rt.exec(new String[] {"winrar.exe", "x", "h:\\myjar.jar", "*.*", "h:\\new" }
            null, 
            dir);

Can I set text box to readonly when using Html.TextBoxFor?

<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @readonly = true })%>

What is the difference between RTP or RTSP in a streaming server?

AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.

Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.

To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.

Pretty much everything can be transported through TCP though.

(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)

How to include PHP files that require an absolute path?

Another option, related to Kevin's, is use __FILE__, but instead replace the php file name from within it:

<?php

$docRoot = str_replace($_SERVER['SCRIPT_NAME'], '', __FILE__);
require_once($docRoot . '/lib/include.php');

?>

I've been using this for a while. The only problem is sometimes you don't have $_SERVER['SCRIPT_NAME'], but sometimes there is another variable similar.

How to validate an OAuth 2.0 access token for a resource server?

Update Nov. 2015: As per Hans Z. below - this is now indeed defined as part of RFC 7662.

Original Answer: The OAuth 2.0 spec (RFC 6749) doesn't clearly define the interaction between a Resource Server (RS) and Authorization Server (AS) for access token (AT) validation. It really depends on the AS's token format/strategy - some tokens are self-contained (like JSON Web Tokens) while others may be similar to a session cookie in that they just reference information held server side back at the AS.

There has been some discussion in the OAuth Working Group about creating a standard way for an RS to communicate with the AS for AT validation. My company (Ping Identity) has come up with one such approach for our commercial OAuth AS (PingFederate): https://support.pingidentity.com/s/document-item?bundleId=pingfederate-93&topicId=lzn1564003025072.html#lzn1564003025072__section_N10578_N1002A_N10001. It uses REST based interaction for this that is very complementary to OAuth 2.0.

Java, How do I get current index/key in "for each" loop

You can't, you either need to keep the index separately:

int index = 0;
for(Element song : question) {
    System.out.println("Current index is: " + (index++));
}

or use a normal for loop:

for(int i = 0; i < question.length; i++) {
    System.out.println("Current index is: " + i);
}

The reason is you can use the condensed for syntax to loop over any Iterable, and it's not guaranteed that the values actually have an "index"

How to display a confirmation dialog when clicking an <a> link?

Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:

document.body.onclick = function( e ) {
    // Cross-browser handling
    var evt = e || window.event,
        target = evt.target || evt.srcElement;

    // If the element clicked is an anchor
    if ( target.nodeName === 'A' ) {

        // Add the confirm box
        return confirm( 'Are you sure?' );
    }
};

This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.

Getting list of parameter names inside python function

Well we don't actually need inspect here.

>>> func = lambda x, y: (x, y)
>>> 
>>> func.__code__.co_argcount
2
>>> func.__code__.co_varnames
('x', 'y')
>>>
>>> def func2(x,y=3):
...  print(func2.__code__.co_varnames)
...  pass # Other things
... 
>>> func2(3,3)
('x', 'y')
>>> 
>>> func2.__defaults__
(3,)

For Python 2.5 and older, use func_code instead of __code__, and func_defaults instead of __defaults__.

Installing Pandas on Mac OSX

You need to install newest version of xCode from appStore. It contains the compiler for C(gcc) and C++(g++) for mac. Then you can install pandas without any problem. Use the following commands in terminal:

  1. xcode-select --install

  2. pip3 install pandas

It might take some time as it installs other packages too. Please be patient.

ImportError: No module named 'google'

According to https://developers.google.com/api-client-library/python/apis/oauth2/v1 you need to install google-api-python-client package:

pip install --upgrade google-api-python-client

installing requests module in python 2.7 windows

On windows 10 run cmd.exe with admin rights then type :

1) cd \Python27\scripts

2) pip install requests

It should work. My case was with python 2.7

CSS align one item right with flexbox

To align one flex child to the right set it withmargin-left: auto;

From the flex spec:

One use of auto margins in the main axis is to separate flex items into distinct "groups". The following example shows how to use this to reproduce a common UI pattern - a single bar of actions with some aligned on the left and others aligned on the right.

.wrap div:last-child {
  margin-left: auto;
}

Updated fiddle

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note:

You could achieve a similar effect by setting flex-grow:1 on the middle flex item (or shorthand flex:1) which would push the last item all the way to the right. (Demo)

The obvious difference however is that the middle item becomes bigger than it may need to be. Add a border to the flex items to see the difference.

Demo

_x000D_
_x000D_
.wrap {_x000D_
  display: flex;_x000D_
  background: #ccc;_x000D_
  width: 100%;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.wrap div {_x000D_
  border: 3px solid tomato;_x000D_
}_x000D_
.margin div:last-child {_x000D_
  margin-left: auto;_x000D_
}_x000D_
.grow div:nth-child(2) {_x000D_
  flex: 1;_x000D_
}_x000D_
.result {_x000D_
  background: #ccc;_x000D_
  margin-top: 20px;_x000D_
}_x000D_
.result:after {_x000D_
  content: '';_x000D_
  display: table;_x000D_
  clear: both;_x000D_
}_x000D_
.result div {_x000D_
  float: left;_x000D_
}_x000D_
.result div:last-child {_x000D_
  float: right;_x000D_
}
_x000D_
<div class="wrap margin">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<div class="wrap grow">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>_x000D_
_x000D_
<!-- DESIRED RESULT -->_x000D_
<div class="result">_x000D_
  <div>One</div>_x000D_
  <div>Two</div>_x000D_
  <div>Three</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Decompile .smali files on an APK

dex2jar helps to decompile your apk but not 100%. You will have some problems with .smali files. Dex2jar cannot convert it to java. I know one application that can decompile your apk source files and no problems with .smali files. Here is a link http://www.hensence.com/en/smali2java/

C# Interfaces. Implicit implementation versus Explicit implementation

If you implement explicitly, you will only be able to reference the interface members through a reference that is of the type of the interface. A reference that is the type of the implementing class will not expose those interface members.

If your implementing class is not public, except for the method used to create the class (which could be a factory or IoC container), and except for the interface methods (of course), then I don't see any advantage to explicitly implementing interfaces.

Otherwise, explicitly implementing interfaces makes sure that references to your concrete implementing class are not used, allowing you to change that implementation at a later time. "Makes sure", I suppose, is the "advantage". A well-factored implementation can accomplish this without explicit implementation.

The disadvantage, in my opinion, is that you will find yourself casting types to/from the interface in the implementation code that does have access to non-public members.

Like many things, the advantage is the disadvantage (and vice-versa). Explicitly implementing interfaces will ensure that your concrete class implementation code is not exposed.

What's the simplest way to extend a numpy array in 2 dimensions?

The shortest in terms of lines of code i can think of is for the first question.

>>> import numpy as np
>>> p = np.array([[1,2],[3,4]])

>>> p = np.append(p, [[5,6]], 0)
>>> p = np.append(p, [[7],[8],[9]],1)

>>> p
array([[1, 2, 7],
   [3, 4, 8],
   [5, 6, 9]])

And the for the second question

    p = np.array(range(20))
>>> p.shape = (4,5)
>>> p
array([[ 0,  1,  2,  3,  4],
       [ 5,  6,  7,  8,  9],
       [10, 11, 12, 13, 14],
       [15, 16, 17, 18, 19]])
>>> n = 2
>>> p = np.append(p[:n],p[n+1:],0)
>>> p = np.append(p[...,:n],p[...,n+1:],1)
>>> p
array([[ 0,  1,  3,  4],
       [ 5,  6,  8,  9],
       [15, 16, 18, 19]])

How to write new line character to a file in Java

Here is a snippet that gets the default newline character for the current platform. Use System.getProperty("os.name") and System.getProperty("os.version"). Example:

public static String getSystemNewline(){
    String eol = null;
    String os = System.getProperty("os.name").toLowerCase();
    if(os.contains("mac"){
        int v = Integer.parseInt(System.getProperty("os.version"));
        eol = (v <= 9 ? "\r" : "\n");
    }
    if(os.contains("nix"))
        eol = "\n";
    if(os.contains("win"))
        eol = "\r\n";

    return eol;
}

Where eol is the newline

change figure size and figure format in matplotlib

You can set the figure size if you explicitly create the figure with

plt.figure(figsize=(3,4))

You need to set figure size before calling plt.plot() To change the format of the saved figure just change the extension in the file name. However, I don't know if any of matplotlib backends support tiff

Wait until ActiveWorkbook.RefreshAll finishes - VBA

This worked for me:

ActiveWorkbook.refreshall
ActiveWorkbook.Save

When you save the workbook it's necessary to complete the refresh.

Create a folder if it doesn't already exist

Faster way to create folder:

if (!is_dir('path/to/directory')) {
    mkdir('path/to/directory', 0777, true);
}

How to make an authenticated web request in Powershell?

For those that need Powershell to return additional information like the Http StatusCode, here's an example. Included are the two most likely ways to pass in credentials.

Its a slightly modified version of this SO answer:
How to obtain numeric HTTP status codes in PowerShell

$req = [system.Net.WebRequest]::Create($url)
# method 1 $req.UseDefaultCredentials = $true
# method 2 $req.Credentials = New-Object System.Net.NetworkCredential($username, $pwd, $domain); 
try
{
    $res = $req.GetResponse()
}
catch [System.Net.WebException]
{
    $res = $_.Exception.Response
}

$int = [int]$res.StatusCode
$status = $res.StatusCode
return "$int $status"

How to cast an object in Objective-C

Sure, the syntax is exactly the same as C - NewObj* pNew = (NewObj*)oldObj;

In this situation you may wish to consider supplying this list as a parameter to the constructor, something like:

// SelectionListViewController
-(id) initWith:(SomeListClass*)anItemList
{
  self = [super init];

  if ( self ) {
    [self setList: anItemList];
  }

  return self;
}

Then use it like this:

myEditController = [[SelectionListViewController alloc] initWith: listOfItems];

Python append() vs. + operator on lists, why do these give different results?

append is appending an element to a list. if you want to extend the list with the new list you need to use extend.

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

Proper use of const for defining functions in JavaScript

It has been three years since this question was asked, but I am just now coming across it. Since this answer is so far down the stack, please allow me to repeat it:

Q: I am interested if there are any limits to what types of values can be set using const in JavaScript—in particular functions. Is this valid? Granted it does work, but is it considered bad practice for any reason?

I was motivated to do some research after observing one prolific JavaScript coder who always uses const statement for functions, even when there is no apparent reason/benefit.

In answer to "is it considered bad practice for any reason?" let me say, IMO, yes it is, or at least, there are advantages to using function statement.

It seems to me that this is largely a matter of preference and style. There are some good arguments presented above, but none so clear as is done in this article:

Constant confusion: why I still use JavaScript function statements by medium.freecodecamp.org/Bill Sourour, JavaScript guru, consultant, and teacher.

I urge everyone to read that article, even if you have already made a decision.

Here's are the main points:

Function statements have two clear advantages over [const] function expressions:

Advantage #1: Clarity of intent

When scanning through thousands of lines of code a day, it’s useful to be able to figure out the programmer’s intent as quickly and easily as possible.

Advantage #2: Order of declaration == order of execution

Ideally, I want to declare my code more or less in the order that I expect it will get executed.

This is the showstopper for me: any value declared using the const keyword is inaccessible until execution reaches it.

What I’ve just described above forces us to write code that looks upside down. We have to start with the lowest level function and work our way up.

My brain doesn’t work that way. I want the context before the details.

Most code is written by humans. So it makes sense that most people’s order of understanding roughly follows most code’s order of execution.

Is there a way to get a list of all current temporary tables in SQL Server?

If you need to 'see' the list of temporary tables, you could simply log the names used. (and as others have noted, it is possible to directly query this information)

If you need to 'see' the content of temporary tables, you will need to create real tables with a (unique) temporary name.

You can trace the SQL being executed using SQL Profiler:

[These articles target SQL Server versions later than 2000, but much of the advice is the same.]

If you have a lengthy process that is important to your business, it's a good idea to log various steps (step name/number, start and end time) in the process. That way you have a baseline to compare against when things don't perform well, and you can pinpoint which step(s) are causing the problem more quickly.

SQL Server SELECT INTO @variable?

You cannot SELECT .. INTO .. a TABLE VARIABLE. The best you can do is create it first, then insert into it. Your 2nd snippet has to be

DECLARE @TempCustomer TABLE
(
   CustomerId uniqueidentifier,
   FirstName nvarchar(100),
   LastName nvarchar(100),
   Email nvarchar(100)
);
INSERT INTO 
    @TempCustomer 
SELECT 
    CustomerId, 
    FirstName, 
    LastName, 
    Email 
FROM 
    Customer
WHERE 
    CustomerId = @CustomerId

SQL Query - Using Order By in UNION

I think this does a good job of explaining.

The following is a UNION query that uses an ORDER BY clause:

select supplier_id, supplier_name
from suppliers
where supplier_id > 2000
UNION
select company_id, company_name
from companies
where company_id > 1000
ORDER BY 2;

Since the column names are different between the two "select" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set.

In this example, we've sorted the results by supplier_name / company_name in ascending order, as denoted by the "ORDER BY 2".

The supplier_name / company_name fields are in position #2 in the result set.

Taken from here: http://www.techonthenet.com/sql/union.php

JavaScript for detecting browser language preference

There is no decent way to get that setting, at least not something browser independent.

But the server has that info, because it is part of the HTTP request header (the Accept-Language field, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)

So the only reliable way is to get an answer back from the server. You will need something that runs on the server (like .asp, .jsp, .php, CGI) and that "thing" can return that info. Good examples here: http://www.developershome.com/wap/detection/detection.asp?page=readHeader

Change default text in input type="file"?

Using Bootstrap you can do this thing like below code.

<!DOCTYPE html>
<html lang="en">
<head>
<style>

.btn-file {
  position: relative;
  overflow: hidden;
}
.btn-file input[type=file] {
    position: absolute;
    top: 0;
    right: 0;
    min-width: 100%;
    min-height: 100%;
    font-size: 100px;
    text-align: right;
    filter: alpha(opacity=0);
    opacity: 0;
    outline: none;
    background: white;
    cursor: inherit;
    display: block;
}
</style>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
  <span class="btn btn-file">Upload image from here<input type="file">
</body>
</html>

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

@Martin Devillers solution works fine. For completeness, providing the steps below:

  1. Put your wsdl to resource directory like : src/main/resource
  2. In pom file, add both wsdlDirectory and wsdlLocation(don't miss / at the beginning of wsdlLocation), like below. While wsdlDirectory is used to generate code and wsdlLocation is used at runtime to create dynamic proxy.

    <wsdlDirectory>src/main/resources/mydir</wsdlDirectory>
    <wsdlLocation>/mydir/my.wsdl</wsdlLocation>
    
  3. Then in your java code(with no-arg constructor):

    MyPort myPort = new MyPortService().getMyPort();
    
  4. Here is the full code generation part in pom file, with fluent api in generated code.

    <plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>2.5</version>
    
    <dependencies>
        <dependency>
            <groupId>org.jvnet.jaxb2_commons</groupId>
            <artifactId>jaxb2-fluent-api</artifactId>
            <version>3.0</version>
        </dependency>
        <dependency>
            <groupId>com.sun.xml.ws</groupId>
            <artifactId>jaxws-tools</artifactId>
            <version>2.3.0</version>
        </dependency>
    </dependencies>
    
    <executions>
        <execution>
            <id>wsdl-to-java-generator</id>
            <goals>
                <goal>wsimport</goal>
            </goals>
            <configuration>
                <xjcArgs>
                    <xjcArg>-Xfluent-api</xjcArg>
                </xjcArgs>
                <keep>true</keep>
                <wsdlDirectory>src/main/resources/package</wsdlDirectory>
                <wsdlLocation>/package/my.wsdl</wsdlLocation>
                <sourceDestDir>${project.build.directory}/generated-sources/annotations/jaxb</sourceDestDir>
                <packageName>full.package.here</packageName>
            </configuration>
        </execution>
    </executions>
    

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I found a possible solution here: http://www.made4dotnet.com/Default.aspx?tabid=141&aid=15

Edit:

If you automate Microsoft Excel with Microsoft Visual Basic .NET, Microsoft Visual C# .NET, or Microsoft Visual C++, you may receive the following errors when calling certain methods because the machine has the locale set to something other than US English (locale ID or LCID 1033):

Exception from HRESULT: 0x800A03EC

and/or

Old format or invalid type library

SOLUTION 1:


To get around this error you can set CurrentCulture to en-US when executing code related to Excel and reset back to your originale by using these 2 functions.

//declare a variable to hold the CurrentCulture
System.Globalization.CultureInfo oldCI;
//get the old CurrenCulture and set the new, en-US
void SetNewCurrentCulture()
{
  oldCI = System.Threading.Thread.CurrentThread.CurrentCulture;
  System.Threading.Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-US");
}
//reset Current Culture back to the originale
void ResetCurrentCulture()
{
  System.Threading.Thread.CurrentThread.CurrentCulture = oldCI;
}

SOLUTION 2:


Another solution that could work, create a 1033 directory under Microsoft Office\Office11 (or your corresponding office-version), copy excel.exe to the 1033 directory, and rename it to xllex.dll.

Although you might solve the problem using one off these solutions, when you call the Excel object model in locales other than US English, the Excel object model can act differently and your code can fail in ways you may not have thought of. For example, you might have code that sets the value of a range to a date:

yourRange.Value2 = "10/10/09"

Depending on the locale this code can act differently resulting in Excel putting into the range any of the following values:

October 10, 2009 September 10, 2009 October 9, 2010

How to group by week in MySQL?

You can use both YEAR(timestamp) and WEEK(timestamp), and use both of the these expressions in the SELECT and the GROUP BY clause.

Not overly elegant, but functional...

And of course you can combine these two date parts in a single expression as well, i.e. something like

SELECT CONCAT(YEAR(timestamp), '/', WEEK(timestamp)), etc...
FROM ...
WHERE ..
GROUP BY CONCAT(YEAR(timestamp), '/', WEEK(timestamp))

Edit: As Martin points out you can also use the YEARWEEK(mysqldatefield) function, although its output is not as eye friendly as the longer formula above.


Edit 2 [3 1/2 years later!]:
YEARWEEK(mysqldatefield) with the optional second argument (mode) set to either 0 or 2 is probably the best way to aggregate by complete weeks (i.e. including for weeks which straddle over January 1st), if that is what is desired. The YEAR() / WEEK() approach initially proposed in this answer has the effect of splitting the aggregated data for such "straddling" weeks in two: one with the former year, one with the new year.
A clean-cut every year, at the cost of having up to two partial weeks, one at either end, is often desired in accounting etc. and for that the YEAR() / WEEK() approach is better.

How to get records randomly from the oracle database?

SELECT column FROM
( SELECT column, dbms_random.value FROM table ORDER BY 2 )
where rownum <= 20;

Linq Syntax - Selecting multiple columns

As the other answers have indicated, you need to use an anonymous type.

As far as syntax is concerned, I personally far prefer method chaining. The method chaining equivalent would be:-

var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo)
    .Select(x => new { x.EMAIL, x.ID });

AFAIK, the declarative LINQ syntax is converted to a method call chain similar to this when it is compiled.

UPDATE

If you want the entire object, then you just have to omit the call to Select(), i.e.

var employee = _db.EMPLOYEEs
    .Where(x => x.EMAIL == givenInfo || x.USER_NAME == givenInfo);

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

iPhone App Development on Ubuntu

Not officially, no. It's just Objective-C though and the compiler's open source - you could probably get the headers and compile it and somehow get the binary on the device. Another option is compiling on the device. All these options will require jailbreaking though.
A Mac Mini is just $599...

How to embed fonts in HTML?

I asked this a while back. The answer is basically that it doesn't work. :(

What good are SQL Server schemas?

In SQL Server 2000, objects created were linked to that particular user, like if a user, say Sam creates an object, say, Employees, that table would appear like: Sam.Employees. What about if Sam is leaving the compnay or moves to so other business area. As soon you delete the user Sam, what would happen to Sam.Employees table? Probably, you would have to change the ownership first from Sam.Employees to dbo.Employess. Schema provides a solution to overcome this problem. Sam can create all his object within a schemam such as Emp_Schema. Now, if he creates an object Employees within Emp_Schema then the object would be referred to as Emp_Schema.Employees. Even if the user account Sam needs to be deleted, the schema would not be affected.

What is the bower (and npm) version syntax?

If there is no patch number, ~ is equivalent to appending .x to the non-tilde version. If there is a patch number, ~ allows all patch numbers >= the specified one.

~1     := 1.x
~1.2   := 1.2.x
~1.2.3 := (>=1.2.3 <1.3.0)

I don't have enough points to comment on the accepted answer, but some of the tilde information is at odds with the linked semver documentation: "angular": "~1.2" will not match 1.3, 1.4, 1.4.9. Also "angular": "~1" and "angular": "~1.0" are not equivalent. This can be verified with the npm semver calculator.

Break promise chain and call a function based on the step in the chain where it is broken (rejected)

Try ro use this like libs:

https://www.npmjs.com/package/promise-chain-break

    db.getData()
.then(pb((data) => {
    if (!data.someCheck()) {
        tellSomeone();

        // All other '.then' calls will be skiped
        return pb.BREAK;
    }
}))
.then(pb(() => {
}))
.then(pb(() => {
}))
.catch((error) => {
    console.error(error);
});

iFrame src change event detection?

Answer based on JQuery < 3

$('#iframeid').load(function(){
    alert('frame has (re)loaded');
});

As mentioned by subharb, as from JQuery 3.0 this needs to be changed to:

$('#iframe').on('load', function() {
    alert('frame has (re)loaded ');
});

https://jquery.com/upgrade-guide/3.0/#breaking-change-load-unload-and-error-removed

Difference between git pull and git pull --rebase

Sometimes we have an upstream that rebased/rewound a branch we're depending on. This can be a big problem -- causing messy conflicts for us if we're downstream.

The magic is git pull --rebase

A normal git pull is, loosely speaking, something like this (we'll use a remote called origin and a branch called foo in all these examples):

# assume current checked out branch is "foo"
git fetch origin
git merge origin/foo

At first glance, you might think that a git pull --rebase does just this:

git fetch origin
git rebase origin/foo

But that will not help if the upstream rebase involved any "squashing" (meaning that the patch-ids of the commits changed, not just their order).

Which means git pull --rebase has to do a little bit more than that. Here's an explanation of what it does and how.

Let's say your starting point is this:

a---b---c---d---e  (origin/foo) (also your local "foo")

Time passes, and you have made some commits on top of your own "foo":

a---b---c---d---e---p---q---r (foo)

Meanwhile, in a fit of anti-social rage, the upstream maintainer has not only rebased his "foo", he even used a squash or two. His commit chain now looks like this:

a---b+c---d+e---f  (origin/foo)

A git pull at this point would result in chaos. Even a git fetch; git rebase origin/foo would not cut it, because commits "b" and "c" on one side, and commit "b+c" on the other, would conflict. (And similarly with d, e, and d+e).

What git pull --rebase does, in this case, is:

git fetch origin
git rebase --onto origin/foo e foo

This gives you:

 a---b+c---d+e---f---p'---q'---r' (foo)

You may still get conflicts, but they will be genuine conflicts (between p/q/r and a/b+c/d+e/f), and not conflicts caused by b/c conflicting with b+c, etc.

Answer taken from (and slightly modified):
http://gitolite.com/git-pull--rebase

Configure Flask dev server to be visible across the network

Go to your project path on CMD(command Prompt) and execute the following command:-

set FLASK_APP=ABC.py

SET FLASK_ENV=development

flask run -h [yourIP] -p 8080

you will get following o/p on CMD:-

  • Serving Flask app "expirement.py" (lazy loading)
    • Environment: development
    • Debug mode: on
    • Restarting with stat
    • Debugger is active!
    • Debugger PIN: 199-519-700
    • Running on http://[yourIP]:8080/ (Press CTRL+C to quit)

Now you can access your flask app on another machine using http://[yourIP]:8080/ url

Getting Cannot bind argument to parameter 'Path' because it is null error in powershell

$_ is the active object in the current pipeline. You've started a new pipeline with $FOLDLIST | ... so $_ represents the objects in that array that are passed down the pipeline. You should stash the FileInfo object from the first pipeline in a variable and then reference that variable later e.g.:

write-host $NEWN.Length
$file = $_
...
Move-Item $file.Name $DPATH

How to switch to other branch in Source Tree to commit the code?

Hi I'm also relatively new but I can give you basic help.

  1. To switch to another branch use "Checkout". Just click on your branch and then on the button "checkout" at the top.

UPDATE 12.01.2016:

The bold line is the current branch.

You can also just double click a branch to use checkout.


  1. Your first answer I think depends on the repository you use (like github or bitbucket). Maybe the "Show hosted repository"-Button can help you (Left panel, bottom, right button = database with cog)

And here some helpful links:

Easy Git Guide

Git-flow - Git branching model

Tips on branching with sourcetree

Why does background-color have no effect on this DIV?

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

How can prevent a PowerShell window from closing so I can see the error?

You basically have 3 options to prevent the PowerShell Console window from closing, that I describe in more detail on my blog post.

  1. One-time Fix: Run your script from the PowerShell Console, or launch the PowerShell process using the -NoExit switch. e.g. PowerShell -NoExit "C:\SomeFolder\SomeScript.ps1"
  2. Per-script Fix: Add a prompt for input to the end of your script file. e.g. Read-Host -Prompt "Press Enter to exit"
  3. Global Fix: Change your registry key to always leave the PowerShell Console window open after the script finishes running. Here's the 2 registry keys that would need to be changed:

    ? Open With ? Windows PowerShell
    When you right-click a .ps1 file and choose Open With

    Registry Key: HKEY_CLASSES_ROOT\Applications\powershell.exe\shell\open\command

    Default Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "%1"
    

    Desired Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "& \"%1\""
    

    ? Run with PowerShell
    When you right-click a .ps1 file and choose Run with PowerShell (shows up depending on which Windows OS and Updates you have installed).

    Registry Key: HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\0\Command

    Default Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & '%1'"
    

    Desired Value:

    "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoExit "-Command" "if((Get-ExecutionPolicy ) -ne 'AllSigned') { Set-ExecutionPolicy -Scope Process Bypass }; & \"%1\""
    

You can download a .reg file from my blog to modify the registry keys for you if you don't want to do it manually.

It sounds like you likely want to use option #2. You could even wrap your whole script in a try block, and only prompt for input if an error occurred, like so:

try
{
    # Do your script's stuff
}
catch
{
    Write-Error $_.Exception.ToString()
    Read-Host -Prompt "The above error occurred. Press Enter to exit."
}

How to extract extension from filename string in Javascript?

Use the lastIndexOf method to find the last period in the string, and get the part of the string after that:

var ext = fileName.substr(fileName.lastIndexOf('.') + 1);

How to Extract Year from DATE in POSTGRESQL

you can also use just like this in newer version of sql,

select year('2001-02-16 20:38:40') as year,
month('2001-02-16 20:38:40') as month,
day('2001-02-16 20:38:40') as day,
hour('2001-02-16 20:38:40') as hour,
minute('2001-02-16 20:38:40') as minute

How to search for a string inside an array of strings

In-case if someone wants a little dynamic search.

 let searchInArray=(searchQuery, array, objectKey=null)=>{

  return array.filter(d=>{
      let data =objectKey? d[objectKey] : d //Incase If It's Array Of Objects.
       let dataWords= typeof data=="string" && data?.split(" ")?.map(b=>b&&b.toLowerCase().trim()).filter(b=>b)
      let searchWords = typeof searchQuery=="string"&&searchQuery?.split(" ").map(b=>b&&b.toLowerCase().trim()).filter(b=>b)

     let matchingWords = searchWords.filter(word=>dataWords.includes(word))

    return matchingWords.length

})
    
    
}

For an Array of strings:

let arrayOfStr = [
  "Search for words",
  "inside an array",
  "dynamic searching",
  "match rate 90%"
]

searchInArray("dynamic search", arrayOfStr)

//Results: [ "Search for words", "dynamic searching" ]

For an Array of Objects:

let arrayOfObject = [
  {
    "address": "Karachi Pakistan"
  },
  {
    "address": "UK London"
  },
  {
    "address": "Pakistan Lahore"
  }
]

searchInArray("Pakistan", arrayOfObject,"address")

//Results: [ { "address": "Karachi Pakistan" }, { "address": "Pakistan Lahore" } ]

How to start MySQL with --skip-grant-tables?

if this is a windows box, the simplest thing to do is to stop the servers, add skip-grant-tables to the mysql configuration file, and restart the server.

once you've fixed your permission problems, repeat the above but remove the skip-grant-tables option.

if you don't know where your configuration file is, then log in to mysql send SHOW VARIABLES LIKE '%config%' and one of the rows returned will tell you where your configuration file is.

How to convert between bytes and strings in Python 3?

The 'mangler' in the above code sample was doing the equivalent of this:

bytesThing = stringThing.encode(encoding='UTF-8')

There are other ways to write this (notably using bytes(stringThing, encoding='UTF-8'), but the above syntax makes it obvious what is going on, and also what to do to recover the string:

newStringThing = bytesThing.decode(encoding='UTF-8')

When we do this, the original string is recovered.

Note, using str(bytesThing) just transcribes all the gobbledegook without converting it back into Unicode, unless you specifically request UTF-8, viz., str(bytesThing, encoding='UTF-8'). No error is reported if the encoding is not specified.

Why is Thread.Sleep so harmful

The problems with calling Thread.Sleep are explained quite succinctly here:

Thread.Sleep has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.

Thread.Sleep(n) means block the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds. The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds. This means the thread is almost guaranteed to block for more than n milliseconds. The likelihood that your thread will re-awaken exactly after n milliseconds is about as impossible as impossible can be. So, Thread.Sleep is pointless for timing.

Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy. By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch. This makes any waiting thread a huge waste.

The preferred solution: WaitHandles

The most-made-mistake is using Thread.Sleep with a while-construct (demo and answer, nice blog-entry)

EDIT:
I would like to enhance my answer:

We have 2 different use-cases:

  1. We are waiting because we know a specific timespan when we should continue (use Thread.Sleep, System.Threading.Timer or alikes)

  2. We are waiting because some condition changes some time ... keyword(s) is/are some time! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad!

My answer mainly covers use-case 2

ElasticSearch: Unassigned Shards, how to fix?

When dealing with corrupted shards you can set the replication factor to 0 and then set it back to the original value. This should clear up most if not all your corrupted shards and relocate the new replicas in the cluster.

Setting indexes with unassigned replicas to use a replication factor of 0:

curl -XGET http://localhost:9200/_cat/shards |\
  grep UNASSIGNED | grep ' r ' |\
  awk '{print $1}' |\
  xargs -I {} curl -XPUT http://localhost:9200/{}/_settings -H "Content-Type: application/json" \
  -d '{ "index":{ "number_of_replicas": 0}}'

Setting them back to 1:

curl -XGET http://localhost:9200/_cat/shards |\
  awk '{print $1}' |\
  xargs -I {} curl -XPUT http://localhost:9200/{}/_settings -H "Content-Type: application/json" \
  -d '{ "index":{ "number_of_replicas": 1}}'

Note: Do not run this if you have different replication factors for different indexes. This would hardcode the replication factor for all indexes to 1.

How to open the terminal in Atom?

For Windows follow the below steps

(1)go to file>setting and click on install enter image description here

(2) then type "platformio-ide-terminal" in packages and hit install enter image description here (3) after finish install restart atom and press

 ctrl + ~ for opening the terminal `~` is the key below `Esc`

enter image description here

welcome ;-)

What is the exact meaning of Git Bash?

Bash is a Command Line Interface that was created over twenty-seven years ago by Brian Fox as a free software replacement for the Bourne Shell. A shell is a specific kind of Command Line Interface. Bash is "open source" which means that anyone can read the code and suggest changes. Since its beginning, it has been supported by a large community of engineers who have worked to make it an incredible tool. Bash is the default shell for Linux and Mac. For these reasons, Bash is the most used and widely distributed shell.

Windows has a different Command Line Interface, called Command Prompt. While this has many of the same features as Bash, Bash is much more popular. Because of the strength of the open source community and the tools they provide, mastering Bash is a better investment than mastering Command Prompt.

To use Bash on a Windows computer, we need to download and install a program called Git Bash. Git Bash (Is the Bash for windows) allows us to easily access Bash as well as another tool called Git, inside the Windows environment.

How to install a package inside virtualenv?

I had the same issue and the --no-site-packages did not work for me. I discovered on this older mailing list archive that you are able to force an installation in the virtualenv using the -U flag for pip, eg pip -U ipython. You may verify this works using the bash command which ipython while in the virtualenv.

source: https://mail.python.org/pipermail/python-list/2010-March/571663.html

Using PI in python 2.7

Python 2.7.5 (default, May 15 2013, 22:44:16) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import math
>>> math.pi
3.141592653589793

Check out the Python tutorial on modules and how to use them.

As for the second part of your question, Python comes with batteries included, of course:

>>> math.radians(90)
1.5707963267948966
>>> math.radians(180)
3.141592653589793

Flatten nested dictionaries, compressing keys

There are two big considerations that the original poster needs to consider:

  1. Are there keyspace clobbering issues? For example, {'a_b':{'c':1}, 'a':{'b_c':2}} would result in {'a_b_c':???}. The below solution evades the problem by returning an iterable of pairs.
  2. If performance is an issue, does the key-reducer function (which I hereby refer to as 'join') require access to the entire key-path, or can it just do O(1) work at every node in the tree? If you want to be able to say joinedKey = '_'.join(*keys), that will cost you O(N^2) running time. However if you're willing to say nextKey = previousKey+'_'+thisKey, that gets you O(N) time. The solution below lets you do both (since you could merely concatenate all the keys, then postprocess them).

(Performance is not likely an issue, but I'll elaborate on the second point in case anyone else cares: In implementing this, there are numerous dangerous choices. If you do this recursively and yield and re-yield, or anything equivalent which touches nodes more than once (which is quite easy to accidentally do), you are doing potentially O(N^2) work rather than O(N). This is because maybe you are calculating a key a then a_1 then a_1_i..., and then calculating a then a_1 then a_1_ii..., but really you shouldn't have to calculate a_1 again. Even if you aren't recalculating it, re-yielding it (a 'level-by-level' approach) is just as bad. A good example is to think about the performance on {1:{1:{1:{1:...(N times)...{1:SOME_LARGE_DICTIONARY_OF_SIZE_N}...}}}})

Below is a function I wrote flattenDict(d, join=..., lift=...) which can be adapted to many purposes and can do what you want. Sadly it is fairly hard to make a lazy version of this function without incurring the above performance penalties (many python builtins like chain.from_iterable aren't actually efficient, which I only realized after extensive testing of three different versions of this code before settling on this one).

from collections import Mapping
from itertools import chain
from operator import add

_FLAG_FIRST = object()

def flattenDict(d, join=add, lift=lambda x:x):
    results = []
    def visit(subdict, results, partialKey):
        for k,v in subdict.items():
            newKey = lift(k) if partialKey==_FLAG_FIRST else join(partialKey,lift(k))
            if isinstance(v,Mapping):
                visit(v, results, newKey)
            else:
                results.append((newKey,v))
    visit(d, results, _FLAG_FIRST)
    return results

To better understand what's going on, below is a diagram for those unfamiliar with reduce(left), otherwise known as "fold left". Sometimes it is drawn with an initial value in place of k0 (not part of the list, passed into the function). Here, J is our join function. We preprocess each kn with lift(k).

               [k0,k1,...,kN].foldleft(J)
                           /    \
                         ...    kN
                         /
       J(k0,J(k1,J(k2,k3)))
                       /  \
                      /    \
           J(J(k0,k1),k2)   k3
                    /   \
                   /     \
             J(k0,k1)    k2
                 /  \
                /    \
               k0     k1

This is in fact the same as functools.reduce, but where our function does this to all key-paths of the tree.

>>> reduce(lambda a,b:(a,b), range(5))
((((0, 1), 2), 3), 4)

Demonstration (which I'd otherwise put in docstring):

>>> testData = {
        'a':1,
        'b':2,
        'c':{
            'aa':11,
            'bb':22,
            'cc':{
                'aaa':111
            }
        }
    }
from pprint import pprint as pp

>>> pp(dict( flattenDict(testData, lift=lambda x:(x,)) ))
{('a',): 1,
 ('b',): 2,
 ('c', 'aa'): 11,
 ('c', 'bb'): 22,
 ('c', 'cc', 'aaa'): 111}

>>> pp(dict( flattenDict(testData, join=lambda a,b:a+'_'+b) ))
{'a': 1, 'b': 2, 'c_aa': 11, 'c_bb': 22, 'c_cc_aaa': 111}    

>>> pp(dict( (v,k) for k,v in flattenDict(testData, lift=hash, join=lambda a,b:hash((a,b))) ))
{1: 12416037344,
 2: 12544037731,
 11: 5470935132935744593,
 22: 4885734186131977315,
 111: 3461911260025554326}

Performance:

from functools import reduce
def makeEvilDict(n):
    return reduce(lambda acc,x:{x:acc}, [{i:0 for i in range(n)}]+range(n))

import timeit
def time(runnable):
    t0 = timeit.default_timer()
    _ = runnable()
    t1 = timeit.default_timer()
    print('took {:.2f} seconds'.format(t1-t0))

>>> pp(makeEvilDict(8))
{7: {6: {5: {4: {3: {2: {1: {0: {0: 0,
                                 1: 0,
                                 2: 0,
                                 3: 0,
                                 4: 0,
                                 5: 0,
                                 6: 0,
                                 7: 0}}}}}}}}}

import sys
sys.setrecursionlimit(1000000)

forget = lambda a,b:''

>>> time(lambda: dict(flattenDict(makeEvilDict(10000), join=forget)) )
took 0.10 seconds
>>> time(lambda: dict(flattenDict(makeEvilDict(100000), join=forget)) )
[1]    12569 segmentation fault  python

... sigh, don't think that one is my fault...


[unimportant historical note due to moderation issues]

Regarding the alleged duplicate of Flatten a dictionary of dictionaries (2 levels deep) of lists in Python:

That question's solution can be implemented in terms of this one by doing sorted( sum(flatten(...),[]) ). The reverse is not possible: while it is true that the values of flatten(...) can be recovered from the alleged duplicate by mapping a higher-order accumulator, one cannot recover the keys. (edit: Also it turns out that the alleged duplicate owner's question is completely different, in that it only deals with dictionaries exactly 2-level deep, though one of the answers on that page gives a general solution.)

Vertical rulers in Visual Studio Code

In addition to global "editor.rulers" setting, it's also possible to set this on a per-language level.

For example, style guides for Python projects often specify either 79 or 120 characters vs. Git commit messages should be no longer than 50 characters.

So in your settings.json, you'd put:

"[git-commit]": {"editor.rulers": [50]},
"[python]": {
    "editor.rulers": [
        79,
        120
    ]
}

High-precision clock in Python

Here is a python 3 solution for Windows building upon the answer posted above by CyberSnoopy (using GetSystemTimePreciseAsFileTime). We borrow some code from jfs

Python datetime.utcnow() returning incorrect datetime

and get a precise timestamp (Unix time) in microseconds

#! python3
import ctypes.wintypes

def utcnow_microseconds():
    system_time = ctypes.wintypes.FILETIME()
    #system call used by time.time()
    #ctypes.windll.kernel32.GetSystemTimeAsFileTime(ctypes.byref(system_time))
    #getting high precision:
    ctypes.windll.kernel32.GetSystemTimePreciseAsFileTime(ctypes.byref(system_time))
    large = (system_time.dwHighDateTime << 32) + system_time.dwLowDateTime
    return large // 10 - 11644473600000000

for ii in range(5):
    print(utcnow_microseconds()*1e-6)

References
https://docs.microsoft.com/en-us/windows/win32/sysinfo/time-functions
https://docs.microsoft.com/en-us/windows/win32/api/sysinfoapi/nf-sysinfoapi-getsystemtimepreciseasfiletime
https://support.microsoft.com/en-us/help/167296/how-to-convert-a-unix-time-t-to-a-win32-filetime-or-systemtime

ruby 1.9: invalid byte sequence in UTF-8

This seems to work:

def sanitize_utf8(string)
  return nil if string.nil?
  return string if string.valid_encoding?
  string.chars.select { |c| c.valid_encoding? }.join
end

C# event with custom arguments

public enum MyEvents
{
    Event1
}

public class CustomEventArgs : EventArgs
{
    public MyEvents MyEvents { get; set; }
}


private EventHandler<CustomEventArgs> onTrigger;

public event EventHandler<CustomEventArgs> Trigger
{
    add
    {
        onTrigger += value;
    }
    remove
    {
        onTrigger -= value;
    }
}

protected void OnTrigger(CustomEventArgs e)
{
    if (onTrigger != null)
    {
        onTrigger(this, e);
    }
}

server error:405 - HTTP verb used to access this page is not allowed

In the Facebook app control panel make sure you have a forward slash on the end of any specified URL if you are only specifying a folder name

i.e.

Page Tab URL: http://mypagetabserver.com/custom_tab/

Delete all duplicate rows Excel vba

The duplicate values in any column can be deleted with a simple for loop.

Sub remove()
Dim a As Long
For a = Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1
If WorksheetFunction.CountIf(Range("A1:A" & a), Cells(a, 1)) > 1 Then Rows(a).Delete
Next
End Sub

AngularJS open modal on button click

Set Jquery in scope

$scope.$ = $;

and call in html

ng-click="$('#novoModelo').modal('show')"

How to add rows dynamically into table layout

Here's technique I figured out after a bit of trial and error that allows you to preserve your XML styles and avoid the issues of using a <merge/> (i.e. inflate() requires a merge to attach to root, and returns the root node). No runtime new TableRow()s or new TextView()s required.

Code

Note: Here CheckBalanceActivity is some sample Activity class

TableLayout table = (TableLayout)CheckBalanceActivity.this.findViewById(R.id.attrib_table);
for(ResourceBalance b : xmlDoc.balance_info)
{
    // Inflate your row "template" and fill out the fields.
    TableRow row = (TableRow)LayoutInflater.from(CheckBalanceActivity.this).inflate(R.layout.attrib_row, null);
    ((TextView)row.findViewById(R.id.attrib_name)).setText(b.NAME);
    ((TextView)row.findViewById(R.id.attrib_value)).setText(b.VALUE);
    table.addView(row);
}
table.requestLayout();     // Not sure if this is needed.

attrib_row.xml

<?xml version="1.0" encoding="utf-8"?>
<TableRow style="@style/PlanAttribute"  xmlns:android="http://schemas.android.com/apk/res/android">
    <TextView
        style="@style/PlanAttributeText"
        android:id="@+id/attrib_name"
        android:textStyle="bold"/>
    <TextView
        style="@style/PlanAttributeText"
        android:id="@+id/attrib_value"
        android:gravity="right"
        android:textStyle="normal"/>
</TableRow>

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

How to return a file (FileContentResult) in ASP.NET WebAPI

For me it was the difference between

var response = Request.CreateResponse(HttpStatusCode.OK, new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");

and

var response = Request.CreateResponse(HttpStatusCode.OK);
response.Content = new StringContent(log, System.Text.Encoding.UTF8, "application/octet-stream");

The first one was returning the JSON representation of StringContent: {"Headers":[{"Key":"Content-Type","Value":["application/octet-stream; charset=utf-8"]}]}

While the second one was returning the file proper.

It seems that Request.CreateResponse has an overload that takes a string as the second parameter and this seems to have been what was causing the StringContent object itself to be rendered as a string, instead of the actual content.

How to add a footer in ListView?

In this Question, best answer not work for me. After that i found this method to show listview footer,

LayoutInflater inflater = getLayoutInflater();
ViewGroup footerView = (ViewGroup)inflater.inflate(R.layout.footer_layout,listView,false);
listView.addFooterView(footerView, null, false);

And create new layout call footer_layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Done"
        android:textStyle="italic"
        android:background="#d6cf55"
        android:padding="10dp"/>
</LinearLayout>

If not work refer this article hear

How to insert a character in a string at a certain position?

I think a simpler and more elegant solution to insert a String in a certain position would be this one-liner:

target.replaceAll("^(.{" + position + "})", "$1" + insert);

For example, to insert a missing : into a time String:

"-0300".replaceAll("^(.{3})", "$1:");

What it does is, matches position characters from the beginning of the string, groups that, and replaces the group with itself ($1) followed by the insert string. Mind the replaceAll, even though there's always one occurrence, because the first parameter must be a regex.

Of course it does not have the same performance as the StringBuilder solution, but I believe the succinctness and elegance as a simple and easier to read one-liner (compared to a huge method) is sufficient for making it the preferred solution in most non performance-critical use-cases.

Note I'm solving the generic problem in the title for documentation reasons, of course if you are dealing with decimal numbers you should use the domain-specific solutions already proposed.

IOS: verify if a point is inside a rect

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
            UITouch *touch = [[event allTouches] anyObject];
            CGPoint touchLocation = [touch locationInView:self.view];
            CGRect rect1 = CGRectMake(vwTable.frame.origin.x, 
            vwTable.frame.origin.y, vwTable.frame.size.width, 
            vwTable.frame.size.height);
            if (CGRectContainsPoint(rect1,touchLocation))
            NSLog(@"Inside");
            else
            NSLog(@"Outside");
    }

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

.apply() takes in a function as the first parameter; pass in the label_race function as so:

df['race_label'] = df.apply(label_race, axis=1)

You don't need to make a lambda function to pass in a function.

The proxy server received an invalid response from an upstream server

This is not mentioned in you post but I suspect you are initiating an SSL connection from the browser to Apache, where VirtualHosts are configured, and Apache does a revese proxy to your Tomcat.

There is a serious bug in (some versions ?) of IE that sends the 'wrong' host information in an SSL connection (see EDIT below) and confuses the Apache VirtualHosts. In short the server name presented is the one of the reverse DNS resolution of the IP, not the one in the URL.

The workaround is to have one IP address per SSL virtual hosts/server name. Is short, you must end up with something like

1 server name == 1 IP address == 1 certificate == 1 Apache Virtual Host

EDIT

Though the conclusion is correct, the identification of the problem is better described here http://en.wikipedia.org/wiki/Server_Name_Indication

Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

With Bootstrap 4+, you can simply add the class custom-select for your select inputs to drop the browser-specific styling and keep the arrow icons.

Documentation Here: Bootstrap 4 Custom Forms Select Menu

Best practices for copying files with Maven

If someone wants total control over the path of the source and destination paths, then using maven-antrun-plugin's copy task is the best option. This approach will allow you to copy between any paths on the system, irrespective of the concerned paths being within the mvn project or not. I had a situation where I had to do some unusual stuff like copy generated source files from target directory back to the src directory for further processing. In my situation, this was the only option that worked without fuss. Sample code snippet from pom.xml:

<plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <version>1.8</version>
        <executions>
            <execution>
                <phase>process-resources</phase>
                <configuration>
                <tasks>
                    <copy file="${basedir}/target/myome/minifyJsSrcDir/myome.min.js" todir="${basedir}/src/main/webapp/app/minifyJsSrcDir"/>
                </tasks>
                </configuration>
                <goals>
                <goal>run</goal>
                </goals>
            </execution>
        </executions>
</plugin>

How to allocate aligned memory only using the standard library?

size =1024;
alignment = 16;
aligned_size = size +(alignment -(size %  alignment));
mem = malloc(aligned_size);
memset_16aligned(mem, 0, 1024);
free(mem);

Hope this one is the simplest implementation, let me know your comments.

Maximum concurrent Socket.IO connections

After making configurations, you can check by writing this command on terminal

sysctl -a | grep file

Swift - How to hide back button in navigation item?

That worked for me in Swift 5 like a charm, just add it to your viewDidLoad()

self.navigationItem.setHidesBackButton(true, animated: true)

In reactJS, how to copy text to clipboard?

Best solution with react hooks, no need of external libraries for that

_x000D_
_x000D_
import React, { useState } from 'react';_x000D_
_x000D_
const MyComponent = () => {_x000D_
const [copySuccess, setCopySuccess] = useState('');_x000D_
_x000D_
// your function to copy here_x000D_
_x000D_
  const copyToClipBoard = async copyMe => {_x000D_
    try {_x000D_
      await navigator.clipboard.writeText(copyMe);_x000D_
      setCopySuccess('Copied!');_x000D_
    } catch (err) {_x000D_
      setCopySuccess('Failed to copy!');_x000D_
    }_x000D_
  };_x000D_
_x000D_
return (_x000D_
 <div>_x000D_
    <Button onClick={() => copyToClipBoard('some text to copy')}>_x000D_
     Click here to copy_x000D_
     </Button>_x000D_
  // after copying see the message here_x000D_
  {copySuccess}_x000D_
 </div>_x000D_
)_x000D_
}
_x000D_
_x000D_
_x000D_

check here for further documentation about navigator.clip board , navigator.clipboard documentation navigotor.clipboard is supported by a huge number of browser look here supported browser

C# Double - ToString() formatting with two decimal places but no rounding

How about adding one extra decimal that is to be rounded and then discarded:

var d = 0.241534545765;
var result1 = d.ToString("0.###%");

var result2 = result1.Remove(result1.Length - 1);

Get current URL from IFRAME

If you're inside an iframe that don't have cross domain src, or src is empty:

Then:

function getOriginUrl() {
    var href = document.location.href;
    var referrer = document.referrer;
    // Check if window.frameElement not null
    if(window.frameElement) {
        href = window.frameElement.ownerDocument.location.href;
        // This one will be origin
        if(window.frameElement.ownerDocument.referrer != "") {
            referrer = window.frameElement.ownerDocument.referrer;
        }
    }
    // Compare if href not equal to referrer
    if(href != referrer) {
        // Take referrer as origin
        return referrer;
    } else {
        // Take href
        return href
    }
}

If you're inside an iframe with cross domain src:

Then:

function getOriginUrl() {
    var href = document.location.href;
    var referrer = document.referrer;
    // Detect if you're inside an iframe
    if(window.parent != window) {
        // Take referrer as origin
        return referrer;
    } else {
        // Take href
        return href;
    }
}

Undefined reference to pthread_create in Linux

Sometimes, if you use multiple library, check the library dependency. (e.g. -lpthread -lSDL... <==> ... -lSDL -lpthread)

How to read values from properties file?

You need to put a PropertyPlaceholderConfigurer bean in your application context and set its location property.

See details here : http://www.zparacha.com/how-to-read-properties-file-in-spring/

You might have to modify your property file a bit for this thing to work.

Hope it helps.

What's the difference between REST & RESTful

REST stands for representational state transfer. That means that state itself is not transferred but a mere representation of it is. The most common example is a pure HTML server based app (no javascript). The browser knows nothing about the application itself but through links and resources, the server is able transfer the state of the application to the browser. Where a button would normally change a state variable (e.g. page open) in a regular windows application, in the browser you have a link that represents such a state change.

The idea is to use hypermedia. And perhaps to create new hypermedia types. Potentially we can expand the browser with javascript/AJAX and create new custom hypermedia types. And we would have a true REST application.

This is my short version of what REST stands for, the problem is that it is hard to implement. I personally say RESTful, when I want to make reference to the REST principles but I know I am not really implementing the whole concept of REST. We don't really say SOAPful, because you either use SOAP or not. I think most people don't do REST the way it was envisioned by it's creator Roy Fielding, we actually implement RESTful or RESTlike architectures. You can see his dissertation, and you will find the REST acronym but not the word RESTful.

How do I remove a property from a JavaScript object?

To clone object without property:

For example:

let object = { a: 1, b: 2, c: 3 };   

And we need to delete a.

  1. With explicit prop key:
    const { a, ...rest } = object;
    object = rest;
  1. With variable prop key:
    const propKey = 'a';
    const { [propKey]: propValue, ...rest } = object;
    object = rest;
  1. Cool arrow function :
    const removeProperty = (propKey, { [propKey]: propValue, ...rest }) => rest;

    object = removeProperty('a', object);
  1. For multiple properties
    const removeProperties = (object, ...keys) => Object.entries(object).reduce((prev, [key, value]) => ({...prev, ...(!keys.includes(key) && { [key]: value }) }), {})

Usage

object = removeProperties(object, 'a', 'b') // result => { c: 3 }

Or

    const propsToRemove = ['a', 'b']
    object = removeProperties(object, ...propsToRemove) // result => { c: 3 }

How do I disable Git Credential Manager for Windows?

If you notice the credential manager UI popping up when you use a JetBrains IDE (such as IntelliJ IDEA, PhpStorm, WebStorm, PyCharm, Rider, RubyMine, Android Studio, or Goland), do this:

  1. In your IDE, go to File | Settings | Version Control | Git.

  2. Disable Use credential helper: Disable "Use credential helper"

  3. Don't forget to press Save.

How to get the last character of a string in a shell?

I know this is a very old thread, but no one mentioned which to me is the cleanest answer:

echo -n $str | tail -c 1

Note the -n is just so the echo doesn't include a newline at the end.

__init__() missing 1 required positional argument

Your constructor is expecting one parameter (data). You're not passing it in the call. I guess you wanted to initialise a field in the object. That would look like this:

class DHT:
    def __init__(self):
        self.data = {}
        self.data['one'] = '1'
        self.data['two'] = '2'
        self.data['three'] = '3'
    def showData(self):
        print(self.data)

if __name__ == '__main__':
    DHT().showData()

Or even just:

class DHT:
    def __init__(self):
        self.data = {'one': '1', 'two': '2', 'three': '3'}
    def showData(self):
        print(self.data)

Passing data to a jQuery UI Dialog

I have now tried your suggestions and found that it kinda works,

  1. The dialog div is alsways written out in plaintext
  2. With the $.post version it actually works in terms that the controller gets called and actually cancels the booking, but the dialog stays open and page doesn't refresh. With the get version window.location = h.ref works great.

Se my "new" script below:

$('a.cancel').click(function() {
        var a = this;               
        $("#dialog").dialog({
            autoOpen: false,
            buttons: {
                "Ja": function() {
                    $.post(a.href);                     
                },
                "Nej": function() { $(this).dialog("close"); }
            },
            modal: true,
            overlay: {
                opacity: 0.5,

            background: "black"
        }
    });
    $("#dialog").dialog('open');
    return false;
});

});

Any clues?

oh and my Action link now looks like this:

<%= Html.ActionLink("Cancel", "Cancel", new { id = v.BookingId }, new  { @class = "cancel" })%>

How to check if an alert exists using WebDriver?

I would suggest to use ExpectedConditions and alertIsPresent(). ExpectedConditions is a wrapper class that implements useful conditions defined in ExpectedCondition interface.

public boolean isAlertPresent(){
    boolean foundAlert = false;
    WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
    try {
        wait.until(ExpectedConditions.alertIsPresent());
        foundAlert = true;
    } catch (TimeoutException eTO) {
        foundAlert = false;
    }
    return foundAlert;
}

Note: this is based on the answer by nilesh, but adapted to catch the TimeoutException which is thrown by the wait.until() method.

Leave menu bar fixed on top when scrolled

Or do this in more dynamic way

$(window).bind('scroll', function () {
    var menu = $('.menu');
    if ($(window).scrollTop() > menu.offset().top) {
        menu.addClass('fixed');
    } else {
        menu.removeClass('fixed');
    }
});

In CSS add class

.fixed {
    position: fixed;
    top: 0;
}

Verilog: How to instantiate a module

Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.

An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto and can afterwards be manually edited.

subcomponent subcomponent_instance_name(/*AUTOINST*/);

Expanded

subcomponent subcomponent_instance_name (/*AUTOINST*/
  //Inputs
  .clk,         (clk)           
  .rst_n,       (rst_n)
  .data_rx      (data_rx_1[9:0]),
  //Outputs
  .data_tx      (data_tx[9:0])
);

Implicit wires can be automated with /*AUTOWIRE*/. Check the link for further information.

How do I return JSON without using a template in Django?

from django.utils import simplejson 
from django.core import serializers 

def pagina_json(request): 
   misdatos = misdatos.objects.all()
   data = serializers.serialize('json', misdatos) 
   return HttpResponse(data, mimetype='application/json')

Split page vertically using CSS

you can use..

<div style="width: 100%;">
   <div style="float:left; width: 80%">
   </div>
   <div style="float:right;">
   </div>
</div>
<div style="clear:both"></div>

now element below this will not be affected.

Can I stretch text using CSS?

I'll answer for horizontal stretching of text, since the vertical is the easy part - just use "transform: scaleY()"

_x000D_
_x000D_
.stretched-text {
  letter-spacing: 2px;
  display: inline-block;
  font-size: 32px;
  transform: scaleY(0.5);
  transform-origin: 0 0;
  margin-bottom: -50%;
}
span {
  font-size: 16px;
  vertical-align: top;
}
_x000D_
<span class="stretched-text">this is some stretched text</span>
<span>and this is some random<br />triple line <br />not stretched text</span>
_x000D_
_x000D_
_x000D_

letter-spacing just adds space between letters, stretches nothing, but it's kinda relative

inline-block because inline elements are too restrictive and the code below wouldn't work otherwise

Now the combination that makes the difference

font-size to get to the size we want - that way the text will really be of the length it's supposed to be and the text before and after it will appear next to it (scaleX is just for show, the browser still sees the element at its original size when positioning other elements).

scaleY to reduce the height of the text, so that it's the same as the text beside it.

transform-origin to make the text scale from the top of the line.

margin-bottom set to a negative value, so that the next line will not be far below - preferably percentage, so that we won't change the line-height property. vertical-align set to top, to prevent the text before or after from floating to other heights (since the stretched text has a real size of 32px)

-- The simple span element has a font-size, only as a reference.

The question asked for a way to prevent the boldness of the text caused by the stretch and I still haven't given one, BUT the font-weight property has more values than just normal and bold.

I know, you just can't see that, but if you search for the appropriate fonts, you can use the more values.

Android ListView selected item stay highlighted

From Avinash Kumar Pankaj's example

View v;

then at oncreate method

v = new View(getActivity());

and then onlistitemclick method i wrote

public void onListItemClick(ListView listView, View view, int position,
       long id) {
   v.setBackgroundResource(0);
   view.setBackgroundResource(R.color.green);
   v = view;
}

It worked for me. Thank you.

I replaced

v = new View(getActivity());

to

v = new View(this);

and the code worked well.

It is necessary the xml files 'colors' and 'bg_key' from previous examples too, as well as ListView attribute android:background="@drawable/bg_key"

Mauro

DNS problem, nslookup works, ping doesn't

I think the problem can be because of the NAT. Normally the DNS clients make requests via UDP. But when the DNS server is behind the NAT the UDP requests will not work.

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

Open your file with Notepad++, select "Encoding" or "Encodage" menu to identify or to convert from ANSI to UTF-8 or the ISO 8859-1 code page.

Python sum() function with list parameter

Have you used the variable sum anywhere else? That would explain it.

>>> sum = 1
>>> numbers = [1, 2, 3]
>>> numsum = (sum(numbers))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

The name sum doesn't point to the function anymore now, it points to an integer.

Solution: Don't call your variable sum, call it total or something similar.

How to get a cookie from an AJAX response?

You're looking for a response header of Set-Cookie:

xhr.getResponseHeader('Set-Cookie');

It won't work with HTTPOnly cookies though.

Update

According to the XMLHttpRequest Level 1 and XMLHttpRequest Level 2, this particular response headers falls under the "forbidden" response headers that you can obtain using getResponseHeader(), so the only reason why this could work is basically a "naughty" browser.

Delete newline in Vim

Certainly. Vim recognizes the \n character as a newline, so you can just search and replace. In command mode type:

:%s/\n/

Batch Renaming of Files in a Directory

as to me in my directory I have multiple subdir, each subdir has lots of images I want to change all the subdir images to 1.jpg ~ n.jpg

def batch_rename():
    base_dir = 'F:/ad_samples/test_samples/'
    sub_dir_list = glob.glob(base_dir + '*')
    # print sub_dir_list # like that ['F:/dir1', 'F:/dir2']
    for dir_item in sub_dir_list:
        files = glob.glob(dir_item + '/*.jpg')
        i = 0
        for f in files:
            os.rename(f, os.path.join(dir_item, str(i) + '.jpg'))
            i += 1

(mys own answer)https://stackoverflow.com/a/45734381/6329006

Concat strings by & and + in VB.Net

  • & is only used for string concatenation.
  • + is overloaded to do both string concatenation and arithmetic addition.

The double purpose of + leads to confusion, exactly like that in your question. Especially when Option Strict is Off, because the compiler will add implicit casts on your strings and integers to try to make sense of your code.

My recommendations

  • You should definitely turn Option Strict On, then the compiler will force you to add explicit casts where it thinks they are necessary.
  • You should avoid using + for concatenation because of the ambiguity with arithmetic addition.

Both these recommendations are also in the Microsoft Press book Practical Guidelines And Best Practises for VB and C# (sections 1.16, 21.2)

Shell script to get the process ID on Linux

You can use the command killall:

$ killall ruby

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

How can I change the Y-axis figures into percentages in a barplot?

In principle, you can pass any reformatting function to the labels parameter:

+ scale_y_continuous(labels = function(x) paste0(x*100, "%")) # Multiply by 100 & add %  

Or

+ scale_y_continuous(labels = function(x) paste0(x, "%")) # Add percent sign 

Reproducible example:

library(ggplot2)
df = data.frame(x=seq(0,1,0.1), y=seq(0,1,0.1))

ggplot(df, aes(x,y)) + 
  geom_point() +
  scale_y_continuous(labels = function(x) paste0(x*100, "%"))

The way to check a HDFS directory's size?

Command Should be hadoop fs -du -s -h \dirPath

  • -du [-s] [-h] ... : Show the amount of space, in bytes, used by the files that match the specified file pattern.

  • -s : Rather than showing the size of each individual file that matches the
    pattern, shows the total (summary) size.

  • -h : Formats the sizes of files in a human-readable fashion rather than a number of bytes. (Ex MB/GB/TB etc)

    Note that, even without the -s option, this only shows size summaries one level deep into a directory.

    The output is in the form size name(full path)

Checking host availability by using ping in bash scripts

up=`fping -r 1 $1 `
if [ -z "${up}" ]; then
    printf "Host $1 not responding to ping   \n"
    else
    printf "Host $1 responding to ping  \n"
fi

/lib/ld-linux.so.2: bad ELF interpreter: No such file or directory

looks to me yum install glibc.i686 should have worked. Unless Peter was not root. He has the 64 bit glib installed, he is installing a 32 bit package that requires the 32 bit glib which is glib.i686 for intel processors.

HTML meta tag for content language

Google recommends to use hreflang, read more info

Examples:

<link rel="alternate" href="http://example.com/en-ie" hreflang="en-ie" />
<link rel="alternate" href="http://example.com/en-ca" hreflang="en-ca" />
<link rel="alternate" href="http://example.com/en-au" hreflang="en-au" />
<link rel="alternate" href="http://example.com/en" hreflang="en" />

C# Version Of SQL LIKE

I think you can use "a string.Contains("str") for this.

it will search in a string to a patern, and result true is founded and false if not.

Detect Safari browser

I create a function that return boolean type:

export const isSafari = () => navigator.userAgent.toLowerCase().indexOf('safari') !== -1

How do I set the request timeout for one controller action in an asp.net mvc application

<location path="ControllerName/ActionName">
    <system.web>
        <httpRuntime executionTimeout="1000"/>
    </system.web>
</location>

Probably it is better to set such values in web.config instead of controller. Hardcoding of configurable options is considered harmful.

How to pass data from Javascript to PHP and vice versa?

I'd use JSON as the format and Ajax (really XMLHttpRequest) as the client->server mechanism.

Hiding a button in Javascript

when you press the button so it should call function that will alert message. so after alert put style visible property . you can achieve it using

_x000D_
_x000D_
function OpenAlert(){_x000D_
        alert("Getting the message");_x000D_
        document.getElementById("getMessage").style.visibility="hidden";_x000D_
        _x000D_
    }
_x000D_
 <input type="button" id="getMessage" name="GetMessage" value="GetMessage" onclick="OpenAlert()"/>
_x000D_
_x000D_
_x000D_

Hope this will help . Happy to help

Angular redirect to login page

1. Create a guard as seen below. 2. Install ngx-cookie-service to get cookies returned by external SSO. 3. Create ssoPath in environment.ts (SSO Login redirection). 4. Get the state.url and use encodeURIComponent.

import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from 
  '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { environment } from '../../../environments/environment.prod';

@Injectable()
export class AuthGuardService implements CanActivate {
  private returnUrl: string;
  constructor(private _router: Router, private cookie: CookieService) {}

canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    if (this.cookie.get('MasterSignOn')) {
      return true;
    } else {
      let uri = window.location.origin + '/#' + state.url;
      this.returnUrl = encodeURIComponent(uri);      
      window.location.href = environment.ssoPath +  this.returnUrl ;   
      return false;      
    }
  }
}

How to insert a new line in Linux shell script?

The simplest way to insert a new line between echo statements is to insert an echo without arguments, for example:

echo Create the snapshots
echo
echo Snapshot created

That is, echo without any arguments will print a blank line.

Another alternative to use a single echo statement with the -e flag and embedded newline characters \n:

echo -e "Create the snapshots\n\nSnapshot created"

However, this is not portable, as the -e flag doesn't work consistently in all systems. A better way if you really want to do this is using printf:

printf "Create the snapshots\n\nSnapshot created\n"

This works more reliably in many systems, though it's not POSIX compliant. Notice that you must manually add a \n at the end, as printf doesn't append a newline automatically as echo does.

How to get the parents of a Python class?

If you want all the ancestors rather than just the immediate ones, use inspect.getmro:

import inspect
print inspect.getmro(cls)

Usefully, this gives you all ancestor classes in the "method resolution order" -- i.e. the order in which the ancestors will be checked when resolving a method (or, actually, any other attribute -- methods and other attributes live in the same namespace in Python, after all;-).

Sort an ArrayList based on an object field

Use a custom comparator:

Collections.sort(nodeList, new Comparator<DataNode>(){
     public int compare(DataNode o1, DataNode o2){
         if(o1.degree == o2.degree)
             return 0;
         return o1.degree < o2.degree ? -1 : 1;
     }
});

null terminating a string

To your first question: I would go with Paul R's comment and terminate with '\0'. But the value 0 itself works also fine. A matter of taste. But don't use the MACRO NULLwhich is meant for pointers.

To your second question: If your string is not terminated with\0, it might still print the expected output because following your string is a non-printable character in your memory. This is a really nasty bug though, since it might blow up when you might not expect it. Always terminate a string with '\0'.

Get fragment (value after hash '#') from a URL in php

If you want to get the value after the hash mark or anchor as shown in a user's browser: This isn't possible with "standard" HTTP as this value is never sent to the server (hence it won't be available in $_SERVER["REQUEST_URI"] or similar predefined variables). You would need some sort of JavaScript magic on the client side, e.g. to include this value as a POST parameter.

If it's only about parsing a known URL from whatever source, the answer by mck89 is perfectly fine though.

TypeError: 'float' object is not subscriptable

You are not selecting multiple indexes with PriceList[0][1][2][3][4][5][6] , instead each [] is going into a sub index.

Try this

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      
PriceList[0:7]=[PizzaChange]*7  
PriceList[7:11]=[PizzaChange+3]*4

How to submit an HTML form without redirection

If you control the back end, then use something like response.redirect instead of response.send.

You can create custom HTML pages for this or just redirect to something you already have.

In Express.js:

const handler = (req, res) => {
  const { body } = req
  handleResponse(body)
  .then(data => {
    console.log(data)
    res.redirect('https://yoursite.com/ok.html')
  })
  .catch(err => {
    console.log(err)
    res.redirect('https://yoursite.com/err.html')
  })
}
...
app.post('/endpoint', handler)

Using Server.MapPath() inside a static field in ASP.NET MVC

I think you can try this for calling in from a class

 System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/");

*----------------Sorry I oversight, for static function already answered the question by adrift*

System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Update

I got exception while using System.Web.Hosting.HostingEnvironment.MapPath("~/SignatureImages/");

Ex details : System.ArgumentException: The relative virtual path 'SignatureImages' is not allowed here. at System.Web.VirtualPath.FailIfRelativePath()

Solution (tested in static webmethod)

System.Web.HttpContext.Current.Server.MapPath("~/SignatureImages/"); Worked

Use multiple @font-face rules in CSS

Multiple variations of a font family can be declared by changing the font-weight and src property of @font-face rule.

/* Regular Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Regular.ttf");
}

/* SemiBold (600) Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-SemiBold.ttf");
    font-weight: 600;
}

/* Bold Weight */
@font-face {
    font-family: Montserrat;
    src: url("../fonts/Montserrat-Bold.ttf");
    font-weight: bold;
}

Declared rules can be used by following

/* Regular */
font-family: Montserrat;


/* Semi Bold */
font-family: Montserrat;
font-weght: 600;

/* Bold */
font-family: Montserrat;
font-weight: bold;

Images can't contain alpha channels or transparencies

i have same problem just compress your png file on https://tinypng.com/ online and then try to upload that new compressed png file.

its work for me.

Querying a linked sql server

If linked server name is IP address following code is true:

select * from [1.2.3.4,1433\MSSQLSERVER].test.dbo.Table1

It's just, note [] around IP address section.

Spring cron expression for every day 1:01:am

Try with:

@Scheduled(cron = "0 1 1 * * ?")

Below you can find the example patterns from the spring forum:

* "0 0 * * * *" = the top of every hour of every day.
* "*/10 * * * * *" = every ten seconds.
* "0 0 8-10 * * *" = 8, 9 and 10 o'clock of every day.
* "0 0 8,10 * * *" = 8 and 10 o'clock of every day.
* "0 0/30 8-10 * * *" = 8:00, 8:30, 9:00, 9:30 and 10 o'clock every day.
* "0 0 9-17 * * MON-FRI" = on the hour nine-to-five weekdays
* "0 0 0 25 12 ?" = every Christmas Day at midnight

Cron expression is represented by six fields:

second, minute, hour, day of month, month, day(s) of week

(*) means match any

*/X means "every X"

? ("no specific value") - useful when you need to specify something in one of the two fields in which the character is allowed, but not the other. For example, if I want my trigger to fire on a particular day of the month (say, the 10th), but I don't care what day of the week that happens to be, I would put "10" in the day-of-month field and "?" in the day-of-week field.

PS: In order to make it work, remember to enable it in your application context: https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/scheduling.html#scheduling-annotation-support

Android : change button text and background color

Just complementing @Jonsmoke's answer.

For API level 21 and above you can use :

android:backgroundTint="@android:color/white"

in XML for the button layout.

For API level below 21 use an AppCompatButton using app namespace instead of android for backgroundTint.

For example:

<android.support.v7.widget.AppCompatButton
    android:id="@+id/my_button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="My Button"
    app:backgroundTint="@android:color/white" />

Android Camera Preview Stretched

Very important point here to understand , the SurfaceView size must be the same as the camera parameters size , it means they have the same aspect ratio then the Stretch effect will go off .

You have to get the correct supported camera preview size using params.getSupportedPreviewSizes() choose one of them and then change your SurfaceView and its holders to this size.

How to restore the permissions of files and directories within git if they have been modified?

Git keeps track of filepermission and exposes permission changes when creating patches using git diff -p. So all we need is:

  1. create a reverse patch
  2. include only the permission changes
  3. apply the patch to our working copy

As a one-liner:

git diff -p -R --no-ext-diff --no-color \
    | grep -E "^(diff|(old|new) mode)" --color=never  \
    | git apply

you can also add it as an alias to your git config...

git config --global --add alias.permission-reset '!git diff -p -R --no-ext-diff --no-color | grep -E "^(diff|(old|new) mode)" --color=never | git apply'

...and you can invoke it via:

git permission-reset

Note, if you shell is bash, make sure to use ' instead of " quotes around the !git, otherwise it gets substituted with the last git command you ran.

Thx to @Mixologic for pointing out that by simply using -R on git diff, the cumbersome sed command is no longer required.

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

In Windows 10 you might also want to delete Windows Explorer's override for file extension association:

HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.ps1\UserChoice

in addition to the HKEY_CLASSES_ROOT\Microsoft.PowerShellScript.1\Shell\open\command change mentioned in other answers.

See https://stackoverflow.com/a/2697804/1360907

assign value using linq

using Linq would be:

 listOfCompany.Where(c=> c.id == 1).FirstOrDefault().Name = "Whatever Name";

UPDATE

This can be simplified to be...

 listOfCompany.FirstOrDefault(c=> c.id == 1).Name = "Whatever Name";

UPDATE

For multiple items (condition is met by multiple items):

 listOfCompany.Where(c=> c.id == 1).ToList().ForEach(cc => cc.Name = "Whatever Name");

How to print without newline or space?

you want to print something in for loop right;but you don't want it print in new line every time.. for example:

 for i in range (0,5):
   print "hi"

 OUTPUT:
    hi
    hi
    hi
    hi
    hi

but you want it to print like this: hi hi hi hi hi hi right???? just add a comma after print "hi"

Example:

for i in range (0,5): print "hi", OUTPUT: hi hi hi hi hi

configure: error: C compiler cannot create executables

About clang iOS cross-compiler

I've found that the problem was at miphoneos-version-min=5.0 . I've changed into miphoneos-version-min=8.0 . Now it works.

I just want suggest to use create a simple test.c file and compile it by the command write in the log.

How to read all rows from huge table?

The short version is, call stmt.setFetchSize(50); and conn.setAutoCommit(false); to avoid reading the entire ResultSet into memory.

Here's what the docs say:

Getting results based on a cursor

By default the driver collects all the results for the query at once. This can be inconvenient for large data sets so the JDBC driver provides a means of basing a ResultSet on a database cursor and only fetching a small number of rows.

A small number of rows are cached on the client side of the connection and when exhausted the next block of rows is retrieved by repositioning the cursor.

Note:

  • Cursor based ResultSets cannot be used in all situations. There a number of restrictions which will make the driver silently fall back to fetching the whole ResultSet at once.

  • The connection to the server must be using the V3 protocol. This is the default for (and is only supported by) server versions 7.4 and later.-

  • The Connection must not be in autocommit mode. The backend closes cursors at the end of transactions, so in autocommit mode the backend will have closed the cursor before anything can be fetched from it.-

  • The Statement must be created with a ResultSet type of ResultSet.TYPE_FORWARD_ONLY. This is the default, so no code will need to be rewritten to take advantage of this, but it also means that you cannot scroll backwards or otherwise jump around in the ResultSet.-

  • The query given must be a single statement, not multiple statements strung together with semicolons.

Example 5.2. Setting fetch size to turn cursors on and off.

Changing code to cursor mode is as simple as setting the fetch size of the Statement to the appropriate size. Setting the fetch size back to 0 will cause all rows to be cached (the default behaviour).

// make sure autocommit is off
conn.setAutoCommit(false);
Statement st = conn.createStatement();

// Turn use of the cursor on.
st.setFetchSize(50);
ResultSet rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
   System.out.print("a row was returned.");
}
rs.close();

// Turn the cursor off.
st.setFetchSize(0);
rs = st.executeQuery("SELECT * FROM mytable");
while (rs.next()) {
   System.out.print("many rows were returned.");
}
rs.close();

// Close the statement.
st.close();

Set a cookie to never expire

Set a far future absolute time:

setcookie("CookieName", "CookieValue", 2147483647);

It is better to use an absolute time than calculating it relative to the present as recommended in the accepted answer.

The maximum value compatible with 32 bits systems is:

2147483647 = 2^31 = ~year 2038

python numpy ValueError: operands could not be broadcast together with shapes

Per numpy docs:

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when:

  • they are equal, or
  • one of them is 1

In other words, if you are trying to multiply two matrices (in the linear algebra sense) then you want X.dot(y) but if you are trying to broadcast scalars from matrix y onto X then you need to perform X * y.T.

Example:

>>> import numpy as np
>>>
>>> X = np.arange(8).reshape(4, 2)
>>> y = np.arange(2).reshape(1, 2)  # create a 1x2 matrix
>>> X * y
array([[0,1],
       [0,3],
       [0,5],
       [0,7]])

Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time

As ping works, but telnetto port 80 does not, the HTTP port 80 is closed on your machine. I assume that your browser's HTTP connection goes through a proxy (as browsing works, how else would you read stackoverflow?). You need to add some code to your python program, that handles the proxy, like described here:

Using an HTTP PROXY - Python

Get environment variable value in Dockerfile

Load environment variables from a file you create at runtime.

export MYVAR="my_var_outside"
cat > build/env.sh <<EOF
MYVAR=${MYVAR}
EOF

... then in the Dockerfile

ADD build /build
RUN /build/test.sh

where test.sh loads MYVAR from env.sh

#!/bin/bash
. /build/env.sh
echo $MYVAR > /tmp/testfile

Mockito : how to verify method was called on an object created within a method?

Solution for your example code using PowerMockito.whenNew

  • mockito-all 1.10.8
  • powermock-core 1.6.1
  • powermock-module-junit4 1.6.1
  • powermock-api-mockito 1.6.1
  • junit 4.12

FooTest.java

package foo;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

//Both @PrepareForTest and @RunWith are needed for `whenNew` to work 
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Foo.class })
public class FooTest {

    // Class Under Test
    Foo cut;

    @Mock
    Bar barMock;

    @Before
    public void setUp() throws Exception {
        cut = new Foo();

    }

    @After
    public void tearDown() {
        cut = null;

    }

    @Test
    public void testFoo() throws Exception {

        // Setup
        PowerMockito.whenNew(Bar.class).withNoArguments()
                .thenReturn(this.barMock);

        // Test
        cut.foo();

        // Validations
        Mockito.verify(this.barMock, Mockito.times(1)).someMethod();

    }

}

JUnit Output JUnit Output

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

Years later, but for what it's worth - This is simple to do.

  • Just RENAME the C:\xampp directory

  • Install the desired new version of XAMPP

  • Simply run the control panel script "xampp-control.exe" directly from within the xampp folder. (Ignore warnings about "must run from C:\xampp - those have nothing to do with multiple installations.)

To switch between these versions of XAMPP, just rename the xampp directories as necessary, and re-run.

Merge Two Lists in R

If lists always have the same structure, as in the example, then a simpler solution is

mapply(c, first, second, SIMPLIFY=FALSE)

Coloring Buttons in Android with Material Design and AppCompat

This has been enhanced in v23.0.0 of AppCompat library with the addition of more themes including

Widget.AppCompat.Button.Colored

First of all include appCompat dependency if you haven't already

compile('com.android.support:appcompat-v7:23.0.0') {
    exclude group: 'com.google.android', module: 'support-v4'
}

now since you need to use v23 of the app compat, you'll need to target SDK-v23 as well!

    compileSdkVersion = 23
    targetSdkVersion = 23

In your values/theme

<item name="android:buttonStyle">@style/BrandButtonStyle</item>

In your values/style

<style name="BrandButtonStyle" parent="Widget.AppCompat.Button.Colored">
    <item name="colorButtonNormal">@color/yourButtonColor</item>
    <item name="android:textColor">@color/White</item>
</style>

In your values-v21/style

<style name="BrandButtonStyle" parent="Widget.AppCompat.Button.Colored">
    <item name="android:colorButtonNormal">@color/yourButtonColor</item>
    <item name="android:textColor">@color/White</item>
</style>

Since your button theme is based on Widget.AppCompat.Button.Colored The text color on the button is by default white!

but it seems there is an issue when you disable the button, the button will change its color to light grey, but the text color will remain white!

a workaround for this is to specifically set the text color on the button to white! as I have done in the style shown above.

now you can simply define your button and let AppCompat do the rest :)

<Button
        android:layout_width="200dp"
        android:layout_height="48dp" />

Disabled State Disabled state

Enabled State Enabled State

Edit:

To add <Button android:theme="@style/BrandButtonStyle"/>

MetadataException: Unable to load the specified metadata resource

I've just spent a happy 30 minutes with this. I'd renamed the entities object, renamed the entry in the config file, but there's more ... you have to change the reference to the csdl as well

very easy to miss - if you're renaming, make sure you get everything ....

php $_POST array empty upon form submission

I came across a similar yet slightly different issue and it took 2 days to understand the issue.

  • In my case also POST array was empty.

  • Then checked with file_get_contents('php://input'); and that was also empty.

Later I found that browser wasnt asking confirmation for resubmitting form data after If I refresh the page loaded after POST submission. It was directly refreshing page. But when I changed form URL to a different one it was passing POST properly and asked for resubmitting data when attempted to refresh page.

Then I checked what is wrong with actual URL . There were no fault with URL, however it was pointing to a folder without index.php in URL and I was checking POST at index.php.

Here I doubted the redirection from / to /index.php causes POST data to be lost and tested URL with appending index.php to the URL.

That Worked.

Posted it here so someone would find it helpful.

Could not find server 'server name' in sys.servers. SQL Server 2014

I figured out the issue. The linked server was created correctly. However, after the server was upgraded and switched the server name in sys.servers still had the old server name.

I had to drop the old server name and add the new server name to sys.servers on the new server

sp_dropserver 'Server_A'
GO
sp_addserver  'Server',local
GO

How to check if a radiobutton is checked in a radiogroup in Android?

If you want to check on just one RadioButton you can use the isChecked function

if(radioButton.isChecked())
{
  // is checked    
}
else
{
  // not checked
}

and if you have a RadioGroup you can use

if (radioGroup.getCheckedRadioButtonId() == -1)
{
  // no radio buttons are checked
}
else
{
  // one of the radio buttons is checked
}

Swift_TransportException Connection could not be established with host smtp.gmail.com

tcp:465 was blocked. Try to add a new firewall rules and add a rule port 465. or check 587 and change the encryption to tls.

Deserializing a JSON file with JavaScriptSerializer()

  1. You need to create a class that holds the user values, just like the response class User.
  2. Add a property to the Response class 'user' with the type of the new class for the user values User.

    public class Response {
    
        public string id { get; set; }
        public string text { get; set; }
        public string url { get; set; }
        public string width { get; set; }
        public string height { get; set; }
        public string size { get; set; }
        public string type { get; set; }
        public string timestamp { get; set; }
        public User user { get; set; }
    
    }
    
    public class User {
    
        public int id { get; set; }
        public string screen_name { get; set; }
    
    }
    

In general you should make sure the property types of the json and your CLR classes match up. It seems that the structure that you're trying to deserialize contains multiple number values (most likely int). I'm not sure if the JavaScriptSerializer is able to deserialize numbers into string fields automatically, but you should try to match your CLR type as close to the actual data as possible anyway.

Can Mysql Split a column?

As an addendum to this, I've strings of the form: Some words 303

where I'd like to split off the numerical part from the tail of the string. This seems to point to a possible solution:

http://lists.mysql.com/mysql/222421

The problem however, is that you only get the answer "yes, it matches", and not the start index of the regexp match.

Creating a List of Lists in C#

A quick example:

List<List<string>> myList = new List<List<string>>();
myList.Add(new List<string> { "a", "b" });
myList.Add(new List<string> { "c", "d", "e" });
myList.Add(new List<string> { "qwerty", "asdf", "zxcv" });
myList.Add(new List<string> { "a", "b" });

// To iterate over it.
foreach (List<string> subList in myList)
{
    foreach (string item in subList)
    {
        Console.WriteLine(item);
    }
}

Is that what you were looking for? Or are you trying to create a new class that extends List<T> that has a member that is a `List'?

Convert int to string?

The ToString method of any object is supposed to return a string representation of that object.

int var1 = 2;

string var2 = var1.ToString();

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

Another possible solution depending on your situation.

If you know that libpthread_rt.so.1 is the same as libpthread_rt.so then you can create a symlink by:

ln -s /lib/libpthread_rt.so /lib/libpthread_rt.so.1

Then ls -l /lib should now show the symlink and what it points to.