Programs & Examples On #Working copy

git status shows modifications, git checkout -- <file> doesn't remove them

For me the problem was that Visual Studio was opened when performing the command

git checkout <file>

After closing Visual Studio the command worked and I could finally apply my work from the stack. So check all applications that could make changes to your code, for example SourceTree, SmartGit, NotePad, NotePad++ and other editors.

SVN upgrade working copy

You have to upgrade your subversion client to at least 1.7.

With the command line client, you have to manually upgrade your working copy format by issuing the command svn upgrade:

Upgrading the Working Copy

Subversion 1.7 introduces substantial changes to the working copy format. In previous releases of Subversion, Subversion would automatically update the working copy to the new format when a write operation was performed. Subversion 1.7, however, will make this a manual step. Before using Subversion 1.7 with their working copies, users will be required to run a new command, svn upgrade to update the metadata to the new format. This command may take a while, and for some users, it may be more practical to simply checkout a new working copy.
Subversion 1.7 Release Notes

TortoiseSVN will perform the working copy upgrade with the next write operation:

Upgrading the Working Copy

Subversion 1.7 introduces substantial changes to the working copy format. In previous releases, Subversion would automatically update the working copy to the new format when a write operation was performed. Subversion 1.7, however, will make this a manual step.

Before you can use an existing working copy with TortoiseSVN 1.7, you have to upgrade the format first. If you right-click on an old working copy, TortoiseSVN only shows you one command in the context menu: Upgrade working copy.
TortoiseSVN 1.7 Release notes

Convert string date to timestamp in Python

A simple function to get UNIX Epoch time.

NOTE: This function assumes the input date time is in UTC format (Refer to comments here).

def utctimestamp(ts: str, DATETIME_FORMAT: str = "%d/%m/%Y"):
    import datetime, calendar
    ts = datetime.datetime.utcnow() if ts is None else datetime.datetime.strptime(ts, DATETIME_FORMAT)
    return calendar.timegm(ts.utctimetuple())

Usage:

>>> utctimestamp("01/12/2011")
1322697600
>>> utctimestamp("2011-12-01", "%Y-%m-%d")
1322697600

Changing background color of selected item in recyclerview

Create a selector into Drawable folder:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"> 
<item android:state_pressed="true">
   <shape>
         <solid android:color="@color/blue" />
   </shape>
</item>

<item android:state_pressed="false">
    <shape>
       <solid android:color="@android:color/transparent" />
    </shape>
</item>
</selector>

Add the property into your xml (where you declare the RecyclerView):

android:background="@drawable/selector"

CALL command vs. START with /WAIT option

Call

Calls one batch program from another without stopping the parent batch program. The call command accepts labels as the target of the call. Call has no effect at the command-line when used outside of a script or batch file. https://technet.microsoft.com/en-us/library/bb490873.aspx

Start

Starts a separate Command Prompt window to run a specified program or command. Used without parameters, start opens a second command prompt window. https://technet.microsoft.com/en-us/library/bb491005.aspx

An established connection was aborted by the software in your host machine

If you develop in multiple IDE's or other programs that connect to AVD you should try closing them too.

Netbeans also can cause conflicts with eclipse if you set it up for NBAndroid.

Missing artifact com.microsoft.sqlserver:sqljdbc4:jar:4.0

I had the similar problem and solved it by doing following.

  • Download sqljdbc4.jar from the Microsoft website to your local machine.
  • Right click on Project-->Import-->Maven-->Install or deploy an artifact to a Maven repository as shown below.

enter image description here

* Next-->Fill the following details

Artifact file: path of the jar you downloaded (Ex: E:\lib\sqljdbc4.jar in my case)
Group Id: com.microsoft.sqlserver
Artifact Id: sqljdbc4
Version: 4.0

enter image description here

  • Then Refresh/clean the project.

    Thank you!

Python pandas insert list into a cell

Quick work around

Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.

mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
data=pd.DataFrame(mydict)
data


   col1     col2
0   1       [1, 4]
1   2       [2, 5]
2   3       [3, 6]

How does inline Javascript (in HTML) work?

There seems to be a lot of bad practice being thrown around Event Handler Attributes. Bad practice is not knowing and using available features where it is most appropriate. The Event Attributes are fully W3C Documented standards and there is nothing bad practice about them. It's no different than placing inline styles, which is also W3C Documented and can be useful in times. Whether you place it wrapped in script tags or not, it's gonna be interpreted the same way.

https://www.w3.org/TR/html5/webappapis.html#event-handler-idl-attributes

How to check if a div is visible state or not?

Add your li to a class, and do $(".myclass").hide(); at the start to hide it instead of the visibility style attribute.

As far as I know, jquery uses the display style attribute to show/hide elements instead of visibility (may be wrong on that one, in either case the above is worth trying)

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

from the terminal type:-

aws configure

then fill in your keys and region.

after this do next step use any environment. You can have multiple keys depending your account. Can manage multiple enviroment or keys

import boto3
aws_session = boto3.Session(profile_name="prod")
# Create an S3 client
s3 = aws_session.client('s3')

pip install mysql-python fails with EnvironmentError: mysql_config not found

In my case my database is running on container and my flask app is running on another container when i tried updating code app got broke with error

   Complete output from command python setup.py egg_info:
/bin/sh: 1: mysql_config: not found
/bin/sh: 1: mariadb_config: not found
/bin/sh: 1: mysql_config: not found
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/tmp/pip-build-bya8e734/mysqlclient/setup.py", line 15, in <module>
    metadata, options = get_config()
  File "/tmp/pip-build-bya8e734/mysqlclient/setup_posix.py", line 65, in get_config
    libs = mysql_config("libs")
  File "/tmp/pip-build-bya8e734/mysqlclient/setup_posix.py", line 31, in mysql_config
    raise OSError("{} not found".format(_mysql_config_path))
OSError: mysql_config not found

Key in stack trace is

/bin/sh: 1: mysql_config: not found

because where my flask app is running doesn't have mysql client properly configured so first i installed mysql server and then install

sudo apt-get install mysql-server-5.7 -y

Then started MySQL

mansoor@LARC-mansur:~/Documents/clients/HR/DevopsSimulator/web$ sudo systemctl start mysql

Then install flask-mysql package and this time it worked

mansoor@LARC-mansur:~/Documents/clients/HR/DevopsSimulator/web$ sudo pip3 install flask-mysqldb

This is different case but posting here because may be someone else in the world facing same issue

Remove row lines in twitter bootstrap

Got the same question from a friend. My suggestion which does not require !Important looks like this: I add a custom class "no-border" which can be added to the bootstrap table.

.table.no-border tr td, .table.no-border tr th {
  border-width: 0;
}

You can see my go at a solution here

Get HTML inside iframe using jQuery

Just for reference's sake. This is how to do it with JQuery (useful for instance when you cannot query by element id):

$('#iframe').get(0).contentWindow.document.body.innerHTML

MySQL compare DATE string with string from DATETIME field

You can cast the DATETIME field into DATE as:

SELECT * FROM `calendar` WHERE CAST(startTime AS DATE) = '2010-04-29'

This is very much efficient.

How to convert a Django QuerySet to a list

Why not just call .values('reqColumn1','reqColumn2') or .values_list('reqColumn1','reqColumn2') on the queryset?

answers_list = models.objects.values('reqColumn1','reqColumn2')

result = [{'reqColumn1':value1,'reqColumn2':value2}]

OR

answers_list = models.objects.values_list('reqColumn1','reqColumn2')

result = [(value1,value2)]

You can able to do all the operation on this QuerySet, which you do for list .

Latex Multiple Linebreaks

Do you want more space between paragraphs? Then you can change the parameter \parskip.

For example, try

\setlength{\parskip}{10pt plus 1pt minus 1pt}

This means that the space between paragraphs is usually 10pt, but can grow or shrink by up to 1pt. This means you give LaTeX the ability to change it up to one 1pt in order to achieve a better page layout. You can remove the plus and minus parts to make it always your specified length.

If you are trying to display source code, try the listings package or use verbatim. If you are trying to typeset pseudocode, try the algorithm package.

Where can I find error log files?

You can use "lsof" to find open logfiles on your system. lsof just gives you a list of all open files.

Use grep for "log" ... use grep again for "php" (if the filename contains the strings "log" and "php" like in "php_error_log" and you are root user you will find the files without knowing the configuration).

        root@lnx-work:~# lsof |grep log
        ... snip
        gmain     12148 12274       user   13r      REG              252,1    32768     661814 /home/user/.local/share/gvfs-metadata/home-11ab0393.log
        gmain     12148 12274       user   21r      REG              252,1    32768     662622 /home/user/.local/share/gvfs-metadata/root-56222fe2.log
        gvfs-udis 12246             user  mem       REG              252,1    55384     790567 /lib/x86_64-linux-gnu/libsystemd-login.so.0.7.1
==> apache 12333             user  mem       REG              252,1    55384     790367 /var/log/http/php_error_log**
        ... snip 

        root@lnx-work:~# lsof |grep log |grep php 
        **apache 12333             user  mem       REG              252,1    55384     790367 /var/log/http/php_error_log**
        ... snip 

Also see this article on finding open logfiles: Find open logfiles on a linux system

Add rows to CSV File in powershell

Create a new custom object and add it to the object array that Import-Csv creates.

$fileContent = Import-csv $file -header "Date", "Description"
$newRow = New-Object PsObject -Property @{ Date = 'Text4' ; Description = 'Text5' }
$fileContent += $newRow

Split string into tokens and save them in an array

#include <stdio.h>
#include <string.h>

int main ()
{
    char buf[] ="abc/qwe/ccd";
    int i = 0;
    char *p = strtok (buf, "/");
    char *array[3];

    while (p != NULL)
    {
        array[i++] = p;
        p = strtok (NULL, "/");
    }

    for (i = 0; i < 3; ++i) 
        printf("%s\n", array[i]);

    return 0;
}

Convert pandas dataframe to NumPy array

Here is my approach to making a structure array from a pandas DataFrame.

Create the data frame

import pandas as pd
import numpy as np
import six

NaN = float('nan')
ID = [1, 2, 3, 4, 5, 6, 7]
A = [NaN, NaN, NaN, 0.1, 0.1, 0.1, 0.1]
B = [0.2, NaN, 0.2, 0.2, 0.2, NaN, NaN]
C = [NaN, 0.5, 0.5, NaN, 0.5, 0.5, NaN]
columns = {'A':A, 'B':B, 'C':C}
df = pd.DataFrame(columns, index=ID)
df.index.name = 'ID'
print(df)

      A    B    C
ID               
1   NaN  0.2  NaN
2   NaN  NaN  0.5
3   NaN  0.2  0.5
4   0.1  0.2  NaN
5   0.1  0.2  0.5
6   0.1  NaN  0.5
7   0.1  NaN  NaN

Define function to make a numpy structure array (not a record array) from a pandas DataFrame.

def df_to_sarray(df):
    """
    Convert a pandas DataFrame object to a numpy structured array.
    This is functionally equivalent to but more efficient than
    np.array(df.to_array())

    :param df: the data frame to convert
    :return: a numpy structured array representation of df
    """

    v = df.values
    cols = df.columns

    if six.PY2:  # python 2 needs .encode() but 3 does not
        types = [(cols[i].encode(), df[k].dtype.type) for (i, k) in enumerate(cols)]
    else:
        types = [(cols[i], df[k].dtype.type) for (i, k) in enumerate(cols)]
    dtype = np.dtype(types)
    z = np.zeros(v.shape[0], dtype)
    for (i, k) in enumerate(z.dtype.names):
        z[k] = v[:, i]
    return z

Use reset_index to make a new data frame that includes the index as part of its data. Convert that data frame to a structure array.

sa = df_to_sarray(df.reset_index())
sa

array([(1L, nan, 0.2, nan), (2L, nan, nan, 0.5), (3L, nan, 0.2, 0.5),
       (4L, 0.1, 0.2, nan), (5L, 0.1, 0.2, 0.5), (6L, 0.1, nan, 0.5),
       (7L, 0.1, nan, nan)], 
      dtype=[('ID', '<i8'), ('A', '<f8'), ('B', '<f8'), ('C', '<f8')])

EDIT: Updated df_to_sarray to avoid error calling .encode() with python 3. Thanks to Joseph Garvin and halcyon for their comment and solution.

Hide Text with CSS, Best Practice?

Actually, a new technique came out recently. This article will answer your questions: http://www.zeldman.com/2012/03/01/replacing-the-9999px-hack-new-image-replacement

.hide-text {
  text-indent: 100%;
  white-space: nowrap;
  overflow: hidden;
}

It is accessible, an has better performance than -99999px.

Update: As @deathlock mentions in the comment area, the author of the fix above (Scott Kellum), has suggested using a transparent font: http://scottkellum.com/2013/10/25/the-new-kellum-method.html.

How to write lists inside a markdown table?

another solution , you can add <br> tag to your table

    |Method name| Behavior |
    |--|--|
    | OnAwakeLogicController(); | Its called when MainLogicController is loaded into the memory , its also hold the following actions :- <br> 1. Checking Audio Settings <br>2. Initializing Level Controller|

enter image description here

How do I make JavaScript beep?

The top answer was correct at the time but is now wrong; you can do it in pure javascript. But the one answer using javascript doesn't work any more, and the other answers are pretty limited or don't use pure javascript.

I made my own solution that works well and lets you control the volume, frequency, and wavetype.

//if you have another AudioContext class use that one, as some browsers have a limit
var audioCtx = new (window.AudioContext || window.webkitAudioContext || window.audioContext);

//All arguments are optional:

//duration of the tone in milliseconds. Default is 500
//frequency of the tone in hertz. default is 440
//volume of the tone. Default is 1, off is 0.
//type of tone. Possible values are sine, square, sawtooth, triangle, and custom. Default is sine.
//callback to use on end of tone
function beep(duration, frequency, volume, type, callback) {
    var oscillator = audioCtx.createOscillator();
    var gainNode = audioCtx.createGain();

    oscillator.connect(gainNode);
    gainNode.connect(audioCtx.destination);

    if (volume){gainNode.gain.value = volume;}
    if (frequency){oscillator.frequency.value = frequency;}
    if (type){oscillator.type = type;}
    if (callback){oscillator.onended = callback;}

    oscillator.start(audioCtx.currentTime);
    oscillator.stop(audioCtx.currentTime + ((duration || 500) / 1000));
};

Someone suggested I edit this to note it only works on some browsers. However Audiocontext seems to be supported on all modern browsers, as far as I can tell. It isn't supported on IE, but that has been discontinued by Microsoft. If you have any issues with this on a specific browser please report it.

How to get the root dir of the Symfony2 application?

UPDATE 2018-10-21:

As of this week, getRootDir() was deprecated. Please use getProjectDir() instead, as suggested in the comment section by Muzaraf Ali.

—-

Use this:

$this->get('kernel')->getRootDir();

And if you want the web root:

$this->get('kernel')->getRootDir() . '/../web' . $this->getRequest()->getBasePath();

this will work from controller action method...

EDIT: As for the services, I think the way you did it is as clean as possible, although I would pass complete kernel service as an argument... but this will also do the trick...

What do parentheses surrounding an object/function/class declaration mean?

...but what about the previous round parenteses surrounding all the function declaration?

Specifically, it makes JavaScript interpret the 'function() {...}' construct as an inline anonymous function expression. If you omitted the brackets:

function() {
    alert('hello');
}();

You'd get a syntax error, because the JS parser would see the 'function' keyword and assume you're starting a function statement of the form:

function doSomething() {
}

...and you can't have a function statement without a function name.

function expressions and function statements are two different constructs which are handled in very different ways. Unfortunately the syntax is almost identical, so it's not just confusing to the programmer, even the parser has difficulty telling which you mean!

make iframe height dynamic based on content inside- JQUERY/Javascript

I found that the accepted answer didn't suffice, since X-FRAME-OPTIONS: Allow-From isn't supported in safari or chrome. Went with a different approach instead, found in a presentation given by Ben Vinegar from Disqus. The idea is to add an event listener to the parent window, and then inside the iframe, use window.postMessage to send an event to the parent telling it to do something (resize the iframe).

So in the parent document, add an event listener:

window.addEventListener('message', function(e) {
  var $iframe = jQuery("#myIframe");
  var eventName = e.data[0];
  var data = e.data[1];
  switch(eventName) {
    case 'setHeight':
      $iframe.height(data);
      break;
  }
}, false);

And inside the iframe, write a function to post the message:

function resize() {
  var height = document.getElementsByTagName("html")[0].scrollHeight;
  window.parent.postMessage(["setHeight", height], "*"); 
}

Finally, inside the iframe, add an onLoad to the body tag to fire the resize function:

<body onLoad="resize();">

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

PHP Composer behind http proxy

Try this:

export HTTPS_PROXY_REQUEST_FULLURI=false

solved this issue for me working behind a proxy at a company few weeks ago.

What is the most efficient/elegant way to parse a flat table into a tree?

Well given the choice, I'd be using objects. I'd create an object for each record where each object has a children collection and store them all in an assoc array (/hashtable) where the Id is the key. And blitz through the collection once, adding the children to the relevant children fields. Simple.

But because you're being no fun by restricting use of some good OOP, I'd probably iterate based on:

function PrintLine(int pID, int level)
    foreach record where ParentID == pID
        print level*tabs + record-data
        PrintLine(record.ID, level + 1)

PrintLine(0, 0)

Edit: this is similar to a couple of other entries, but I think it's slightly cleaner. One thing I'll add: this is extremely SQL-intensive. It's nasty. If you have the choice, go the OOP route.

Show space, tab, CRLF characters in editor of Visual Studio

For Visual Studio for mac, you can find it under Visual Studio -> Preferences -> Text Editor -> Markers and Rulers -> Show invisible characters

Please note you may need to restart Visual Studio for the changes to take effect

How to post JSON to a server using C#?

Further to Sean's post, it isn't necessary to nest the using statements. By using the StreamWriter it will be flushed and closed at the end of the block so no need to explicitly call the Flush() and Close() methods:

var request = (HttpWebRequest)WebRequest.Create("http://url");
request.ContentType = "application/json";
request.Method = "POST";

using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
    string json = new JavaScriptSerializer().Serialize(new
                {
                    user = "Foo",
                    password = "Baz"
                });

    streamWriter.Write(json);
}

var response = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
        var result = streamReader.ReadToEnd();
}

How to remove an appended element with Jquery and why bind or live is causing elements to repeat

Do you have multiple Radio Buttons on the page..

Because what I see is that you are assigning the events to all the radio button's on the page when you click on a radio button

Using iFrames In ASP.NET

How about:

<asp:HtmlIframe ID="yourIframe" runat="server" />

Is supported since .Net Framework 4.5

If you have Problems using this control, you might take a look here.

jQuery: Performing synchronous AJAX requests

As you're making a synchronous request, that should be

function getRemote() {
    return $.ajax({
        type: "GET",
        url: remote_url,
        async: false
    }).responseText;
}

Example - http://api.jquery.com/jQuery.ajax/#example-3

PLEASE NOTE: Setting async property to false is deprecated and in the process of being removed (link). Many browsers including Firefox and Chrome have already started to print a warning in the console if you use this:

Chrome:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.

Firefox:

Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/

Force to open "Save As..." popup open at text link click for PDF in HTML

Just put the below code in your .htaccess file:

AddType application/octet-stream .csv
AddType application/octet-stream .xls
AddType application/octet-stream .doc
AddType application/octet-stream .avi
AddType application/octet-stream .mpg
AddType application/octet-stream .mov
AddType application/octet-stream .pdf

Or you can also do trick by JavaScript

element.setAttribute( 'download', whatever_string_you_want);

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

Step-1: Your Model class

public class RechargeMobileViewModel
    {
        public string CustomerFullName { get; set; }
        public string TelecomSubscriber { get; set; }
        public int TotalAmount { get; set; }
        public string MobileNumber { get; set; }
        public int Month { get; set; }
        public List<SelectListItem> getAllDaysList { get; set; }

        // Define the list which you have to show in Drop down List
        public List<SelectListItem> getAllWeekDaysList()
        {
            List<SelectListItem> myList = new List<SelectListItem>();
            var data = new[]{
                 new SelectListItem{ Value="1",Text="Monday"},
                 new SelectListItem{ Value="2",Text="Tuesday"},
                 new SelectListItem{ Value="3",Text="Wednesday"},
                 new SelectListItem{ Value="4",Text="Thrusday"},
                 new SelectListItem{ Value="5",Text="Friday"},
                 new SelectListItem{ Value="6",Text="Saturday"},
                 new SelectListItem{ Value="7",Text="Sunday"},
             };
            myList = data.ToList();
            return myList;
        }
}

Step-2: Call this method to fill Drop down in your controller Action

namespace MvcVariousApplication.Controllers
    {
        public class HomeController : Controller
        {
            public ActionResult Index()
            {
              RechargeMobileViewModel objModel = new RechargeMobileViewModel();
                objModel.getAllDaysList = objModel.getAllWeekDaysList();  
                return View(objModel);
            }
    }
    }

Step-3: Fill your Drop-Down List of View as follows

 @model MvcVariousApplication.Models.RechargeMobileViewModel
    @{
        ViewBag.Title = "Contact";
    }
    @Html.LabelFor(model=> model.CustomerFullName)
    @Html.TextBoxFor(model => model.CustomerFullName)

    @Html.LabelFor(model => model.MobileNumber)
    @Html.TextBoxFor(model => model.MobileNumber)

    @Html.LabelFor(model => model.TelecomSubscriber)
    @Html.TextBoxFor(model => model.TelecomSubscriber)

    @Html.LabelFor(model => model.TotalAmount)
    @Html.TextBoxFor(model => model.TotalAmount)

    @Html.LabelFor(model => model.Month)
    @Html.DropDownListFor(model => model.Month, new SelectList(Model.getAllDaysList, "Value", "Text"), "-Select Day-")

Why would a "java.net.ConnectException: Connection timed out" exception occur when URL is up?

There is a possibility that your IP/host are blocked by the remote host, especially if it thinks you are hitting it too hard.

Replace non-ASCII characters with a single space

Your ''.join() expression is filtering, removing anything non-ASCII; you could use a conditional expression instead:

return ''.join([i if ord(i) < 128 else ' ' for i in text])

This handles characters one by one and would still use one space per character replaced.

Your regular expression should just replace consecutive non-ASCII characters with a space:

re.sub(r'[^\x00-\x7F]+',' ', text)

Note the + there.

Linker Error C++ "undefined reference "

Your error shows you are not compiling file with the definition of the insert function. Update your command to include the file which contains the definition of that function and it should work.

Removing a non empty directory programmatically in C or C++

You can use opendir and readdir to read directory entries and unlink to delete them.

Any difference between await Promise.all() and multiple await?

Generally, using Promise.all() runs requests "async" in parallel. Using await can run in parallel OR be "sync" blocking.

test1 and test2 functions below show how await can run async or sync.

test3 shows Promise.all() that is async.

jsfiddle with timed results - open browser console to see test results

Sync behavior. Does NOT run in parallel, takes ~1800ms:

const test1 = async () => {
  const delay1 = await Promise.delay(600); //runs 1st
  const delay2 = await Promise.delay(600); //waits 600 for delay1 to run
  const delay3 = await Promise.delay(600); //waits 600 more for delay2 to run
};

Async behavior. Runs in paralel, takes ~600ms:

const test2 = async () => {
  const delay1 = Promise.delay(600);
  const delay2 = Promise.delay(600);
  const delay3 = Promise.delay(600);
  const data1 = await delay1;
  const data2 = await delay2;
  const data3 = await delay3; //runs all delays simultaneously
}

Async behavior. Runs in parallel, takes ~600ms:

const test3 = async () => {
  await Promise.all([
  Promise.delay(600), 
  Promise.delay(600), 
  Promise.delay(600)]); //runs all delays simultaneously
};

TLDR; If you are using Promise.all() it will also "fast-fail" - stop running at the time of the first failure of any of the included functions.

iOS for VirtualBox

You could try qemu, which is what the Android emulator uses. I believe it actually emulates the ARM hardware.

JSON find in JavaScript

Ok. So, I know this is an old post, but perhaps this can help someone else. This is not backwards compatible, but that's almost irrelevant since Internet Explorer is being made redundant.

Easiest way to do exactly what is wanted:

function findInJson(objJsonResp, key, value, aType){        
     if(aType=="edit"){
        return objJsonResp.find(x=> x[key] == value);
     }else{//delete
         var a =objJsonResp.find(x=> x[key] == value);
         objJsonResp.splice(objJsonResp.indexOf(a),1);
     }
}

It will return the item you want to edit if you supply 'edit' as the type. Supply anything else, or nothing, and it assumes delete. You can flip the conditionals if you'd prefer.

In Bash, how to add "Are you sure [Y/n]" to any command or alias?

I know this is an old question but this might help someone, it hasn't been addressed here.

I have been asked how to use rm -i in a script which is receiving input from a file. As file input to a script is normally received from STDIN we need to change it, so that only the response to the rm command is received from STDIN. Here's the solution:

#!/bin/bash
while read -u 3 line
do
 echo -n "Remove file $line?"
 read -u 1 -n 1 key
 [[ $key = "y" ]] &&  rm "$line"
 echo
done 3<filelist

If ANY key other than the "y" key (lower case only) is pressed, the file will not be deleted. It is not necessary to press return after the key (hence the echo command to send a new line to the display). Note that the POSIX bash "read" command does not support the -u switch so a workaround would need to be sought.

Do AJAX requests retain PHP Session info?

Well, not always. Using cookies, you are good. But the "can I safely rely on the id being present" urged me to extend the discussion with an important point (mostly for reference, as the visitor count of this page seems quite high).

PHP can be configured to maintain sessions by URL-rewriting, instead of cookies. (How it's good or bad (<-- see e.g. the topmost comment there) is a separate question, let's now stick to the current one, with just one side-note: the most prominent issue with URL-based sessions -- the blatant visibility of the naked session ID -- is not an issue with internal Ajax calls; but then, if it's turned on for Ajax, it's turned on for the rest of the site, too, so there...)

In case of URL-rewriting (cookieless) sessions, Ajax calls must take care of it themselves that their request URLs are properly crafted. (Or you can roll your own custom solution. You can even resort to maintaining sessions on the client side, in less demanding cases.) The point is the explicit care needed for session continuity, if not using cookies:

  1. If the Ajax calls just extract URLs verbatim from the HTML (as received from PHP), that should be OK, as they are already cooked (umm, cookified).

  2. If they need to assemble request URIs themselves, the session ID needs to be added to the URL manually. (Check here, or the page sources generated by PHP (with URL-rewriting on) to see how to do it.)


From OWASP.org:

Effectively, the web application can use both mechanisms, cookies or URL parameters, or even switch from one to the other (automatic URL rewriting) if certain conditions are met (for example, the existence of web clients without cookies support or when cookies are not accepted due to user privacy concerns).

From a Ruby-forum post:

When using php with cookies, the session ID will automatically be sent in the request headers even for Ajax XMLHttpRequests. If you use or allow URL-based php sessions, you'll have to add the session id to every Ajax request url.

Get next / previous element using JavaScript?

that's so simple

var element = querySelector("div")
var nextelement = element.ParentElement.querySelector("div+div")

Here is the browser supports https://caniuse.com/queryselector

PHP: maximum execution time when importing .SQL data file

Set Only 3 Parameters from php.ini file of your server

A. max_execution_time = 3000000 (Set as per your requirment)
B. post_max_size = 4096M
C. upload_max_filesize = 4096M

Edit C:\xampp\phpMyAdmin\libraries\config.default.php Page

$cfg['ExecTimeLimit'] = 0;

After all set, restart your server and import again your database.

Done

npm WARN ... requires a peer of ... but none is installed. You must install peer dependencies yourself

I had a similar issue and solved after running these instructions!

npm install npm -g
npm install --save-dev @angular/cli@latest
npm install
npm start

trim left characters in sql server?

For 'Hello' at the start of the string:

SELECT STUFF('Hello World', 1, 6, '')

This will work for 'Hello' anywhere in the string:

SELECT REPLACE('Hello World', 'Hello ', '')

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

Reading a file character by character in C

Either of the two should do the trick -

char *readFile(char *fileName)
{
  FILE *file;
  char *code = malloc(1000 * sizeof(char));
  char *p = code;
  file = fopen(fileName, "r");
  do 
  {
    *p++ = (char)fgetc(file);
  } while(*p != EOF);
  *p = '\0';
  return code;
}

char *readFile(char *fileName)
{
  FILE *file;
  int i = 0;
  char *code = malloc(1000 * sizeof(char));
  file = fopen(fileName, "r");
  do 
  {
    code[i++] = (char)fgetc(file);
  } while(code[i-1] != EOF);
  code[i] = '\0'
  return code;
}

Like the other posters have pointed out, you need to ensure that the file size does not exceed 1000 characters. Also, remember to free the memory when you're done using it.

How to keep :active css style after click a button

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

HTML

<input type="checkbox" id="activate-div">
  <label for="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>
  </label>

CSS

#activate-div{display:none}    

.my-div{background-color:#FFF} 

#activate-div:checked ~ label 
.my-div{background-color:#000}



To make button change content:

HTML

<input type="checkbox" id="activate-div">
   <div class="my-div">
      //MY DIV CONTENT
   </div>

<label for="activate-div">
   //MY BUTTON STUFF
</label>

CSS

#activate-div{display:none}

.my-div{background-color:#FFF} 

#activate-div:checked + 
.my-div{background-color:#000}

Hope it helps!!

Connection to SQL Server Works Sometimes

Unfortunately, I had problem with Local SQL Server installed within Visual Studio and here many solutions didn't work out for me. All I have to do is to reset my Visual Studio, by going to:

Control Panel > Program & Features > Visual Studio Setup Launcher

and click on More button and choose Repair

After that I was able to access my Local SQL Server and work with local SQL Databases.

What is the Maximum Size that an Array can hold?

I think it is linked with your RAM (or probably virtual memory) space and for the absolute maximum constrained to your OS version (e.g. 32 bit or 64 bit)

Using Jquery Datatable with AngularJs

visit this link for reference:http://codepen.io/kalaiselvan/pen/RRBzda

<script>  
var app=angular.module('formvalid', ['ui.bootstrap','ui.utils']);
app.controller('validationCtrl',function($scope){
  $scope.data=[
        [
            "Tiger Nixon",
            "System Architect",
            "Edinburgh",
            "5421",
            "2011\/04\/25",
            "$320,800"
        ],
        [
            "Garrett Winters",
            "Accountant",
            "Tokyo",
            "8422",
            "2011\/07\/25",
            "$170,750"
        ],
        [
            "Ashton Cox",
            "Junior Technical Author",
            "San Francisco",
            "1562",
            "2009\/01\/12",
            "$86,000"
        ],
        [
            "Cedric Kelly",
            "Senior Javascript Developer",
            "Edinburgh",
            "6224",
            "2012\/03\/29",
            "$433,060"
        ],
        [
            "Airi Satou",
            "Accountant",
            "Tokyo",
            "5407",
            "2008\/11\/28",
            "$162,700"
        ],
        [
            "Brielle Williamson",
            "Integration Specialist",
            "New York",
            "4804",
            "2012\/12\/02",
            "$372,000"
        ],
        [
            "Herrod Chandler",
            "Sales Assistant",
            "San Francisco",
            "9608",
            "2012\/08\/06",
            "$137,500"
        ],
        [
            "Rhona Davidson",
            "Integration Specialist",
            "Tokyo",
            "6200",
            "2010\/10\/14",
            "$327,900"
        ],
        [
            "Colleen Hurst",
            "Javascript Developer",
            "San Francisco",
            "2360",
            "2009\/09\/15",
            "$205,500"
        ],
        [
            "Sonya Frost",
            "Software Engineer",
            "Edinburgh",
            "1667",
            "2008\/12\/13",
            "$103,600"
        ],
        [
            "Jena Gaines",
            "Office Manager",
            "London",
            "3814",
            "2008\/12\/19",
            "$90,560"
        ],
        [
            "Quinn Flynn",
            "Support Lead",
            "Edinburgh",
            "9497",
            "2013\/03\/03",
            "$342,000"
        ],
        [
            "Charde Marshall",
            "Regional Director",
            "San Francisco",
            "6741",
            "2008\/10\/16",
            "$470,600"
        ],
        [
            "Haley Kennedy",
            "Senior Marketing Designer",
            "London",
            "3597",
            "2012\/12\/18",
            "$313,500"
        ],
        [
            "Tatyana Fitzpatrick",
            "Regional Director",
            "London",
            "1965",
            "2010\/03\/17",
            "$385,750"
        ],
        [
            "Michael Silva",
            "Marketing Designer",
            "London",
            "1581",
            "2012\/11\/27",
            "$198,500"
        ],
        [
            "Paul Byrd",
            "Chief Financial Officer (CFO)",
            "New York",
            "3059",
            "2010\/06\/09",
            "$725,000"
        ],
        [
            "Gloria Little",
            "Systems Administrator",
            "New York",
            "1721",
            "2009\/04\/10",
            "$237,500"
        ],
        [
            "Bradley Greer",
            "Software Engineer",
            "London",
            "2558",
            "2012\/10\/13",
            "$132,000"
        ],
        [
            "Dai Rios",
            "Personnel Lead",
            "Edinburgh",
            "2290",
            "2012\/09\/26",
            "$217,500"
        ],
        [
            "Jenette Caldwell",
            "Development Lead",
            "New York",
            "1937",
            "2011\/09\/03",
            "$345,000"
        ],
        [
            "Yuri Berry",
            "Chief Marketing Officer (CMO)",
            "New York",
            "6154",
            "2009\/06\/25",
            "$675,000"
        ],
        [
            "Caesar Vance",
            "Pre-Sales Support",
            "New York",
            "8330",
            "2011\/12\/12",
            "$106,450"
        ],
        [
            "Doris Wilder",
            "Sales Assistant",
            "Sidney",
            "3023",
            "2010\/09\/20",
            "$85,600"
        ],
        [
            "Angelica Ramos",
            "Chief Executive Officer (CEO)",
            "London",
            "5797",
            "2009\/10\/09",
            "$1,200,000"
        ],
        [
            "Gavin Joyce",
            "Developer",
            "Edinburgh",
            "8822",
            "2010\/12\/22",
            "$92,575"
        ],
        [
            "Jennifer Chang",
            "Regional Director",
            "Singapore",
            "9239",
            "2010\/11\/14",
            "$357,650"
        ],
        [
            "Brenden Wagner",
            "Software Engineer",
            "San Francisco",
            "1314",
            "2011\/06\/07",
            "$206,850"
        ],
        [
            "Fiona Green",
            "Chief Operating Officer (COO)",
            "San Francisco",
            "2947",
            "2010\/03\/11",
            "$850,000"
        ],
        [
            "Shou Itou",
            "Regional Marketing",
            "Tokyo",
            "8899",
            "2011\/08\/14",
            "$163,000"
        ],
        [
            "Michelle House",
            "Integration Specialist",
            "Sidney",
            "2769",
            "2011\/06\/02",
            "$95,400"
        ],
        [
            "Suki Burks",
            "Developer",
            "London",
            "6832",
            "2009\/10\/22",
            "$114,500"
        ],
        [
            "Prescott Bartlett",
            "Technical Author",
            "London",
            "3606",
            "2011\/05\/07",
            "$145,000"
        ],
        [
            "Gavin Cortez",
            "Team Leader",
            "San Francisco",
            "2860",
            "2008\/10\/26",
            "$235,500"
        ],
        [
            "Martena Mccray",
            "Post-Sales support",
            "Edinburgh",
            "8240",
            "2011\/03\/09",
            "$324,050"
        ],
        [
            "Unity Butler",
            "Marketing Designer",
            "San Francisco",
            "5384",
            "2009\/12\/09",
            "$85,675"
        ],
        [
            "Howard Hatfield",
            "Office Manager",
            "San Francisco",
            "7031",
            "2008\/12\/16",
            "$164,500"
        ],
        [
            "Hope Fuentes",
            "Secretary",
            "San Francisco",
            "6318",
            "2010\/02\/12",
            "$109,850"
        ],
        [
            "Vivian Harrell",
            "Financial Controller",
            "San Francisco",
            "9422",
            "2009\/02\/14",
            "$452,500"
        ],
        [
            "Timothy Mooney",
            "Office Manager",
            "London",
            "7580",
            "2008\/12\/11",
            "$136,200"
        ],
        [
            "Jackson Bradshaw",
            "Director",
            "New York",
            "1042",
            "2008\/09\/26",
            "$645,750"
        ],
        [
            "Olivia Liang",
            "Support Engineer",
            "Singapore",
            "2120",
            "2011\/02\/03",
            "$234,500"
        ],
        [
            "Bruno Nash",
            "Software Engineer",
            "London",
            "6222",
            "2011\/05\/03",
            "$163,500"
        ],
        [
            "Sakura Yamamoto",
            "Support Engineer",
            "Tokyo",
            "9383",
            "2009\/08\/19",
            "$139,575"
        ],
        [
            "Thor Walton",
            "Developer",
            "New York",
            "8327",
            "2013\/08\/11",
            "$98,540"
        ],
        [
            "Finn Camacho",
            "Support Engineer",
            "San Francisco",
            "2927",
            "2009\/07\/07",
            "$87,500"
        ],
        [
            "Serge Baldwin",
            "Data Coordinator",
            "Singapore",
            "8352",
            "2012\/04\/09",
            "$138,575"
        ],
        [
            "Zenaida Frank",
            "Software Engineer",
            "New York",
            "7439",
            "2010\/01\/04",
            "$125,250"
        ],
        [
            "Zorita Serrano",
            "Software Engineer",
            "San Francisco",
            "4389",
            "2012\/06\/01",
            "$115,000"
        ],
        [
            "Jennifer Acosta",
            "Junior Javascript Developer",
            "Edinburgh",
            "3431",
            "2013\/02\/01",
            "$75,650"
        ],
        [
            "Cara Stevens",
            "Sales Assistant",
            "New York",
            "3990",
            "2011\/12\/06",
            "$145,600"
        ],
        [
            "Hermione Butler",
            "Regional Director",
            "London",
            "1016",
            "2011\/03\/21",
            "$356,250"
        ],
        [
            "Lael Greer",
            "Systems Administrator",
            "London",
            "6733",
            "2009\/02\/27",
            "$103,500"
        ],
        [
            "Jonas Alexander",
            "Developer",
            "San Francisco",
            "8196",
            "2010\/07\/14",
            "$86,500"
        ],
        [
            "Shad Decker",
            "Regional Director",
            "Edinburgh",
            "6373",
            "2008\/11\/13",
            "$183,000"
        ],
        [
            "Michael Bruce",
            "Javascript Developer",
            "Singapore",
            "5384",
            "2011\/06\/27",
            "$183,000"
        ],
        [
            "Donna Snider",
            "Customer Support",
            "New York",
            "4226",
            "2011\/01\/25",
            "$112,000"
        ]
    ]


$scope.dataTableOpt = {
  //if any ajax call 
  };
});
</script>
<div class="container" ng-app="formvalid">
      <div class="panel" data-ng-controller="validationCtrl">
      <div class="panel-heading border">    
        <h2>Data table using jquery datatable in Angularjs </h2>
      </div>
      <div class="panel-body">
          <table class="table table-bordered bordered table-striped table-condensed datatable" ui-jq="dataTable" ui-options="dataTableOpt">
          <thead>
            <tr>
              <th>#</th>
              <th>Name</th>
              <th>Position</th>
              <th>Office</th>
              <th>Age</th>
              <th>Start Date</th>
            </tr>
          </thead>
            <tbody>
              <tr ng-repeat="n in data">
                <td>{{$index+1}}</td>
                <td>{{n[0]}}</td>
                <td>{{n[1]}}</td>
                <td>{{n[2]}}</td>
                <td>{{n[3]}}</td>
                <td>{{n[4] | date:'dd/MM/yyyy'}}</td>
              </tr>
            </tbody>
        </table>
      </div>
    </div>
    </div>

How can I do string interpolation in JavaScript?

Try sprintf library (a complete open source JavaScript sprintf implementation). For example:

vsprintf('The first 4 letters of the english alphabet are: %s, %s, %s and %s', ['a', 'b', 'c', 'd']);

vsprintf takes an array of arguments and returns a formatted string.

How to SUM and SUBTRACT using SQL?

ah homework...

So wait, you need to deduct the balance of items in stock from the total number of those items that have been ordered? I have to tell you that sounds a bit backwards. Generally I think people do it the other way round. Deduct the total number of items ordered from the balance.

If you really need to do that though... Assuming that ITEM is unique in stock_bal...

SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY

How to get text of an element in Selenium WebDriver, without including child element text?

Unfortunately, Selenium was only built to work with Elements, not Text nodes.

If you try to use a function like get_element_by_xpath to target the text nodes, Selenium will throw an InvalidSelectorException.

One workaround is to grab the relevant HTML with Selenium and then use an HTML parsing library like BeautifulSoup that can handle text nodes more elegantly.

import bs4
from bs4 import BeautifulSoup

inner_html = driver.find_elements_by_css_selector('#a')[0].get_attribute("innerHTML")
inner_soup = BeautifulSoup(inner_html, 'html.parser')

outer_html = driver.find_elements_by_css_selector('#a')[0].get_attribute("outerHTML")
outer_soup = BeautifulSoup(outer_html, 'html.parser')

From there, there are several ways to search for the Text content. You'll have to experiment to see what works best for your use case.

Here's a simple one-liner that may be sufficient:

inner_soup.find(text=True)

If that doesn't work, then you can loop through the element's child nodes with .contents() and check their object type.

BeautifulSoup has four types of elements, and the one that you'll be interested in is the NavigableString type, which is produced by Text nodes. By contrast, Elements will have a type of Tag.

contents = inner_soup.contents

for bs4_object in contents:

    if (type(bs4_object) == bs4.Tag):
        print("This object is an Element.")

    elif (type(bs4_object) == bs4.NavigableString):
        print("This object is a Text node.")

Note that BeautifulSoup doesn't support Xpath expressions. If you need those, then you can use some of the workarounds in this thread.

How to check internet access on Android? InetAddress never times out

Network connection / Internet access

  • isConnectedOrConnecting() (used in most answers) checks for any network connection
  • To know whether any of those networks have internet access, use one of the following

A) Ping a Server (easy)

// ICMP 
public boolean isOnline() {
    Runtime runtime = Runtime.getRuntime();
    try {
        Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8");
        int     exitValue = ipProcess.waitFor();
        return (exitValue == 0);
    }
    catch (IOException e)          { e.printStackTrace(); }
    catch (InterruptedException e) { e.printStackTrace(); }

    return false;
}

+ could run on main thread

- does not work on some old devices (Galays S3, etc.), it blocks a while if no internet is available.

B) Connect to a Socket on the Internet (advanced)

// TCP/HTTP/DNS (depending on the port, 53=DNS, 80=HTTP, etc.)
public boolean isOnline() {
    try {
        int timeoutMs = 1500;
        Socket sock = new Socket();
        SocketAddress sockaddr = new InetSocketAddress("8.8.8.8", 53);

        sock.connect(sockaddr, timeoutMs);
        sock.close();

        return true;
    } catch (IOException e) { return false; }
}

+ very fast (either way), works on all devices, very reliable

- can't run on the UI thread

This works very reliably, on every device, and is very fast. It needs to run in a separate task though (e.g. ScheduledExecutorService or AsyncTask).

Possible Questions

  • Is it really fast enough?

    Yes, very fast ;-)

  • Is there no reliable way to check internet, other than testing something on the internet?

    Not as far as I know, but let me know, and I will edit my answer.

  • What if the DNS is down?

    Google DNS (e.g. 8.8.8.8) is the largest public DNS in the world. As of 2018 it handled over a trillion queries a day [1]. Let 's just say, your app would probably not be the talk of the day.

  • Which permissions are required?

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

    Just internet access - surprise ^^ (Btw have you ever thought about, how some of the methods suggested here could even have a remote glue about internet access, without this permission?)

 

Extra: One-shot RxJava/RxAndroid Example (Kotlin)

fun hasInternetConnection(): Single<Boolean> {
  return Single.fromCallable {
    try {
      // Connect to Google DNS to check for connection
      val timeoutMs = 1500
      val socket = Socket()
      val socketAddress = InetSocketAddress("8.8.8.8", 53)
    
      socket.connect(socketAddress, timeoutMs)
      socket.close()
  
      true
    } catch (e: IOException) {
      false
    }
  }
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
}

///////////////////////////////////////////////////////////////////////////////////
// Usage

    hasInternetConnection().subscribe { hasInternet -> /* do something */}

Extra: One-shot RxJava/RxAndroid Example (Java)

public static Single<Boolean> hasInternetConnection() {
    return Single.fromCallable(() -> {
        try {
            // Connect to Google DNS to check for connection
            int timeoutMs = 1500;
            Socket socket = new Socket();
            InetSocketAddress socketAddress = new InetSocketAddress("8.8.8.8", 53);

            socket.connect(socketAddress, timeoutMs);
            socket.close();

            return true;
        } catch (IOException e) {
            return false;
        }
    }).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread());
}

///////////////////////////////////////////////////////////////////////////////////
// Usage

    hasInternetConnection().subscribe((hasInternet) -> {
        if(hasInternet) {

        }else {

        }
    });

Extra: One-shot AsyncTask Example

Caution: This shows another example of how to do the request. However, since AsyncTask is deprecated, it should be replaced by your App's thread scheduling, Kotlin Coroutines, Rx, ...

class InternetCheck extends AsyncTask<Void,Void,Boolean> {

    private Consumer mConsumer;
    public  interface Consumer { void accept(Boolean internet); }

    public  InternetCheck(Consumer consumer) { mConsumer = consumer; execute(); }

    @Override protected Boolean doInBackground(Void... voids) { try {
        Socket sock = new Socket();
        sock.connect(new InetSocketAddress("8.8.8.8", 53), 1500);
        sock.close();
        return true;
    } catch (IOException e) { return false; } }

    @Override protected void onPostExecute(Boolean internet) { mConsumer.accept(internet); }
}

///////////////////////////////////////////////////////////////////////////////////
// Usage

    new InternetCheck(internet -> { /* do something with boolean response */ });

The declared package does not match the expected package ""

Make sure that Devices is defined as a source folder in the project properties.

Sort matrix according to first column in R

The accepted answer works like a charm unless you're applying it to a vector. Since a vector is non-recursive, you'll get an error like this

$ operator is invalid for atomic vectors

You can use [ in that case

foo[order(foo["V1"]),]

TimeStamp on file name using PowerShell

You can insert arbitrary PowerShell script code in a double-quoted string by using a subexpression, for example, $() like so:

"C:\temp\mybackup $(get-date -f yyyy-MM-dd).zip"

And if you are getting the path from somewhere else - already as a string:

$dirName  = [io.path]::GetDirectoryName($path)
$filename = [io.path]::GetFileNameWithoutExtension($path)
$ext      = [io.path]::GetExtension($path)
$newPath  = "$dirName\$filename $(get-date -f yyyy-MM-dd)$ext"

And if the path happens to be coming from the output of Get-ChildItem:

Get-ChildItem *.zip | Foreach {
  "$($_.DirectoryName)\$($_.BaseName) $(get-date -f yyyy-MM-dd)$($_.extension)"}

How to select clear table contents without destroying the table?

I reworked Doug Glancy's solution to avoid rows deletion, which can lead to #Ref issue in formulae.

Sub ListReset(lst As ListObject)
'clears a listObject while leaving row 1 empty, with formulae
    With lst
        If .ShowAutoFilter Then .AutoFilter.ShowAllData
        On Error Resume Next
        With .DataBodyRange
            .Offset(1).Rows.Clear
            .Rows(1).SpecialCells(xlCellTypeConstants).ClearContents
        End With
        On Error GoTo 0
        .Resize .Range.Rows("1:2")
    End With
End Sub

PHP array printing using a loop

$array = array("Jonathan","Sampson");

foreach($array as $value) {
  print $value;
}

or

$length = count($array);
for ($i = 0; $i < $length; $i++) {
  print $array[$i];
}

What should a Multipart HTTP request with multiple files look like?

Well, note that the request contains binary data, so I'm not posting the request as such - instead, I've converted every non-printable-ascii character into a dot (".").

POST /cgi-bin/qtest HTTP/1.1
Host: aram
User-Agent: Mozilla/5.0 Gecko/2009042316 Firefox/3.0.10
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-us,en;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
Referer: http://aram/~martind/banner.htm
Content-Type: multipart/form-data; boundary=2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Length: 514

--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile1"; filename="r.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile2"; filename="g.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f
Content-Disposition: form-data; name="datafile3"; filename="b.gif"
Content-Type: image/gif

GIF87a.............,...........D..;
--2a8ae6ad-f4ad-4d9a-a92c-6d217011fe0f--

Note that every line (including the last one) is terminated by a \r\n sequence.

Calculate date from week number

According to ISO 8601:1988 that is used in Sweden the first week of the year is the first week that has at least four days within the new year.

So if your week starts on a Monday the first Thursday any year is within the first week. You can DateAdd or DateDiff from that.

C++ Boost: undefined reference to boost::system::generic_category()

try

g++ -c main.cpp && g++ main.o /usr/lib/x86_64-linux-gnu/libboost_system.so && ./a.out 

/usr/lib/x86_64-linux-gnu/ is the location of the boost library

use find /usr/ -name '*boost*.so' to find the boost library location

Debug vs Release in CMake

// CMakeLists.txt : release

set(CMAKE_CONFIGURATION_TYPES "Release" CACHE STRING "" FORCE)

// CMakeLists.txt : debug

set(CMAKE_CONFIGURATION_TYPES "Debug" CACHE STRING "" FORCE)

error: No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

I also faced the same problem, I was using GoogleAdMobAdsSDK-4.1.0.jar then I tried with GoogleAdMobAdsSDK-4.0.4.jar now it is working fine, It is problem with jar file as per my experience.

HTML button onclick event

Try this:-

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="ISO-8859-1"> 
    <title>Online Student Portal</title> 
</head> 
<body> 
    <form action="">
         <input type="button" value="Add Students" onclick="window.location.href='Students.html';"/>
         <input type="button" value="Add Courses" onclick="window.location.href='Courses.html';"/>
         <input type="button" value="Student Payments" onclick="window.location.href='Payment.html';"/>
    </form> 
</body> 
</html>

How do you test your Request.QueryString[] variables?

I actually have a utility class that uses Generics to "wrap" session, which does all of the "grunt work" for me, I also have something almost identical for working with QueryString values.

This helps remove the code dupe for the (often numerous) checks..

For example:

public class QueryString
{
    static NameValueCollection QS
    {
        get
        {
            if (HttpContext.Current == null)
                throw new ApplicationException("No HttpContext!");

            return HttpContext.Current.Request.QueryString;
        }
    }

    public static int Int(string key)
    {
        int i; 
        if (!int.TryParse(QS[key], out i))
            i = -1; // Obviously Change as you see fit.
        return i;
    }

    // ... Other types omitted.
}

// And to Use..
void Test()
{
    int i = QueryString.Int("test");
}

NOTE:

This obviously makes use of statics, which some people don't like because of the way it can impact test code.. You can easily refactor into something that works based on instances and any interfaces you require.. I just think the statics example is the lightest.

Hope this helps/gives food for thought.

C# Get/Set Syntax Usage

I do not understand what this is unclear

Properties are members that provide a flexible mechanism to read, write, or compute the values of private fields. Properties can be used as though they are public data members, but they are actually special methods called accessors. This enables data to be accessed easily while still providing the safety and flexibility of methods.

In this example, the class TimePeriod stores a time period. Internally the class stores the time in seconds, but a property called Hours is provided that allows a client to specify a time in hours. The accessors for the Hours property perform the conversion between hours and seconds.

Example

class TimePeriod
{
    private double seconds;

    public double Hours
    {
        get { return seconds / 3600; }
        set { seconds = value * 3600; }
    }
}

class Program
{
    static void Main()
    {
        TimePeriod t = new TimePeriod();

        // Assigning the Hours property causes the 'set' accessor to be called.
        t.Hours = 24;

        // Evaluating the Hours property causes the 'get' accessor to be called.
        System.Console.WriteLine("Time in hours: " + t.Hours);
    }
}

Properties Overview

Properties enable a class to expose a public way of getting and setting values, while hiding implementation or verification code.

A get property accessor is used to return the property value, and a set accessor is used to assign a new value. These accessors can have different access levels.

The value keyword is used to define the value being assigned by the set indexer.

Properties that do not implement a set method are read only.

http://msdn.microsoft.com/en-US/library/x9fsa0sw%28v=vs.80%29.aspx

iPhone UIView Animation Best Practice

The difference seems to be the amount of control you need over the animation.

The CATransition approach gives you more control and therefore more things to set up, eg. the timing function. Being an object, you can store it for later, refactor to point all your animations at it to reduce duplicated code, etc.

The UIView class methods are convenience methods for common animations, but are more limited than CATransition. For example, there are only four possible transition types (flip left, flip right, curl up, curl down). If you wanted to do a fade in, you'd have to either dig down to CATransition's fade transition, or set up an explicit animation of your UIView's alpha.

Note that CATransition on Mac OS X will let you specify an arbitrary CoreImage filter to use as a transition, but as it stands now you can't do this on the iPhone, which lacks CoreImage.

How should we manage jdk8 stream for null values

An example how to avoid null e.g. use filter before groupingBy

Filter out the null instances before groupingBy.

Here is an example

MyObjectlist.stream()
            .filter(p -> p.getSomeInstance() != null)
            .collect(Collectors.groupingBy(MyObject::getSomeInstance));

How to get child element by index in Jquery?

You can get first element via index selector:

$('div.second div:eq(0)')

Code: http://jsfiddle.net/RX46D/

MySQL Delete all rows from table and reset ID to zero

if you want to use truncate use this:

SET FOREIGN_KEY_CHECKS = 0; 
TRUNCATE table $table_name; 
SET FOREIGN_KEY_CHECKS = 1;

Why do I get a "Null value was assigned to a property of primitive type setter of" error message when using HibernateCriteriaBuilder in Grails

use Integer as the type and provide setter/getter accordingly..

private Integer num;

public Integer getNum()...

public void setNum(Integer num)...

Memory address of an object in C#

Here's a simple way I came up with that doesn't involve unsafe code or pinning the object. Also works in reverse (object from address):

public static class AddressHelper
{
    private static object mutualObject;
    private static ObjectReinterpreter reinterpreter;

    static AddressHelper()
    {
        AddressHelper.mutualObject = new object();
        AddressHelper.reinterpreter = new ObjectReinterpreter();
        AddressHelper.reinterpreter.AsObject = new ObjectWrapper();
    }

    public static IntPtr GetAddress(object obj)
    {
        lock (AddressHelper.mutualObject)
        {
            AddressHelper.reinterpreter.AsObject.Object = obj;
            IntPtr address = AddressHelper.reinterpreter.AsIntPtr.Value;
            AddressHelper.reinterpreter.AsObject.Object = null;
            return address;
        }
    }

    public static T GetInstance<T>(IntPtr address)
    {
        lock (AddressHelper.mutualObject)
        {
            AddressHelper.reinterpreter.AsIntPtr.Value = address;
            return (T)AddressHelper.reinterpreter.AsObject.Object;
        }
    }

    // I bet you thought C# was type-safe.
    [StructLayout(LayoutKind.Explicit)]
    private struct ObjectReinterpreter
    {
        [FieldOffset(0)] public ObjectWrapper AsObject;
        [FieldOffset(0)] public IntPtrWrapper AsIntPtr;
    }

    private class ObjectWrapper
    {
        public object Object;
    }

    private class IntPtrWrapper
    {
        public IntPtr Value;
    }
}

typeof !== "undefined" vs. != null

If the variable is declared (either with the var keyword, as a function argument, or as a global variable), I think the best way to do it is:

if (my_variable === undefined)

jQuery does it, so it's good enough for me :-)

Otherwise, you'll have to use typeof to avoid a ReferenceError.

If you expect undefined to be redefined, you could wrap your code like this:

(function(undefined){
    // undefined is now what it's supposed to be
})();

Or obtain it via the void operator:

const undefined = void 0;
// also safe

Looping each row in datagridview

You could loop through DataGridView using Rows property, like:

foreach (DataGridViewRow row in datagridviews.Rows)
{
   currQty += row.Cells["qty"].Value;
   //More code here
}

possibly undefined macro: AC_MSG_ERROR

i also had similar problem.. my solution is to

apt-get install libcurl4-openssl-dev

(i had libcurl allready installed ) worked for me at least..

Enum String Name from Value

You can convert the int back to an enumeration member with a simple cast, and then call ToString():

int value = GetValueFromDb();
var enumDisplayStatus = (EnumDisplayStatus)value;
string stringValue = enumDisplayStatus.ToString();

CheckBox in RecyclerView keeps on checking different items

What worked for me is to nullify the listeners on the viewHolder when the view is going to be recycled (onViewRecycled):

 override fun onViewRecycled(holder: AttendeeViewHolder) {
            super.onViewRecycled(holder)
            holder.itemView.hasArrived.setOnCheckedChangeListener(null);
            holder.itemView.edit.setOnClickListener { null }
        }

How to remove a TFS Workspace Mapping?

Follow these steps to remove mapping from TFS:

  1. Open team explorer
  2. Click Source Control
  3. Right click on you project
  4. Click on Remove Mapping

Android: Unable to add window. Permission denied for this window type

For Android API level of 8.0.0, you should use

WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY

instead of

LayoutParams.TYPE_TOAST or TYPE_APPLICATION_PANEL

or SYSTEM_ALERT.

How do I get PHP errors to display?

You can show Php error in your display via simple ways. Firstly, just put this below code in your php.ini file.

display_errors = on;

(if you don't have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1

OR you can also use the following code in your index.php file

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

How can I check if a View exists in a Database?

If you want to check the validity and consistency of all the existing views you can use the following query

declare @viewName sysname
declare @cmd sysname
DECLARE check_cursor CURSOR FOR 
SELECT cast('['+SCHEMA_NAME(schema_id)+'].['+name+']' as sysname) AS viewname
FROM sys.views

OPEN check_cursor
FETCH NEXT FROM check_cursor 
INTO @viewName

WHILE @@FETCH_STATUS = 0
BEGIN

set @cmd='select * from '+@viewName
begin try
exec (@cmd)
end try
begin catch
print 'Error: The view '+@viewName+' is corrupted .'
end catch
FETCH NEXT FROM check_cursor 
INTO @viewName
END 
CLOSE check_cursor;
DEALLOCATE check_cursor;

JQuery Redirect to URL after specified time

You can use

    $(document).ready(function(){
      setTimeout(function() {
       window.location.href = "http://test.example.com/;"
      }, 5000);
    });

Difference between ref and out parameters in .NET

ref and out both allow the called method to modify a parameter. The difference between them is what happens before you make the call.

  • ref means that the parameter has a value on it before going into the function. The called function can read and or change the value any time. The parameter goes in, then comes out

  • out means that the parameter has no official value before going into the function. The called function must initialize it. The parameter only goes out

Here's my favorite way to look at it: ref is to pass variables by reference. out is to declare a secondary return value for the function. It's like if you could write this:

// This is not C#
public (bool, string) GetWebThing(string name, ref Buffer paramBuffer);

// This is C#
public bool GetWebThing(string name, ref Buffer paramBuffer, out string actualUrl);

Here's a more detailed list of the effects of each alternative:

Before calling the method:

ref: The caller must set the value of the parameter before passing it to the called method.

out: The caller method is not required to set the value of the argument before calling the method. Most likely, you shouldn't. In fact, any current value is discarded.

During the call:

ref: The called method can read the argument at any time.

out: The called method must initialize the parameter before reading it.

Remoted calls:

ref: The current value is marshalled to the remote call. Extra performance cost.

out: Nothing is passed to the remote call. Faster.

Technically speaking, you could use always ref in place of out, but out allows you to be more precise about the meaning of the argument, and sometimes it can be a lot more efficient.

Why would anybody use C over C++?

I take the other view: why use C++ instead of C?

The book The C Programming Language (aka: K&R) tells you clearly how to do everything the language can do in under 300 pages. It's a masterpiece of minimalism. No C++ book even comes close.

The obvious counterargument is that the same could be said of most, if not all, modern languages -- they also can't tell you how to do everything in only a few hundred pages. True. So why use C++ instead? Feature richness? Power? If you need something more feature rich or powerful then go with C#, Objective C, Java, or something else like that. Why burden yourself with the complexities of C++? If you need the degree of control C++ grants then I argue to use C. C can do anything and can do it well.

Difference between "module.exports" and "exports" in the CommonJs Module System

Renee's answer is well explained. Addition to the answer with an example:

Node does a lot of things to your file and one of the important is WRAPPING your file. Inside nodejs source code "module.exports" is returned. Lets take a step back and understand the wrapper. Suppose you have

greet.js

var greet = function () {
   console.log('Hello World');
};

module.exports = greet;

the above code is wrapped as IIFE(Immediately Invoked Function Expression) inside nodejs source code as follows:

(function (exports, require, module, __filename, __dirname) { //add by node

      var greet = function () {
         console.log('Hello World');
      };

      module.exports = greet;

}).apply();                                                  //add by node

return module.exports;                                      //add by node

and the above function is invoked (.apply()) and returned module.exports. At this time module.exports and exports pointing to the same reference.

Now, imagine you re-write greet.js as

exports = function () {
   console.log('Hello World');
};
console.log(exports);
console.log(module.exports);

the output will be

[Function]
{}

the reason is : module.exports is an empty object. We did not set anything to module.exports rather we set exports = function()..... in new greet.js. So, module.exports is empty.

Technically exports and module.exports should point to same reference(thats correct!!). But we use "=" when assigning function().... to exports, which creates another object in the memory. So, module.exports and exports produce different results. When it comes to exports we can't override it.

Now, imagine you re-write (this is called Mutation) greet.js (referring to Renee answer) as

exports.a = function() {
    console.log("Hello");
}

console.log(exports);
console.log(module.exports);

the output will be

{ a: [Function] }
{ a: [Function] }

As you can see module.exports and exports are pointing to same reference which is a function. If you set a property on exports then it will be set on module.exports because in JS, objects are pass by reference.

Conclusion is always use module.exports to avoid confusion. Hope this helps. Happy coding :)

JQuery Validate Dropdown list

The documentation for required() states:

To force a user to select an option from a select box, provide an empty options like <option value="">Choose...</option>

By having value="none" in your <option> tag, you are preventing the validation call from ever being made. You can also remove your custom validation rule, simplifying your code. Here's a jsFiddle showing it in action:

http://jsfiddle.net/Kn3v5/

If you can't change the value attribute to the empty string, I don't know what to tell you...I couldn't find any way to get it to validate otherwise.

Having services in React application

The issue becomes extremely simple when you realize that an Angular service is just an object which delivers a set of context-independent methods. It's just the Angular DI mechanism which makes it look more complicated. The DI is useful as it takes care of creating and maintaining instances for you but you don't really need it.

Consider a popular AJAX library named axios (which you've probably heard of):

import axios from "axios";
axios.post(...);

Doesn't it behave as a service? It provides a set of methods responsible for some specific logic and is independent from the main code.

Your example case was about creating an isolated set of methods for validating your inputs (e.g. checking the password strength). Some suggested to put these methods inside the components which for me is clearly an anti-pattern. What if the validation involves making and processing XHR backend calls or doing complex calculations? Would you mix this logic with mouse click handlers and other UI specific stuff? Nonsense. The same with the container/HOC approach. Wrapping your component just for adding a method which will check whether the value has a digit in it? Come on.

I would just create a new file named say 'ValidationService.js' and organize it as follows:

const ValidationService = {
    firstValidationMethod: function(value) {
        //inspect the value
    },

    secondValidationMethod: function(value) {
        //inspect the value
    }
};

export default ValidationService;

Then in your component:

import ValidationService from "./services/ValidationService.js";

...

//inside the component
yourInputChangeHandler(event) {

    if(!ValidationService.firstValidationMethod(event.target.value) {
        //show a validation warning
        return false;
    }
    //proceed
}

Use this service from anywhere you want. If the validation rules change you need to focus on the ValidationService.js file only.

You may need a more complicated service which depends on other services. In this case your service file may return a class constructor instead of a static object so you can create an instance of the object by yourself in the component. You may also consider implementing a simple singleton for making sure that there is always only one instance of the service object in use across the entire application.

jQuery: what is the best way to restrict "number"-only input for textboxes? (allow decimal points)

You dont see alphabets magical appearance and disappearance on key down. This works on mouse paste too.

$('#txtInt').bind('input propertychange', function () {
    $(this).val($(this).val().replace(/[^0-9]/g, ''));
});

Import and insert sql.gz file into database with putty

Creating a Dump File SQL.gz on the current server

$ sudo apt-get install pigz pv

$ pv | mysqldump --user=<yourdbuser> --password=<yourdbpassword> <currentexistingdbname> --single-transaction --routines --triggers --events --quick --opt -Q --flush-logs --allow-keywords --hex-blob --order-by-primary --skip-comments --skip-disable-keys --skip-add-locks --extended-insert --log-error=/var/log/mysql/<dbname>_backup.log | pigz > /path/to/folder/<dbname>_`date +\%Y\%m\%d_\%H\%M`.sql.gz

Optional: Command Arguments for connection

--host=127.0.0.1 / localhost / IP Address of the Dump Server
--port=3306

Importing the dumpfile created above to a different Server

$ sudo apt-get install pigz pv

$ zcat /path/to/folder/<dbname>_`date +\%Y\%m\%d_\%H\%M`.sql.gz | pv | mysql --user=<yourdbuser> --password=<yourdbpassword> --database=<yournewdatabasename> --compress --reconnect --unbuffered --net_buffer_length=1048576 --max_allowed_packet=1073741824 --connect_timeout=36000 --line-numbers --wait --init-command="SET GLOBAL net_buffer_length=1048576;SET GLOBAL max_allowed_packet=1073741824;SET FOREIGN_KEY_CHECKS=0;SET UNIQUE_CHECKS = 0;SET AUTOCOMMIT = 1;FLUSH NO_WRITE_TO_BINLOG QUERY CACHE, STATUS, SLOW LOGS, GENERAL LOGS, ERROR LOGS, ENGINE LOGS, BINARY LOGS, LOGS;"

Optional: Command Arguments for connection

--host=127.0.0.1 / localhost / IP Address of the Import Server
--port=3306

mysql: [Warning] Using a password on the command line interface can be insecure. 1.0GiB 00:06:51 [8.05MiB/s] [<=> ]

The optional software packages are helpful to import your database SQL file faster

  • with a progress view (pv)
  • Parallel gzip (pigz/unpigz) to gzip/gunzip files in parallel

for faster zipping of the output

connecting MySQL server to NetBeans

Follow these 2 steps:

STEP 1 :

Follow these steps using the Services Tab:

  1. Right click on Database
  2. Create new Connection

Customize the New COnnection as follows:

  1. Connector Name: MYSQL (Connector/J Driver)
  2. Host: localhost
  3. Port: 3306
  4. Database: mysql ( mysql is the default or enter your database name)
  5. Username: enter your database username
  6. Password: enter your database password
  7. JDBC URL: jdbc:mysql://localhost:3306/mysql
  8. CLick Finish button

NB: DELETE the ?zeroDateTimeBehaviour=convertToNull part in the URL. Instead of mysql in the URL, you should see your database name)


STEP 2 :

  1. Right click on MySQL Server at localhost:3306:[username](...)
  2. Select Properties... from the shortcut menu

In the "MySQL Server Properties" dialog select the "Admin Properties" tab Enter the following in the textboxes specified:

For Linux users :

  1. Path to start command: /usr/bin/mysql
  2. Arguments: /etc/init.d/mysql start
  3. Path to Stop command: /usr/bin/mysql
  4. Arguments: /etc/init.d/mysql stop

For MS Windows users :

NOTE: Optional:

In the Path/URL to admin tool field, type or browse to the location of your MySQL Administration application such as the MySQL Admin Tool, PhpMyAdmin, or other web-based administration tools.

Note: mysqladmin is the MySQL admin tool found in the bin folder of the MySQL installation directory. It is a command-line tool and not ideal for use with the IDE.

Citations:
https://netbeans.org/kb/docs/ide/mysql.html?print=yes
http://javawebaction.blogspot.com/2013/04/how-to-register-mysql-database-server.html


We will use MySQL Workbench in this example. Please use the path of your installation if you have MySQL workbench and the path to MySQL.

  1. Path/URL to admin tool: C:\Program Files\MySQL\MySQL Workbench CE 5.2.47\MySQLWorkbench.exe
  2. Arguments: (Leave blank)
  3. Path to start command: C:\mysql\bin\mysqld (OR C:\mysql\bin\mysqld.exe)
  4. Arguments: (Leave blank)
  5. Path to Stop command: C:\mysql\bin\mysqladmin (OR C:\mysql\bin\mysqladmin.exe )
  6. Arguments: -u root shutdown (Try -u root stop)

Possible exampes of MySQL bin folder locations for Windows Users:

  • C:\mysql\bin
  • C:\Program Files\MySQL\MySQL Server 5.1\bin\
  • Installation Folder: ~\xampp\mysql\bin

Android Animation Alpha

Kotlin Version

Simply use ViewPropertyAnimator like this:

iv.alpha = 0.2f
iv.animate().apply {
    interpolator = LinearInterpolator()
    duration = 500
    alpha(1f)
    startDelay = 1000
    start()
}

How to merge lists into a list of tuples?

The output which you showed in problem statement is not the tuple but list

list_c = [(1,5), (2,6), (3,7), (4,8)]

check for

type(list_c)

considering you want the result as tuple out of list_a and list_b, do

tuple(zip(list_a,list_b)) 

What do curly braces mean in Verilog?

The curly braces mean concatenation, from most significant bit (MSB) on the left down to the least significant bit (LSB) on the right. You are creating a 32-bit bus (result) whose 16 most significant bits consist of 16 copies of bit 15 (the MSB) of the a bus, and whose 16 least significant bits consist of just the a bus (this particular construction is known as sign extension, which is needed e.g. to right-shift a negative number in two's complement form and keep it negative rather than introduce zeros into the MSBits).

There is a tutorial here*, but it doesn't explain too much more than the above paragraph.

For what it's worth, the nested curly braces around a[15:0] are superfluous.

*Beware: the example within the tutorial link contains a typo when demonstrating multiple concatenations - the (2{C}} should be a {2{2}}.

Check if key exists and iterate the JSON array using Python

You can use a try-except

try:
   print(str.to.id)
except AttributeError: # Not a Retweet
   print('null')

hibernate - get id after save object

Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned

Integer id = (Integer)session.save(ticket);

Symbol for any number of any characters in regex?

I would use .*. . matches any character, * signifies 0 or more occurrences. You might need a DOTALL switch to the regex to capture new lines with ..

Prevent form redirect OR refresh on submit?

Just handle the form submission on the submit event, and return false:

$('#contactForm').submit(function () {
 sendContactForm();
 return false;
});

You don't need any more the onclick event on the submit button:

<input class="submit" type="submit" value="Send" />

Centering Bootstrap input fields

For bootstrap 4 use offset-4, see below.

<div class="mx-auto">        
        <form class="mx-auto" action="/campgrounds" method="POST">
            <div class="form-group row">                
                <div class="col-sm-4 offset-4">
                    <input class="form-control" type="text" name="name" placeholder="name">
                </div>
            </div>
            <div class="form-group row">               
                <div class="col-sm-4 offset-4">
                    <input class="form-control" type="text" name="picture" placeholder="image url">
                </div>
            </div>
            <div class="form-group row">
                    <div class="col-sm-4 offset-4">
                        <input class="form-control" type="text" name="description" placeholder="description">
                    </div>
                </div>
            <button class="btn btn-primary" type="submit">Submit!</button>
            <a class="btn btn-secondary"  href="/campgrounds">Go Back</a>
        </form>      
    </div>

Delete branches in Bitbucket

Try this command, it will purge all branches that have been merged to the develop branch.

for i in `git branch -r --merged origin/develop| grep origin | grep -v '>' \
   | grep -v master | grep -v develop | sed -E "s|^ *origin/||g"`; \
do \
   git push origin $i --delete; \
done

Get list of passed arguments in Windows batch script (.bat)

The following code simulates an array ('params') - takes the parameters received by the script and stores them in the variables params_1 .. params_n, where n=params_0=the number of elements of the array:

@echo off

rem Storing the program parameters into the array 'params':
rem Delayed expansion is left disabled in order not to interpret "!" in program parameters' values;
rem however, if a parameter is not quoted, special characters in it (like "^", "&", "|") get interpreted at program launch
set /a count=0
:repeat
    set /a count+=1
    set "params_%count%=%~1"
    shift
    if defined params_%count% (
        goto :repeat
    ) else (
        set /a count-=1
    )    
set /a params_0=count

rem Printing the program parameters stored in the array 'params':
rem After the variables params_1 .. params_n are set with the program parameters' values, delayed expansion can
rem be enabled and "!" are not interpreted in the variables params_1 .. params_n values
setlocal enabledelayedexpansion
    for /l %%i in (1,1,!params_0!) do (
        echo params_%%i: "!params_%%i!"
    )
endlocal

pause
goto :eof

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

If you want to delete file first close all the connections and streams. after that delete the file.

Why would one mark local variables and method parameters as "final" in Java?

Why would you want to? You wrote the method, so anyone modifying it could always remove the final keyword from qwerty and reassign it. As for the method signature, same reasoning, although I'm not sure what it would do to subclasses of your class... they may inherit the final parameter and even if they override the method, be unable to de-finalize x. Try it and find out if it would work.

The only real benefit, then, is if you make the parameter immutable and it carries over to the children. Otherwise, you're just cluttering your code for no particularly good reason. If it won't force anyone to follow your rules, you're better off just leaving a good comment as you why you shouldn't change that parameter or variable instead of giving if the final modifier.

Edit

In response to a comment, I will add that if you are seeing performance issues, making your local variables and parameters final can allow the compiler to optimize your code better. However, from the perspective of immutability of your code, I stand by my original statement.

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

Use Moment.js (https://momentjs.com/)

moment().isDST(); will give you if Day light savings is observed.

Also it has helper function to calculate relative time for you. You don't need to do manual calculations e.g moment("20200105", "YYYYMMDD").fromNow();

Does java.util.List.isEmpty() check if the list itself is null?

No java.util.List.isEmpty() doesn't check if a list is null.

If you are using Spring framework you can use the CollectionUtils class to check if a list is empty or not. It also takes care of the null references. Following is the code snippet from Spring framework's CollectionUtils class.

public static boolean isEmpty(Collection<?> collection) {
    return (collection == null || collection.isEmpty());
}

Even if you are not using Spring, you can go on and tweak this code to add in your AppUtil class.

How to catch a unique constraint error in a PL/SQL block?

I suspect the condition you are looking for is DUP_VAL_ON_INDEX

EXCEPTION
    WHEN DUP_VAL_ON_INDEX THEN
        DBMS_OUTPUT.PUT_LINE('OH DEAR. I THINK IT IS TIME TO PANIC!')

Best way to remove from NSMutableArray while iterating?

Iterating backwards-ly was my favourite for years , but for a long time I never encountered the case where the 'deepest' ( highest count) object was removed first. Momentarily before the pointer moves on to the next index there ain't anything and it crashes.

Benzado's way is the closest to what i do now but I never realised there would be the stack reshuffle after every remove.

under Xcode 6 this works

NSMutableArray *itemsToKeep = [NSMutableArray arrayWithCapacity:[array count]];

    for (id object in array)
    {
        if ( [object isNotEqualTo:@"whatever"]) {
           [itemsToKeep addObject:object ];
        }
    }
    array = nil;
    array = [[NSMutableArray alloc]initWithArray:itemsToKeep];

Duplicate and rename Xcode project & associated folders

I'm posting this since I have always been struggling when renaming a project in XCode.

Renaming the project is good and simple but this doesn't rename the source folder. Here is a step by step of what I have done that worked great in Xcode 4 and 5 thanks to the links below.

REF links:
Rename Project.
Rename Source Folder and other files.

1- Backup your project.

If you are using git, commit any changes, make a copy of the entire project folder and backup in time machine before making any changes (this step is not required but I highly recommended).

2- Open your project.

3- Slow double click or hit enter on the Project name (blue top icon) and rename it to whatever you like.

NOTE: After you rename the project and press ‘enter’ it will suggest to automatically change all project-name-related entries and will allow you to de-select some of them if you want. Select all of them and click ok.

4- Rename the Scheme

a) Click the menu right next to the stop button and select Manage Schemes.

b) Single-slow-click or hit enter on the old name scheme and rename it to whatever you like.

c) Click ok.

5 - Build and run to make sure it works.

NOTES: At this point all of the important project files should be renamed except the comments in the classes created when the project was created nor the source folder. Next we will rename the folder in the file system.

6- Close the project.

7- Rename the main and the source folder.

8- Right click the project bundle .xcodeproj file and select “Show Package Contents” from the context menu. Open the .pbxproj file with any text editor.

9- Search and replace any occurrence of the original folder name with the new folder name.

10- Save the file.

11- Open XCode project, test it.

12- Done.

EDIT 10/11/19:

There is a tool to rename projects in Xcode I haven't tried it enough to comment on it. https://github.com/appculture/xcode-project-renamer

Difference between style = "position:absolute" and style = "position:relative"

Relative:

  1. An element with position: relative; is positioned relative to its normal position.

  2. If you add no positioning attributes (top, left, bottom or right) on a relative element it will have no effect on it's positioning at all. It will behave exactly as a position: static element.

  3. But if you do add some other positioning attribute, say, top: 10px;, it will shift its position 10 pixels down from where it would normally be.

  4. An element with this type of positioning gets affected by other elements and it itself also affects others.

Absolute:

  1. An element with position: absolute; allows you to place any element exactly where you want it to be. You use the positioning attributes top, left, bottom. and right to set the location.

  2. It is placed relative to the nearest non-static ancestor. If there is no such container, it is placed relative to the page itself.

  3. It gets removed from the normal flow of elements on the page.

  4. An element with this type of positioning is not affected by other elements and also it doesn't affect flow of other elements.

See this self-explanatory example for better clarity. https://codepen.io/nyctophiliac/pen/BJMqjX

How to assign name for a screen?

The easiest way use screen with name

screen -S 'name' 'application'
  • Ctrl+a, d = exit and leave application open

Return to screen:

screen -r 'name'

for example using lynx with screen

Create screen:

screen -S lynx lynx

Ctrl+a, d =exit

later you can return with:

screen -r lynx

Inserting image into IPython notebook markdown

You can find your current working directory by 'pwd' command in jupyter notebook without quotes.

How do I enumerate through a JObject?

If you look at the documentation for JObject, you will see that it implements IEnumerable<KeyValuePair<string, JToken>>. So, you can iterate over it simply using a foreach:

foreach (var x in obj)
{
    string name = x.Key;
    JToken value = x.Value;
    …
}

PHP: How to check if image file exists?

if(@getimagesize($image_path)){
 ...}

Is working for me.

How to extract table as text from the PDF using Python?

  • I would suggest you to extract the table using tabula.
  • Pass your pdf as an argument to the tabula api and it will return you the table in the form of dataframe.
  • Each table in your pdf is returned as one dataframe.
  • The table will be returned in a list of dataframea, for working with dataframe you need pandas.

This is my code for extracting pdf.

import pandas as pd
import tabula
file = "filename.pdf"
path = 'enter your directory path here'  + file
df = tabula.read_pdf(path, pages = '1', multiple_tables = True)
print(df)

Please refer to this repo of mine for more details.

How to get Top 5 records in SqLite?

Select TableName.* from  TableName DESC LIMIT 5

Multi-Line Comments in Ruby?

In case someone is looking for a way to comment multiple lines in a html template in Ruby on Rails, there might be a problem with =begin =end, for instance:

<%
=begin
%>
  ... multiple HTML lines to comment out
  <%= image_tag("image.jpg") %>
<%
=end
%>

will fail because of the %> closing the image_tag.

In this case, maybe it is arguable whether this is commenting out or not, but I prefer to enclose the undesired section with an "if false" block:

<% if false %>
  ... multiple HTML lines to comment out
  <%= image_tag("image.jpg") %>
<% end %>

This will work.

How to create the branch from specific commit in different branch

You can do this locally as everyone mentioned using

git checkout -b <branch-name> <sha1-of-commit>

Alternatively, you can do this in github itself, follow the steps:

1- In the repository, click on the Commits.

2- on the commit you want to branch from, click on <> to browse the repository at this point in the history.

commits history

3- Click on the tree: xxxxxx in the upper left. Just type in a new branch name there click Create branch xxx as shown below.

create new branch

Now you can fetch the changes from that branch locally and continue from there.

Bash scripting missing ']'

If you created your script on windows and want to run it on linux machine, and you're sure there is no mistake in your code, install dos2unix on linux machine and run dos2unix yourscript.sh. Then, run the script.

Xcode 'CodeSign error: code signing is required'

In my case, locking and unlocking login-keychain from Keychain Access did the trick enter image description here

How to handle errors with boto3?

Just an update to the 'no exceptions on resources' problem as pointed to by @jarmod (do please feel free to update your answer if below seems applicable)

I have tested the below code and it runs fine. It uses 'resources' for doing things, but catches the client.exceptions - although it 'looks' somewhat wrong... it tests good, the exception classes are showing and matching when looked into using debugger at exception time...

It may not be applicable to all resources and clients, but works for data folders (aka s3 buckets).

lab_session = boto3.Session() 
c = lab_session.client('s3') #this client is only for exception catching

try:
    b = s3.Bucket(bucket)
    b.delete()
except c.exceptions.NoSuchBucket as e:
    #ignoring no such bucket exceptions
    logger.debug("Failed deleting bucket. Continuing. {}".format(e))
except Exception as e:
    #logging all the others as warning
    logger.warning("Failed deleting bucket. Continuing. {}".format(e))

Hope this helps...

writing a batch file that opens a chrome URL

@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://tweetdeck.twitter.com/"

@ECHO OFF
"c:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --app="https://web.whatsapp.com/"

What is the syntax for Typescript arrow functions with generics?

In case you'd like to do it with async:

const request = async <T>(param1: string, param2: number) => {
  const res = await func();
  return res.response() as T;
}

And a more complex pattern, in case you'd like to wrap your function inside a generic counterpart, such as memoization (Example uses fast-memoize):

const request = memoize(
  async <T>(
    url: string,
    token?: string
  ) => {
    // Perform your code here
  }
);

See how you define the generic after the memoizing function.

How do I delete everything in Redis?

If you are using Java then from the documentation, you can use any one of them based on your use case.

/**
 * Remove all keys from all databases.
 *
 * @return String simple-string-reply
 */
String flushall();

/**
 * Remove all keys asynchronously from all databases.
 *
 * @return String simple-string-reply
 */
String flushallAsync();

/**
 * Remove all keys from the current database.
 *
 * @return String simple-string-reply
 */
String flushdb();

/**
 * Remove all keys asynchronously from the current database.
 *
 * @return String simple-string-reply
 */
String flushdbAsync();

Code:

RedisAdvancedClusterCommands syncCommands = // get sync() or async() commands 
syncCommands.flushdb();

Read more: https://github.com/lettuce-io/lettuce-core/wiki/Redis-Cluster

CSS / HTML Navigation and Logo on same line

Firstly, let's use some semantic HTML.

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <ul>
        <li><a href="#">Home</a></li>
        <li><a href="#">Projects</a></li>
        <li><a href="#">About</a></li>
        <li><a href="#">Services</a></li>
        <li><a href="#">Get in Touch</a></li>
    </ul>
</nav>

In fact, you can even get away with the more minimalist:

<nav class="navigation-bar">
    <img class="logo" src="logo.png">
    <a href="#">Home</a>
    <a href="#">Projects</a>
    <a href="#">About</a>
    <a href="#">Services</a>
    <a href="#">Get in Touch</a>
</nav>

Then add some CSS:

.navigation-bar {
    width: 100%;  /* i'm assuming full width */
    height: 80px; /* change it to desired width */
    background-color: red; /* change to desired color */
}
.logo {
    display: inline-block;
    vertical-align: top;
    width: 50px;
    height: 50px;
    margin-right: 20px;
    margin-top: 15px;    /* if you want it vertically middle of the navbar. */
}
.navigation-bar > a {
    display: inline-block;
    vertical-align: top;
    margin-right: 20px;
    height: 80px;        /* if you want it to take the full height of the bar */
    line-height: 80px;    /* if you want it vertically middle of the navbar */
}

Obviously, the actual margins, heights and line-heights etc. depend on your design.

Other options are to use tables or floats for layout, but these are generally frowned upon.

Last but not least, I hope you get cured of div-itis.

Add new attribute (element) to JSON object using JavaScript

var jsonObj = {
    members: 
           {
            host: "hostName",
            viewers: 
            {
                user1: "value1",
                user2: "value2",
                user3: "value3"
            }
        }
}

var i;

for(i=4; i<=8; i++){
    var newUser = "user" + i;
    var newValue = "value" + i;
    jsonObj.members.viewers[newUser] = newValue ;

}

console.log(jsonObj);

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

How to change resolution (DPI) of an image?

You have to copy the bits over a new image with the target resolution, like this:

    using (Bitmap bitmap = (Bitmap)Image.FromFile("file.jpg"))
    {
        using (Bitmap newBitmap = new Bitmap(bitmap))
        {
            newBitmap.SetResolution(300, 300);
            newBitmap.Save("file300.jpg", ImageFormat.Jpeg);
        }
    }

Convert string to symbol-able in ruby

Rails got ActiveSupport::CoreExtensions::String::Inflections module that provides such methods. They're all worth looking at. For your example:

'Book Author Title'.parameterize.underscore.to_sym # :book_author_title

How to have a default option in Angular.js select box

I needed the default “Please Select” to be unselectable. I also needed to be able to conditionally set a default selected option.

I achieved this the following simplistic way: JS code: // Flip these 2 to test selected default or no default with default “Please Select” text //$scope.defaultOption = 0; $scope.defaultOption = { key: '3', value: 'Option 3' };

$scope.options = [
   { key: '1', value: 'Option 1' },
   { key: '2', value: 'Option 2' },
   { key: '3', value: 'Option 3' },
   { key: '4', value: 'Option 4' }
];

getOptions();

function getOptions(){
    if ($scope.defaultOption != 0)
    { $scope.options.selectedOption = $scope.defaultOption; }
}

HTML:

<select name="OptionSelect" id="OptionSelect" ng-model="options.selectedOption" ng-options="item.value for item in options track by item.key">
<option value="" disabled selected style="display: none;"> -- Please Select -- </option>
</select>
<h1>You selected: {{options.selectedOption.key}}</h1>         

I hope this helps someone else that has similar requirements.

The "Please Select" was accomplished through Joffrey Outtier's answer here.

Mysql service is missing

Go to

C:\Program Files\MySQL\MySQL Server 5.2\bin

then Open MySQLInstanceConfig file

then complete the wizard.

Click finish

Solve the problem

I think this is the best way to change the port number also.

It works for me

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

If we are using the UIImagePickerController as a property, then this warning will disappear. assume that we are not using the result from the UIImagePickerController , if we are instantiating the UIImagePickerController within a function.

VBA - If a cell in column A is not blank the column B equals

Another way (Using Formulas in VBA). I guess this is the shortest VBA code as well?

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long

    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("B1:B" & lRow).Formula = "=If(A1<>"""",""My Text"","""")"
        .Range("B1:B" & lRow).Value = .Range("B1:B" & lRow).Value
    End With
End Sub

Failed to instantiate module error in Angular js

You need to include angular-route.js in your HTML:

<script src="angular-route.js">

http://docs.angularjs.org/api/ngRoute

Preloading images with JavaScript

Try this I think this is better.

var images = [];
function preload() {
    for (var i = 0; i < arguments.length; i++) {
        images[i] = new Image();
        images[i].src = preload.arguments[i];
    }
}

//-- usage --//
preload(
    "http://domain.tld/gallery/image-001.jpg",
    "http://domain.tld/gallery/image-002.jpg",
    "http://domain.tld/gallery/image-003.jpg"
)

Source: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

"You may need an appropriate loader to handle this file type" with Webpack and Babel

If you are using Webpack > 3 then you only need to install babel-preset-env, since this preset accounts for es2015, es2016 and es2017.

var path = require('path');
let webpack = require("webpack");

module.exports = {
    entry: {
        app: './app/App.js',
        vendor: ["react","react-dom"]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '../public')
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader?cacheDirectory=true',
            }
        }]
    }
};

This picks up its configuration from my .babelrc file:

{
    "presets": [
        [
            "env",
            {
                "targets": {
                    "browsers":["last 2 versions"],
                    "node":"current"
                }
            }
        ],["react"]
    ]
}

How to get full width in body element

If its in a landscape then you will be needing more width and less height! That's just what all websites have.

Lets go with a basic first then the rest!

The basic CSS:

By CSS you can do this,

#body {
width: 100%;
height: 100%;
}

Here you are using a div with id body, as:

<body>
  <div id="body>
    all the text would go here!
  </div>
</body>

Then you can have a web page with 100% height and width.

What if he tries to resize the window?

The issues pops up, what if he tries to resize the window? Then all the elements inside #body would try to mess up the UI. For that you can write this:

#body {
height: 100%;
width: 100%;
}

And just add min-height max-height min-width and max-width.

This way, the page element would stay at the place they were at the page load.

Using JavaScript:

Using JavaScript, you can control the UI, use jQuery as:

$('#body').css('min-height', '100%');

And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.

How to not add scroll to the web page:

If you are not trying to add a scroll, then you can use this JS

$('#body').css('min-height', screen.height); // or anyother like window.height

This way, the document will get a new height whenever the user would load the page.

Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!

Tip: So try using JS to find current Screen size and edit the page! :)

how to check if item is selected from a comboBox in C#

You seem to be using Windows Forms. Look at the SelectedIndex or SelectedItem properties.

if (this.combo1.SelectedItem == MY_OBJECT)
{
    // do stuff
}

Run certain code every n seconds

You can start a separate thread whose sole duty is to count for 5 seconds, update the file, repeat. You wouldn't want this separate thread to interfere with your main thread.

Best way to reverse a string

If you want to play a really dangerous game, then this is by far the fastest way there is (around four times faster than the Array.Reverse method). It's an in-place reverse using pointers.

Note that I really do not recommend this for any use, ever (have a look here for some reasons why you should not use this method), but it's just interesting to see that it can be done, and that strings aren't really immutable once you turn on unsafe code.

public static unsafe string Reverse(string text)
{
    if (string.IsNullOrEmpty(text))
    {
        return text;
    }

    fixed (char* pText = text)
    {
        char* pStart = pText;
        char* pEnd = pText + text.Length - 1;
        for (int i = text.Length / 2; i >= 0; i--)
        {
            char temp = *pStart;
            *pStart++ = *pEnd;
            *pEnd-- = temp;
        }

        return text;
    }
}

Sass nth-child nesting

You're trying to do &(2), &(4) which won't work

#romtest {
  .detailed {
    th {
      &:nth-child(2) {//your styles here}
      &:nth-child(4) {//your styles here}
      &:nth-child(6) {//your styles here}
      }
  }
}

Strings in C, how to get subString

Doing it all in two fell swoops:

char *otherString = strncpy((char*)malloc(6), someString);
otherString[5] = 0;

If/else else if in Jquery for a condition

If statement for images in jquery:
#html

<button id="chain">Chain</button>
<img src="bulb_on.jpg" alt="img" id="img"/>

#script
    <script>
        $(document).ready(function(){
            $("#chain").click(function(){
            if($("#img").attr('src')!='bulb_on.jpg'){
                $("#img").attr('src', 'bulb_on.jpg');
            }
            else
            {
                $("#img").attr('src', 'bulb_onn.jpg');
            }
            });
        });
    </script>

Convert Rtf to HTML

You can try to upload it to google docs, and download it as HTML.

How to avoid "StaleElementReferenceException" in Selenium?

Clean findByAndroidId method that gracefully handles StaleElementReference.

This is heavily based off of jspcal's answer but I had to modify that answer to get it working cleanly with our setup and so I wanted to add it here in case it's helpful to others. If this answer helped you, please go upvote jspcal's answer.

// This loops gracefully handles StateElementReference errors and retries up to 10 times. These can occur when an element, like a modal or notification, is no longer available.
export async function findByAndroidId( id, { assert = wd.asserters.isDisplayed, timeout = 10000, interval = 100 } = {} ) {
  MAX_ATTEMPTS = 10;
  let attempt = 0;

  while( attempt < MAX_ATTEMPTS ) {
    try {
      return await this.waitForElementById( `android:id/${ id }`, assert, timeout, interval );
    }
    catch ( error ) {
      if ( error.message.includes( "StaleElementReference" ) )
        attempt++;
      else
        throw error; // Re-throws the error so the test fails as normal if the assertion fails.
    }
  }
}

Can a WSDL indicate the SOAP version (1.1 or 1.2) of the web service?

SOAP 1.1 uses namespace http://schemas.xmlsoap.org/wsdl/soap/

SOAP 1.2 uses namespace http://schemas.xmlsoap.org/wsdl/soap12/

The wsdl is able to define operations under soap 1.1 and soap 1.2 at the same time in the same wsdl. Thats useful if you need to evolve your wsdl to support new functionality that requires soap 1.2 (eg. MTOM), in this case you dont need to create a new service but just evolve the original one.

Creating an array of objects in Java

The genaral form to declare a new array in java is as follows:

type arrayName[] = new type[numberOfElements];

Where type is a primitive type or Object. numberOfElements is the number of elements you will store into the array and this value can’t change because Java does not support dynamic arrays (if you need a flexible and dynamic structure for holding objects you may want to use some of the Java collections).

Lets initialize an array to store the salaries of all employees in a small company of 5 people:

int salaries[] = new int[5];

The type of the array (in this case int) applies to all values in the array. You can not mix types in one array.

Now that we have our salaries array initialized we want to put some values into it. We can do this either during the initialization like this:

int salaries[] = {50000, 75340, 110500, 98270, 39400};

Or to do it at a later point like this:

salaries[0] = 50000;
salaries[1] = 75340;
salaries[2] = 110500;
salaries[3] = 98270;
salaries[4] = 39400;

More visual example of array creation: enter image description here

To learn more about Arrays, check out the guide.

Android - get children inside a View?

As an update for those who come across this question after 2018, if you are using Kotlin, you can simply use the Android KTX extension property ViewGroup.children to get a sequence of the View's immediate children.

Running Python code in Vim

This .vimrc mapping needs Conque Shell, but it replicates Geany (and other X editors') behaviour:

  • Press a key to execute
  • Executes in gnome-terminal
  • Waits for confirmation to exit
  • Window closes automatically on exit

    :let dummy = conque_term#subprocess('gnome-terminal -e "bash -c \"python ' . expand("%") . '; answer=\\\"z\\\"; while [ $answer != \\\"q\\\" ]; do printf \\\"\nexited with code $?, press (q) to quit: \\\"; read -n 1 answer; done; \" "')

How can I style an Android Switch?

It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio

A good description of all the tools are at AndroidOnRocks.com (site offline now)

However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick

Platform.runLater and Task in JavaFX

Use Platform.runLater(...) for quick and simple operations and Task for complex and big operations .

Example: Why Can't we use Platform.runLater(...) for long calculations (Taken from below reference).

Problem: Background thread which just counts from 0 to 1 million and update progress bar in UI.

Code using Platform.runLater(...):

final ProgressBar bar = new ProgressBar();
new Thread(new Runnable() {
    @Override public void run() {
    for (int i = 1; i <= 1000000; i++) {
        final int counter = i;
        Platform.runLater(new Runnable() {
            @Override public void run() {
                bar.setProgress(counter / 1000000.0);
            }
        });
    }
}).start();

This is a hideous hunk of code, a crime against nature (and programming in general). First, you’ll lose brain cells just looking at this double nesting of Runnables. Second, it is going to swamp the event queue with little Runnables — a million of them in fact. Clearly, we needed some API to make it easier to write background workers which then communicate back with the UI.

Code using Task :

Task task = new Task<Void>() {
    @Override public Void call() {
        static final int max = 1000000;
        for (int i = 1; i <= max; i++) {
            updateProgress(i, max);
        }
        return null;
    }
};

ProgressBar bar = new ProgressBar();
bar.progressProperty().bind(task.progressProperty());
new Thread(task).start();

it suffers from none of the flaws exhibited in the previous code

Reference : Worker Threading in JavaFX 2.0

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Is there an XSL "contains" directive?

Use the standard XPath function contains().

Function: boolean contains(string, string)

The contains function returns true if the first argument string contains the second argument string, and otherwise returns false

Difference between text and varchar (character varying)

On PostgreSQL manual

There is no performance difference among these three types, apart from increased storage space when using the blank-padded type, and a few extra CPU cycles to check the length when storing into a length-constrained column. While character(n) has performance advantages in some other database systems, there is no such advantage in PostgreSQL; in fact character(n) is usually the slowest of the three because of its additional storage costs. In most situations text or character varying should be used instead.

I usually use text

References: http://www.postgresql.org/docs/current/static/datatype-character.html

How can I declare enums using java

public enum NewEnum {
   ONE("test"),
   TWO("test");

   private String s;

   private NewEnum(String s) {
      this.s = s);
   }

    public String getS() {
        return this.s;
    }
}

Get filename in batch for loop

If you want to remain both filename (only) and extension, you may use %~nxF:

FOR /R C:\Directory %F in (*.*) do echo %~nxF

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

How to reload .bashrc settings without logging out and back in again?

Depending on your environment, just typing

bash

may also work.

docker build with --build-arg with multiple arguments

Use --build-arg with each argument.

If you are passing two argument then add --build-arg with each argument like:

docker build \
-t essearch/ess-elasticsearch:1.7.6 \
--build-arg number_of_shards=5 \
--build-arg number_of_replicas=2 \
--no-cache .

C# how to change data in DataTable?

You should probably set the property dt.Columns["columnName"].ReadOnly = false; before.

How to get value by key from JObject?

This should help -

var json = "{'@STARTDATE': '2016-02-17 00:00:00.000',  '@ENDDATE': '2016-02-18 23:59:00.000' }";
var fdate = JObject.Parse(json)["@STARTDATE"];

CodeIgniter: Unable to connect to your database server using the provided settings Error Message

Today I fallen this kind of problem in live server and i solved the problem changing this line

$db['default']['db_debug'] = TRUE;

to

$db['default']['db_debug'] = FALSE;

How to enter a formula into a cell using VBA?

You aren't building your formula right.

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

Also, you want to have the = at the beginning of the formala.

Add custom header in HttpWebRequest

You use the Headers property with a string index:

request.Headers["X-My-Custom-Header"] = "the-value";

According to MSDN, this has been available since:

  • Universal Windows Platform 4.5
  • .NET Framework 1.1
  • Portable Class Library
  • Silverlight 2.0
  • Windows Phone Silverlight 7.0
  • Windows Phone 8.1

https://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers(v=vs.110).aspx

How to capture no file for fs.readFileSync()?

Try using Async instead to avoid blocking the only thread you have with NodeJS. Check this example:

const util = require('util');
const fs = require('fs');
const path = require('path');
const readFileAsync = util.promisify(fs.readFile);

const readContentFile = async (filePath) => {
  // Eureka, you are using good code practices here!
  const content = await readFileAsync(path.join(__dirname, filePath), {
    encoding: 'utf8'
  })
  return content;
}

Later can use this async function with try/catch from any other function:

const anyOtherFun = async () => {
  try {
    const fileContent = await readContentFile('my-file.txt');
  } catch (err) {
    // Here you get the error when the file was not found,
    // but you also get any other error
  }
}

Happy Coding!

Redirect to specified URL on PHP script completion?

<?php

// do something here

header("Location: http://example.com/thankyou.php");
?>

How to parse a String containing XML in Java and retrieve the value of the root node?

You could do this with JAXB (an implementation is included in Java SE 6).

import java.io.StringReader;
import javax.xml.bind.*;
import javax.xml.transform.stream.StreamSource;

public class Demo {

    public static void main(String[] args) throws Exception {
        String xmlString = "<message>HELLO!</message> ";
        JAXBContext jc = JAXBContext.newInstance(String.class);
        Unmarshaller unmarshaller = jc.createUnmarshaller();
        StreamSource xmlSource = new StreamSource(new StringReader(xmlString));
        JAXBElement<String> je = unmarshaller.unmarshal(xmlSource, String.class);
        System.out.println(je.getValue());
    }

}

Output

HELLO!

PostgreSQL visual interface similar to phpMyAdmin?

I would also highly recommend Adminer - http://www.adminer.org/

It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.

How to list files inside a folder with SQL Server

Very easy, just use the SQLCMD-syntax.

Remember to enable SQLCMD-mode in the SSMS, look under Query -> SQLCMD Mode

Try execute:

!!DIR
!!:GO

or maybe:
!!DIR "c:/temp"
!!:GO

How to get post slug from post in WordPress?

Best option to do this according to WP Codex is as follow.

Use the global variable $post:

<?php 
    global $post;
    $post_slug = $post->post_name;
?>

Angularjs loading screen on ajax request

Typescript and Angular Implementation

directive

((): void=> {
    "use strict";
    angular.module("app").directive("busyindicator", busyIndicator);
    function busyIndicator($http:ng.IHttpService): ng.IDirective {
        var directive = <ng.IDirective>{
            restrict: "A",
            link(scope: Scope.IBusyIndicatorScope) {
                scope.anyRequestInProgress = () => ($http.pendingRequests.length > 0);
                scope.$watch(scope.anyRequestInProgress, x => {            
                    if (x) {
                        scope.canShow = true;
                    } else {
                        scope.canShow = false;
                    }
                });
            }
        };
        return directive;
    }
})();

Scope

   module App.Scope {
        export interface IBusyIndicatorScope extends angular.IScope {
            anyRequestInProgress: any;
            canShow: boolean;
        }
    }  

Template

<div id="activityspinner" ng-show="canShow" class="show" data-busyindicator>
</div>

CSS
#activityspinner
{
    display : none;
}
#activityspinner.show {
    display : block;
    position : fixed;
    z-index: 100;
    background-image : url('data:image/gif;base64,R0lGODlhNgA3APMAAPz8/GZmZqysrHV1dW1tbeXl5ZeXl+fn59nZ2ZCQkLa2tgAAAAAAAAAAAAAAAAAAACH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAANgA3AAAEzBDISau9OOvNu/9gKI5kaZ4lkhBEgqCnws6EApMITb93uOqsRC8EpA1Bxdnx8wMKl51ckXcsGFiGAkamsy0LA9pAe1EFqRbBYCAYXXUGk4DWJhZN4dlAlMSLRW80cSVzM3UgB3ksAwcnamwkB28GjVCWl5iZmpucnZ4cj4eWoRqFLKJHpgSoFIoEe5ausBeyl7UYqqw9uaVrukOkn8LDxMXGx8ibwY6+JLxydCO3JdMg1dJ/Is+E0SPLcs3Jnt/F28XXw+jC5uXh4u89EQAh+QQJCgAAACwAAAAANgA3AAAEzhDISau9OOvNu/9gKI5kaZ5oqhYGQRiFWhaD6w6xLLa2a+iiXg8YEtqIIF7vh/QcarbB4YJIuBKIpuTAM0wtCqNiJBgMBCaE0ZUFCXpoknWdCEFvpfURdCcM8noEIW82cSNzRnWDZoYjamttWhphQmOSHFVXkZecnZ6foKFujJdlZxqELo1AqQSrFH1/TbEZtLM9shetrzK7qKSSpryixMXGx8jJyifCKc1kcMzRIrYl1Xy4J9cfvibdIs/MwMue4cffxtvE6qLoxubk8ScRACH5BAkKAAAALAAAAAA2ADcAAATOEMhJq7046827/2AojmRpnmiqrqwwDAJbCkRNxLI42MSQ6zzfD0Sz4YYfFwyZKxhqhgJJeSQVdraBNFSsVUVPHsEAzJrEtnJNSELXRN2bKcwjw19f0QG7PjA7B2EGfn+FhoeIiYoSCAk1CQiLFQpoChlUQwhuBJEWcXkpjm4JF3w9P5tvFqZsLKkEF58/omiksXiZm52SlGKWkhONj7vAxcbHyMkTmCjMcDygRNAjrCfVaqcm11zTJrIjzt64yojhxd/G28XqwOjG5uTxJhEAIfkECQoAAAAsAAAAADYANwAABM0QyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7/i8qmCoGQoacT8FZ4AXbFopfTwEBhhnQ4w2j0GRkgQYiEOLPI6ZUkgHZwd6EweLBqSlq6ytricICTUJCKwKkgojgiMIlwS1VEYlspcJIZAkvjXHlcnKIZokxJLG0KAlvZfAebeMuUi7FbGz2z/Rq8jozavn7Nev8CsRACH5BAkKAAAALAAAAAA2ADcAAATLEMhJq7046827/2AojmRpnmiqrqwwDAJbCkRNxLI42MSQ6zzfD0Sz4YYfFwzJNCmPzheUyJuKijVrZ2cTlrg1LwjcO5HFyeoJeyM9U++mfE6v2+/4PD6O5F/YWiqAGWdIhRiHP4kWg0ONGH4/kXqUlZaXmJlMBQY1BgVuUicFZ6AhjyOdPAQGQF0mqzauYbCxBFdqJao8rVeiGQgJNQkIFwdnB0MKsQrGqgbJPwi2BMV5wrYJetQ129x62LHaedO21nnLq82VwcPnIhEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7/g8Po7kX9haKoAZZ0iFGIc/iRaDQ40Yfj+RepSVlpeYAAgJNQkIlgo8NQqUCKI2nzNSIpynBAkzaiCuNl9BIbQ1tl0hraewbrIfpq6pbqsioaKkFwUGNQYFSJudxhUFZ9KUz6IGlbTfrpXcPN6UB2cHlgfcBuqZKBEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhhh8XDMk0KY/OF5TIm4qKNWtnZxOWuDUvCNw7kcXJ6gl7Iz1T76Z8Tq/b7yJEopZA4CsKPDUKfxIIgjZ+P3EWe4gECYtqFo82P2cXlTWXQReOiJE5bFqHj4qiUhmBgoSFho59rrKztLVMBQY1BgWzBWe8UUsiuYIGTpMglSaYIcpfnSHEPMYzyB8HZwdrqSMHxAbath2MsqO0zLLorua05OLvJxEAIfkECQoAAAAsAAAAADYANwAABMwQyEmrvTjrzbv/YCiOZGmeaKqurDAMAlsKRE3EsjjYxJDrPN8PRLPhfohELYHQuGBDgIJXU0Q5CKqtOXsdP0otITHjfTtiW2lnE37StXUwFNaSScXaGZvm4r0jU1RWV1hhTIWJiouMjVcFBjUGBY4WBWw1A5RDT3sTkVQGnGYYaUOYPaVip3MXoDyiP3k3GAeoAwdRnRoHoAa5lcHCw8TFxscduyjKIrOeRKRAbSe3I9Um1yHOJ9sjzCbfyInhwt3E2cPo5dHF5OLvJREAOwAAAAAAAAAAAA==') 
    -ms-opacity : 0.4;
    opacity : 0.4;
    background-repeat : no-repeat;
    background-position : center;
    left : 0;
    bottom : 0;
    right : 0;
    top : 0;
}

Playing HTML5 video on fullscreen in android webview

Cprcrack's answer works very well for API levels 19 and under. Just a minor addition to cprcrack's onShowCustomView will get it working on API level 21+

if (Build.VERSION.SDK_INT >= 21) {
      videoViewContainer.setBackgroundColor(Color.BLACK);
      ((ViewGroup) webView.getParent()).addView(videoViewContainer);
      webView.scrollTo(0,0);  // centers full screen view 
} else {
      activityNonVideoView.setVisibility(View.INVISIBLE);
      ViewGroup.LayoutParams vg = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
      activityVideoView.addView(videoViewContainer,vg);
      activityVideoView.setVisibility(View.VISIBLE);
}

You will also need to reflect the changes in onHideCustomView

Ansible date variable

The filter option filters only the first level subkey below ansible_facts

Set element width or height in Standards Mode

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";

Setting initial values on load with Select2 with Ajax

Maybe this work for you!! This works for me...

initSelection: function (element, callback) {

            callback({ id: 1, text: 'Text' });
}

Check very well that code is correctly spelled, my issue was in the initSelection, I had initselection

jQuery: Best practice to populate drop down?

For a newbie like me to JavaScript let alone JQuery, the more JavaScript way of doing it is:

result.forEach(d=>$("#dropdown").append(new Option(d,d)))

Show dialog from fragment?

 public void showAlert(){


     AlertDialog.Builder alertDialog = new AlertDialog.Builder(getActivity());
     LayoutInflater inflater = getActivity().getLayoutInflater();
     View alertDialogView = inflater.inflate(R.layout.test_dialog, null);
     alertDialog.setView(alertDialogView);

     TextView textDialog = (TextView) alertDialogView.findViewById(R.id.text_testDialogMsg);
     textDialog.setText(questionMissing);

     alertDialog.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
             dialog.cancel();
         }
     });
     alertDialog.show();

}

where .test_dialog is of xml custom

Converting BigDecimal to Integer

Following should do the trick:

BigDecimal d = new BigDecimal(10);
int i = d.intValue();

Link to reload current page

Just add target="_blank" and the link will open a new page keeping the original page.

How can you tell if a value is not numeric in Oracle?

SELECT DECODE(REGEXP_COUNT(:value,'\d'),LENGTH(:value),'Y','N') AS is_numeric FROM dual;

There are many ways but this one works perfect for me.

count number of rows in a data frame in R based on group

library(plyr)
ddply(data, .(MONTH-YEAR), nrow)

This will give you the answer, if "MONTH-YEAR" is a variable. First, try unique(data$MONTH-YEAR) and see if it returns unique values (no duplicates).

Then above simple split-apply-combine will return what you are looking for.

Line break (like <br>) using only css

It works like this:

h4 {
    display:inline;
}
h4:after {
    content:"\a";
    white-space: pre;
}

Example: http://jsfiddle.net/Bb2d7/

The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)

Error In PHP5 ..Unable to load dynamic library

My problem was solved by the following command

sudo apt-get install php5-mcrypt

I have

  • PHP 5.3.10-1ubuntu3.4 with Suhosin-Patch (cli)
  • Ubuntu Desktop 12.04
  • Mysql 5.5

PHP error: php_network_getaddresses: getaddrinfo failed: (while getting information from other site.)

I faced this issue, while connecting DB, the variable to connect to db was not defined.

Cause: php tried to connect to the db with undefined variable for db host (localhost/127.0.0.1/... any other ip or domain) but failed to trace the domain.

Solution: Make sure the db host is properly defined.

jQuery.click() vs onClick

Performance

There are already many good answers here however, authors sometimes mention about performance but actually nobody investigate it yet - so I will focus on this aspect here. Today I perform test on Chrome 83.0, Safari 13.1 and Firefox 77.0 for solutions mention in question and additionally few alternative solutions (some of them was mention in other answers).

Results

I compare here solutions A-H because they operate on elements id. I also show results for solutions which use class (I,J,K) as reference.

  • solution based on html-inline handler binding (B) is fast and fastest for Chrome and fastest for small number of elements
  • solutions based on getElementById (C,D) are fast, and for big number of elements fastest on Safari and Firefox
  • referenced solutions I,J based are fastest for big num of elements so It is worth to consider use class instead id approach in this case
  • solution based on jQuery.click (A) is slowest

enter image description here

Details

Actually It was not easy to design performance test for this question. I notice that for all tested solutions, performance of triggering events for 10K div-s was fast and manually I was not able to detect any differences between them (you can run below snippet to check it yourself). So I focus on measure execution time of generate html and bind event handlers for two cases

  • 10 divs - you can run test HERE
  • 1000 divs - you can run test HERE

_x000D_
_x000D_
// https://stackoverflow.com/questions/12627443/jquery-click-vs-onclick
let a= [...Array(10000)];

function clean() { test.innerHTML = ''; console.clear() }

function divFunction(el) {
  console.log(`clicked on: ${el.id}`);
}

function initA() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> $(`#myDiv${i}`).click(e=> divFunction(e.target)));
}

function initB() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box" onclick="divFunction(this)">${i}</div>`).join``;
}

function initC() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> document.getElementById(`myDiv${i}`).onclick = e=> divFunction(e.target) );
}

function initD() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> document.getElementById(`myDiv${i}`).addEventListener('click', e=> divFunction(e.target) ));
}

function initE() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> document.querySelector(`#myDiv${i}`).onclick = e=> divFunction(e.target) );
}

function initF() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> document.querySelector(`#myDiv${i}`).addEventListener('click', e=> divFunction(e.target) ));
}

function initG() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> window[`myDiv${i}`].onclick = e=> divFunction(e.target) );
}

function initH() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  a.map((x,i)=> window[`myDiv${i}`].addEventListener('click',e=> divFunction(e.target)));
}

function initI() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  [...document.querySelectorAll(`.box`)].map(el => el.onclick = e=> divFunction(e.target));
}

function initJ() {
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  [...document.querySelectorAll(`.box`)].map(el => el.addEventListener('click', e=> divFunction(e.target)));
}

function initK() {  
  test.innerHTML = a.map((x,i)=> `<div id="myDiv${i}" class="box">${i}</div>`).join``;
  $(`.box`).click(e=> divFunction(e.target));
}



function measure(f) {  
  console.time("measure "+f.name);
  f();
  console.timeEnd("measure "+f.name)
}
_x000D_
#test {
  display: flex;
  flex-wrap: wrap;
}

.box {
  margin: 1px;
  height: 10px;
  background: red;
  font-size: 10px;
  cursor: pointer;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>This snippet only presents used solutions. Click to solution button and then click on any red box to trigger its handler</div>
<button onclick="measure(initA)">A</button>
<button onclick="measure(initB)">B</button>
<button onclick="measure(initC)">C</button>
<button onclick="measure(initD)">D</button>
<button onclick="measure(initE)">E</button>
<button onclick="measure(initF)">F</button>
<button onclick="measure(initG)">G</button>
<button onclick="measure(initH)">H</button>
<button onclick="measure(initI)">I</button>
<button onclick="measure(initJ)">J</button>
<button onclick="measure(initK)">K</button>
<button onclick="clean()">Clean</button>

<div id="test"></div>
_x000D_
_x000D_
_x000D_

Here is example test for Chrome

enter image description here

Set transparent background of an imageview on Android

For those who are still facing this problem, you may try this
element.getBackground().setAlpha(0);

Can we pass model as a parameter in RedirectToAction?

  [HttpPost]
    public async Task<ActionResult> Capture(string imageData)
    {                      
        if (imageData.Length > 0)
        {
            var imageBytes = Convert.FromBase64String(imageData);
            using (var stream = new MemoryStream(imageBytes))
            {
                var result = (JsonResult)await IdentifyFace(stream);
                var serializer = new JavaScriptSerializer();
                var faceRecon = serializer.Deserialize<FaceIdentity>(serializer.Serialize(result.Data));

                if (faceRecon.Success) return RedirectToAction("Index", "Auth", new { param = serializer.Serialize(result.Data) });

            }
        }

        return Json(new { success = false, responseText = "Der opstod en fejl - Intet billede, manglede data." }, JsonRequestBehavior.AllowGet);

    }


// GET: Auth
    [HttpGet]
    public ActionResult Index(string param)
    {
        var serializer = new JavaScriptSerializer();
        var faceRecon = serializer.Deserialize<FaceIdentity>(param);


        return View(faceRecon);
    }

how to call a onclick function in <a> tag?

Fun! There are a few things to tease out here:

  • $leadID seems to be a php string. Make sure it gets printed in the right place. Also be aware of all the risks involved in passing your own strings around, like cross-site scripting and SQL injection vulnerabilities. There’s really no excuse for having Internet-facing production code not running on a solid framework.
  • Strings in Javascript (like in PHP and usually HTML) need to be enclosed in " or ' characters. Since you’re already inside both " and ', you’ll want to escape whichever you choose. \' to escape the PHP quotes, or &apos; to escape the HTML quotes.
  • <a /> elements are commonly used for “hyper”links, and almost always with a href attribute to indicate their destination, like this: <a href="http://www.google.com">Google homepage</a>.
  • You’re trying to double up on watching when the user clicks. Why? Because a standard click both activates the link (causing the browser to navigate to whatever URL, even that executes Javascript), and “triggers” the onclick event. Tip: Add a return false; to a Javascript event to suppress default behavior.
  • Within Javascript, onclick doesn’t mean anything on its own. That’s because onclick is a property, and not a variable. There has to be a reference to some object, so it knows whose onclick we’re talking about! One such object is window. You could write <a href="javascript:window.onclick = location.reload;">Activate me to reload when anything is clicked</a>.
  • Within HTML, onclick can mean something on its own, as long as its part of an HTML tag: <a href="#" onclick="location.reload(); return false;">. I bet you had this in mind.
  • Big difference between those two kinds of = assignments. The Javascript = expects something that hasn’t been run yet. You can wrap things in a function block to signal code that should be run later, if you want to specify some arguments now (like I didn’t above with reload): <a href="javascript:window.onclick = function () { window.open( ... ) };"> ....
  • Did you know you don’t even need to use Javascript to signal the browser to open a link in a new window? There’s a special target attribute for that: <a href="http://www.google.com" target="_blank">Google homepage</a>.

Hope those are useful.

Base64 length calculation?

Seems to me that the right formula should be:

n64 = 4 * (n / 3) + (n % 3 != 0 ? 4 : 0)

Validating input using java.util.Scanner

Here's a minimalist way to do it.

System.out.print("Please enter an integer: ");
while(!scan.hasNextInt()) scan.next();
int demoInt = scan.nextInt();

How to align this span to the right of the div?

Working with floats is bit messy:

This as many other 'trivial' layout tricks can be done with flexbox.

   div.container {
     display: flex;
     justify-content: space-between;
   }

In 2017 I think this is preferred solution (over float) if you don't have to support legacy browsers: https://caniuse.com/#feat=flexbox

Check fiddle how different float usages compares to flexbox ("may include some competing answers"): https://jsfiddle.net/b244s19k/25/. If you still need to stick with float I recommended third version of course.

Convert .class to .java

I'm guessing that either the class name is wrong - be sure to use the fully-resolved class name, with all packages - or it's not in the CLASSPATH so javap can't find it.

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

Configure Log4net to write to multiple files

Vinay is correct. In answer to your comment in his answer, one way you can do it is as follows:

<root>
    <level value="ALL" />
    <appender-ref ref="File1Appender" />
</root>
<logger name="SomeName">
    <level value="ALL" />
    <appender-ref ref="File1Appender2" />
</logger>

This is how I have done it in the past. Then something like this for the other log:

private static readonly ILog otherLog = LogManager.GetLogger("SomeName");

And you can get your normal logger as follows:

private static readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

Read the loggers and appenders section of the documentation to understand how this works.

Storing an object in state of a React component?

  1. this.setState({ abc.xyz: 'new value' }); syntax is not allowed. You have to pass the whole object.

    this.setState({abc: {xyz: 'new value'}});
    

    If you have other variables in abc

    var abc = this.state.abc;
    abc.xyz = 'new value';
    this.setState({abc: abc});
    
  2. You can have ordinary variables, if they don't rely on this.props and this.state.

Unicode character for "X" cancel / close?

? works really well. The HTML code is &#10006;.

An alternative is &#x2715: ?