Programs & Examples On #Graph traversal

ProgressDialog spinning circle

Just change from ProgressDialog to ProgressBar in a layout:

res/layout.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/container">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >
        //Your content here
     </LinearLayout>

        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyleLarge"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerHorizontal="true"
            android:layout_centerVertical="true"
            android:visibility="gone"
            android:indeterminateDrawable="@drawable/progress" >
        </ProgressBar>
</RelativeLayout>

src/yourPackage/YourActivity.java

public class YourActivity extends Activity{

private ProgressBar bar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout);
    bar = (ProgressBar) this.findViewById(R.id.progressBar);
    new ProgressTask().execute();
}
private class ProgressTask extends AsyncTask <Void,Void,Void>{
    @Override
    protected void onPreExecute(){
        bar.setVisibility(View.VISIBLE);
    }

    @Override
    protected Void doInBackground(Void... arg0) {   
           //my stuff is here
    }

    @Override
    protected void onPostExecute(Void result) {
          bar.setVisibility(View.GONE);
    }
}
}

drawable/progress.xml This is a custom ProgressBar that i use to change the default colors.

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

<!-- 
    Duration = 1 means that one rotation will be done in 1 second. leave it.
    If you want to speed up the rotation, increase duration value. 
    in example 1080 shows three times faster revolution. 
    make the value multiply of 360, or the ring animates clunky 
-->
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
    android:fromDegrees="0"
    android:pivotX="50%"
    android:pivotY="50%"
    android:duration="1"
    android:toDegrees="360" >

    <shape
        android:innerRadiusRatio="3"
        android:shape="ring"
        android:thicknessRatio="8"
        android:useLevel="false" >
        <size
            android:height="48dip"
            android:width="48dip" />

        <gradient
            android:centerColor="@color/color_preloader_center"
            android:centerY="0.50"
            android:endColor="@color/color_preloader_end"
            android:startColor="@color/color_preloader_start"
            android:type="sweep"
            android:useLevel="false" />
    </shape>

</rotate>

"Insert if not exists" statement in SQLite

For a unique column, use this:

INSERT OR REPLACE INTO table () values();

For more information, see: sqlite.org/lang_insert

SQL keys, MUL vs PRI vs UNI

UNI: For UNIQUE:

  • It is a set of one or more columns of a table to uniquely identify the record.
  • A table can have multiple UNIQUE key.
  • It is quite like primary key to allow unique values but can accept one null value which primary key does not.

PRI: For PRIMARY:

  • It is also a set of one or more columns of a table to uniquely identify the record.
  • A table can have only one PRIMARY key.
  • It is quite like UNIQUE key to allow unique values but does not allow any null value.

MUL: For MULTIPLE:

  • It is also a set of one or more columns of a table which does not identify the record uniquely.
  • A table can have more than one MULTIPLE key.
  • It can be created in table on index or foreign key adding, it does not allow null value.
  • It allows duplicate entries in column.
  • If we do not specify MUL column type then it is quite like a normal column but can allow null entries too hence; to restrict such entries we need to specify it.
  • If we add indexes on column or add foreign key then automatically MUL key type added.

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

Unfortunately you can't reference your alias in the GROUP BY statement, you'll have to write the logic again, amazing as that seems.

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY     LastName + ', ' + FirstName

Alternately you could put the select into a subselect or common table expression, after which you could group on the column name (no longer an alias.)

Excel VBA App stops spontaneously with message "Code execution has been halted"

I have came across this issue few times during the development of one complex Excel VBA app. Sometimes Excel started to break VBA object quite randomly. And the only remedy was to reboot machine. After reboot, Excel usually started to act normally.

Soon I have found out that possible solution to this issue is to hit CTRL+Break once when macro is NOT running. Maybe this can help to you too.

catch specific HTTP error in python

Python 3

from urllib.error import HTTPError

Python 2

from urllib2 import HTTPError

Just catch HTTPError, handle it, and if it's not Error 404, simply use raise to re-raise the exception.

See the Python tutorial.

e.g. complete example for Pyhton 2

import urllib2
from urllib2 import HTTPError
try:
   urllib2.urlopen("some url")
except HTTPError as err:
   if err.code == 404:
       <whatever>
   else:
       raise

Which variable size to use (db, dw, dd) with x86 assembly?

The full list is:

DB, DW, DD, DQ, DT, DDQ, and DO (used to declare initialized data in the output file.)

See: http://www.tortall.net/projects/yasm/manual/html/nasm-pseudop.html

They can be invoked in a wide range of ways: (Note: for Visual-Studio - use "h" instead of "0x" syntax - eg: not 0x55 but 55h instead):

    db      0x55                ; just the byte 0x55
    db      0x55,0x56,0x57      ; three bytes in succession
    db      'a',0x55            ; character constants are OK
    db      'hello',13,10,'$'   ; so are string constants
    dw      0x1234              ; 0x34 0x12
    dw      'A'                 ; 0x41 0x00 (it's just a number)
    dw      'AB'                ; 0x41 0x42 (character constant)
    dw      'ABC'               ; 0x41 0x42 0x43 0x00 (string)
    dd      0x12345678          ; 0x78 0x56 0x34 0x12
    dq      0x1122334455667788  ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    ddq     0x112233445566778899aabbccddeeff00
    ; 0x00 0xff 0xee 0xdd 0xcc 0xbb 0xaa 0x99
    ; 0x88 0x77 0x66 0x55 0x44 0x33 0x22 0x11
    do      0x112233445566778899aabbccddeeff00 ; same as previous
    dd      1.234567e20         ; floating-point constant
    dq      1.234567e20         ; double-precision float
    dt      1.234567e20         ; extended-precision float

DT does not accept numeric constants as operands, and DDQ does not accept float constants as operands. Any size larger than DD does not accept strings as operands.

ASP.NET MVC Return Json Result?

It should be :

public async Task<ActionResult> GetSomeJsonData()
{
    var model = // ... get data or build model etc.

    return Json(new { Data = model }, JsonRequestBehavior.AllowGet); 
}

or more simply:

return Json(model, JsonRequestBehavior.AllowGet); 

I did notice that you are calling GetResources() from another ActionResult which wont work. If you are looking to get JSON back, you should be calling GetResources() from ajax directly...

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

Following line is hurting JSON encoder,

now = datetime.datetime.now()
now = datetime.datetime.strftime(now, '%Y-%m-%dT%H:%M:%S.%fZ')
print json.dumps({'current_time': now}) // this is the culprit

I got a temporary fix for it

print json.dumps( {'old_time': now.encode('ISO-8859-1').strip() })

Marking this as correct as a temporary fix (Not sure so).

How do I check if a string is valid JSON in Python?

I came up with an generic, interesting solution to this problem:

class SafeInvocator(object):
    def __init__(self, module):
        self._module = module

    def _safe(self, func):
        def inner(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except:
                return None

        return inner

    def __getattr__(self, item):
        obj = getattr(self.module, item)
        return self._safe(obj) if hasattr(obj, '__call__') else obj

and you can use it like so:

safe_json = SafeInvocator(json)
text = "{'foo':'bar'}"
item = safe_json.loads(text)
if item:
    # do something

How can I make robocopy silent in the command line except for progress?

I did it by using the following options:

/njh /njs /ndl /nc /ns

Note that the file name still displays, but that's fine for me.

For more information on robocopy, go to http://technet.microsoft.com/en-us/library/cc733145%28WS.10%29.aspx

How can I run Tensorboard on a remote server?

This is not a proper answer but a troubleshooter, hopefully helps other less seasoned networkers like me.

In my case (firefox+ubuntu16) the browser was connecting, but showing a blank page (with the tensorboard logo on the tab), and no log activity at all was shown. I still don't know what could be the reason for that (didn't look much into it but if anybody knows please let know!), but I solved it switching to ubuntu's default browser. Here the exact steps, pretty much the same as in @Olivier Moindrot's answer:

  1. On the server, start tensorboard: tensorboard --logdir=. --host=localhost --port=6006
  2. On the client, open the ssh tunnel ssh -p 23 <USER>@<SERVER> -N -f -L localhost:16006:localhost:6006
  3. Open ubuntu's Browser and visit localhost:16006. The tensorboard page should load without much delay.

To check that the SSH tunnel is effectively working, a simple echo server like this python script can help:

  1. Put the script into an <ECHO>.py file in the server and run it with python <ECHO>.py. Now the server will have the echo script listening on 0.0.0.0:5555.
  2. On the client, open the ssh tunnel ssh -p <SSH_PORT> <USER>@<SERVER> -N -f -L localhost:12345:localhost:5555
  3. On the client, in the same terminal used to open the tunnel (step 2.), issuing telnet localhost 12345 will connect to the echo script running in the server. Typing hello and pressing enter should print hello back. If that is the case, your SSH tunnel is working. This was my case, and lead me to the conclusion that the problem involved the browser. Trying to connect from a different terminal caused the terminal to freeze.

As I said, hope it helps!
Cheers,
Andres

Header set Access-Control-Allow-Origin in .htaccess doesn't work

Try this in the .htaccess of the external root folder

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

Be careful on : Header add Access-Control-Allow-Origin "*" This is not judicious at all to grant access to everybody. I think you should user:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "http://example.com"
</IfModule>

How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue?

If error reason is extension use incognito Ctrl+Shift+N. In incognito mode Chrome does not have extensions.

UPD. If you need some extension in incognito mode e.g. ReduxDevTools or any other, in extension settings turn on "Allow in incognito"

Redirecting exec output to a buffer or file

Since you look like you're going to be using this in a linux/cygwin environment, you want to use popen. It's like opening a file, only you'll get the executing programs stdout, so you can use your normal fscanf, fread etc.

How can I easily view the contents of a datatable or dataview in the immediate window

i have programmed a small method for it.. its a generalize function..

    public static void printDataTable(DataTable tbl)
    {
        string line = "";
        foreach (DataColumn item in tbl.Columns)
        {
            line += item.ColumnName +"   ";
        }
        line += "\n";
        foreach (DataRow row in tbl.Rows)
        {
            for (int i = 0; i < tbl.Columns.Count; i++)
            {
                line += row[i].ToString() + "   ";
            }
            line += "\n";
        }
        Console.WriteLine(line) ;
    }

Eclipse executable launcher error: Unable to locate companion shared library

I had the same problem when I was trying to install it on Windows 8. But it was an zip composed file.... Ones I unzip and Run "eclipes.exe" file as run As 'Administrator' it was resolved. Now I am enjoying it very well.

What is "pom" packaging in maven?

I suggest to see the classic example at: http://maven.apache.org/guides/getting-started/index.html#How_do_I_build_more_than_one_project_at_once

Here my-webapp is web project, which depends on the code at my-app project. So to bundle two projects in one, we have top level pom.xml which mentions which are the projects (modules as per maven terminology) to be bundled finally. Such top level pom.xml can use pom packaging.

my-webapp can have war packaging and can have dependency on my-app. my-app can have jar packaging.

How to check for an empty struct?

You can use == to compare with a zero value composite literal because all fields are comparable:

if (Session{}) == session  {
    fmt.Println("is zero value")
}

playground example

Because of a parsing ambiguity, parentheses are required around the composite literal in the if condition.

The use of == above applies to structs where all fields are comparable. If the struct contains a non-comparable field (slice, map or function), then the fields must be compared one by one to their zero values.

An alternative to comparing the entire value is to compare a field that must be set to a non-zero value in a valid session. For example, if the player id must be != "" in a valid session, use

if session.playerId == "" {
    fmt.Println("is zero value")
}

Repeat String - Javascript

function repeat(s, n) { var r=""; for (var a=0;a<n;a++) r+=s; return r;}

Get the value of bootstrap Datetimepicker in JavaScript

Or try:

$("#datetimepicker").data().date;

Display alert message and redirect after click on accept

The redirect function cleans the output buffer and does a header('Location:...'); redirection and exits script execution. The part you are trying to echo will never be outputted.

You should either notify on the download page or notify on the page you redirect to about the missing data.

C# ASP.NET Single Sign-On Implementation

I am late to the party, but for option #1, I would go with IdentityServer3(.NET 4.6 or below) or IdentityServer4 (compatible with Core) .

You can reuse your existing user store in your app and plug that to be IdentityServer's User Store. Then the clients must be pointed to your IdentityServer as the open id provider.

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

Center text in table cell

How about simply (Please note, come up with a better name for the class name this is simply an example):

.centerText{
   text-align: center;
}


<div>
   <table style="width:100%">
   <tbody>
   <tr>
      <td class="centerText">Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td class="centerText">Cell 3</td>
      <td>Cell 4</td>
    </tr>
    </tbody>
    </table>
</div>

Example here

You can place the css in a separate file, which is recommended. In my example, I created a file called styles.css and placed my css rules in it. Then include it in the html document in the <head> section as follows:

<head>
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>

The alternative, not creating a seperate css file, not recommended at all... Create <style> block in your <head> in the html document. Then just place your rules there.

<head>
 <style type="text/css">
   .centerText{
       text-align: center;
    }
 </style>
</head>

Cloning specific branch

Please try like this : git clone --single-branch --branch <branchname> <url>

replace <branchname> with your branch and <url> with your url.

url will be like http://[email protected]:portno/yourrepo.git.

Writing an Excel file in EPPlus

If you have a collection of objects that you load using stored procedure you can also use LoadFromCollection.

using (ExcelPackage package = new ExcelPackage(file))
{
    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("test");

    worksheet.Cells["A1"].LoadFromCollection(myColl, true, OfficeOpenXml.Table.TableStyles.Medium1);

    package.Save();
}

Failed to execute 'postMessage' on 'DOMWindow': https://www.youtube.com !== http://localhost:9000

You can try :

document.getElementById('your_id_iframe').contentWindow.postMessage('your_message', 'your_domain_iframe')

Moment.js - How to convert date string into date?

If you are getting a JS based date String then first use the new Date(String) constructor and then pass the Date object to the moment method. Like:

var dateString = 'Thu Jul 15 2016 19:31:44 GMT+0200 (CEST)';
var dateObj = new Date(dateString);
var momentObj = moment(dateObj);
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

In case dateString is 15-07-2016, then you should use the moment(date:String, format:String) method

var dateString = '07-15-2016';
var momentObj = moment(dateString, 'MM-DD-YYYY');
var momentString = momentObj.format('YYYY-MM-DD'); // 2016-07-15

JVM option -Xss - What does it do exactly?

If I am not mistaken, this is what tells the JVM how much successive calls it will accept before issuing a StackOverflowError. Not something you wish to change generally.

SOAP Action WSDL

When soapAction is missing in the SOAP 1.2 request (and many clients do not set it, even when it is specified in WSDL), some app servers (eg. jboss) infer the "actual" soapAction from {xsd:import namespace}+{wsdl:operation name}. So, to make the inferred "actual" soapAction match the expected soapAction, you can set the expected soapAction to {xsd:import namespace}+{wsdl:operation name} in your WS definition (@WebMethod(action=...) for Java EE)

Eg. for a typical Java EE case, this helps (not the Stewart's case, National Rail WS has 'soapAction' set):

@WebMethod(action = "http://packagename.of.your.webservice.class.com/methodName")

If you cannot change the server, you will have to force client to fill soapAction.

Transparent background in JPEG image

Just wanted to add that GIF "transparency" is more like missing pixels. If you use GIF then you will see jagged edges where the background and the rest of the image meet. Using PNG, you can smoothly "composite" images together, which is what you really want. Plus PNG supports highly quality images.

Don't use "Paint". There are many high quality art applications for doing art work. I think even the cell phone apps (Pixlr is pretty good and free!) and web-based image editting apps are better. I use Gimp - free for all platforms.

While a JPEG can't be made transparent in and of itself, if your goal is to reduce the size of very large image areas for the web that need to contain transparent image areas, then there is a solution. It's a bit too complicated to post details, but Google it. Basically, you create your image with transparency and then split out the alpha channel (Gimp can do this easily) as a simple 8-bit greyscale PNG. Then you export the color data as a JPG. Now your web page uses a CANVAS tag to load the JPG as image data and applies the 8-bit greyscale PNG as the Canvas's alpha channel. The browser's Canvas does the work of making the image transparent. The JPEG stores the color info (better compressed than PNG) and the PNG is reduced to 8-bit alpha so its considerably smaller. I've saved a few hundred K per image using this technique. A few people have proposed file formats that embed PNG transparency info into a JPEG's extended information fields, but these proposal's don't have wide support as of yet.

How to get a List<string> collection of values from app.config in WPF?

I love Richard Nienaber's answer, but as Chuu pointed out, it really doesn't tell how to accomplish what Richard is refering to as a solution. Therefore I have chosen to provide you with the way I ended up doing this, ending with the result Richard is talking about.

The solution

In this case I'm creating a greeting widget that needs to know which options it has to greet in. This may be an over-engineered solution to OPs question as I am also creating an container for possible future widgets.

First I set up my collection to handle the different greetings

public class GreetingWidgetCollection : System.Configuration.ConfigurationElementCollection
{
    public List<IGreeting> All { get { return this.Cast<IGreeting>().ToList(); } }

    public GreetingElement this[int index]
    {
        get
        {
            return base.BaseGet(index) as GreetingElement;
        }
        set
        {
            if (base.BaseGet(index) != null)
            {
                base.BaseRemoveAt(index);
            }
            this.BaseAdd(index, value);
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new GreetingElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((GreetingElement)element).Greeting;
    }
}

Then we create the acutal greeting element and it's interface

(You can omit the interface, that's just the way I'm always doing it.)

public interface IGreeting
{
    string Greeting { get; set; }
}

public class GreetingElement : System.Configuration.ConfigurationElement, IGreeting
{
    [ConfigurationProperty("greeting", IsRequired = true)]
    public string Greeting
    {
        get { return (string)this["greeting"]; }
        set { this["greeting"] = value; }
    }
}

The greetingWidget property so our config understands the collection

We define our collection GreetingWidgetCollection as the ConfigurationProperty greetingWidget so that we can use "greetingWidget" as our container in the resulting XML.

public class Widgets : System.Configuration.ConfigurationSection
{
    public static Widgets Widget => ConfigurationManager.GetSection("widgets") as Widgets;

    [ConfigurationProperty("greetingWidget", IsRequired = true)]
    public GreetingWidgetCollection GreetingWidget
    {
        get { return (GreetingWidgetCollection) this["greetingWidget"]; }
        set { this["greetingWidget"] = value; }
    }
}

The resulting XML

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <widgets>
       <greetingWidget>
           <add greeting="Hej" />
           <add greeting="Goddag" />
           <add greeting="Hello" />
           ...
           <add greeting="Konnichiwa" />
           <add greeting="Namaskaar" />
       </greetingWidget>
    </widgets>
</configuration>

And you would call it like this

List<GreetingElement> greetings = Widgets.GreetingWidget.All;

An implementation of the fast Fourier transform (FFT) in C#

For a multi-threaded implementation tuned for Intel processors I'd check out Intel's MKL library. It's not free, but it's afforable (less than $100) and blazing fast - but you'd need to call it's C dll's via P/Invokes. The Exocortex project stopped development 6 years ago, so I'd be careful using it if this is an important project.

Convert number of minutes into hours & minutes using PHP

$t = 250;
$h = floor($t/60) ? floor($t/60) .' hours' : '';
$m = $t%60 ? $t%60 .' minutes' : '';
echo $h && $m ? $h.' and '.$m : $h.$m;

4 hours and 10 minutes

HTML: How to limit file upload to be only images?

HTML5 File input has accept attribute and also multiple attribute. By using multiple attribute you can upload multiple images in an instance.

<input type="file" multiple accept="image/*">

You can also limit multiple mime types.

<input type="file" multiple accept="image/*,audio/*,video/*">

and another way of checking mime type using file object.

file object gives you name,size and type.

var files=e.target.files;

var mimeType=files[0].type; // You can get the mime type

You can also restrict the user for some file types to upload by the above code.

How to only find files in a given directory, and ignore subdirectories using bash

find /dev -maxdepth 1 -name 'abc-*'

Does not work for me. It return nothing. If I just do '.' it gives me all the files in directory below the one I'm working in on.

find /dev -maxdepth 1 -name "*.root" -type 'f' -size +100k -ls

Return nothing with '.' instead I get list of all 'big' files in my directory as well as the rootfiles/ directory where I store old ones.

Continuing. This works.

find ./ -maxdepth 1 -name "*.root" -type 'f' -size +100k -ls
564751   71 -rw-r--r--   1 snyder   bfactory   115739 May 21 12:39 ./R24eTightPiPi771052-55.root
565197  105 -rw-r--r--   1 snyder   bfactory   150719 May 21 14:27 ./R24eTightPiPi771106-2.root
565023   94 -rw-r--r--   1 snyder   bfactory   134180 May 21 12:59 ./R24eTightPiPi77999-109.root
719678   82 -rw-r--r--   1 snyder   bfactory   121149 May 21 12:42 ./R24eTightPiPi771098-10.root
564029  140 -rw-r--r--   1 snyder   bfactory   170181 May 21 14:14 ./combo77v.root

Apparently /dev means directory of interest. But ./ is needed, not just .. The need for the / was not obvious even after I figured out what /dev meant more or less.

I couldn't respond as a comment because I have no 'reputation'.

axios post request to send form data

import axios from "axios";
import qs from "qs";   

const url = "https://yourapplicationbaseurl/api/user/authenticate";
    let data = {
      Email: "[email protected]",
      Password: "Admin@123"
    };
    let options = {
      method: "POST",
      headers: { "content-type": "application/x-www-form-urlencoded" },
      data: qs.stringify(data),
      url
    };
    axios(options)
      .then(res => {
        console.log("yeh we have", res.data);
      })
      .catch(er => {
        console.log("no data sorry ", er);
      });
  };

Toolbar overlapping below status bar

For me, the problem was that I copied something from an example and used

<item name="android:windowTranslucentStatus">true</item>

just removing this fixed my problem.

PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

That’s probably everyone’s first thought. But it’s a little bit more difficult. See Chris Shiflett’s article SERVER_NAME Versus HTTP_HOST.

It seems that there is no silver bullet. Only when you force Apache to use the canonical name you will always get the right server name with SERVER_NAME.

So you either go with that or you check the host name against a white list:

$allowed_hosts = array('foo.example.com', 'bar.example.com');
if (!isset($_SERVER['HTTP_HOST']) || !in_array($_SERVER['HTTP_HOST'], $allowed_hosts)) {
    header($_SERVER['SERVER_PROTOCOL'].' 400 Bad Request');
    exit;
}

Determine on iPhone if user has enabled push notifications

In the latest version of iOS this method is now deprecated. To support both iOS 7 and iOS 8 use:

UIApplication *application = [UIApplication sharedApplication];

BOOL enabled;

// Try to use the newer isRegisteredForRemoteNotifications otherwise use the enabledRemoteNotificationTypes.
if ([application respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
{
    enabled = [application isRegisteredForRemoteNotifications];
}
else
{
    UIRemoteNotificationType types = [application enabledRemoteNotificationTypes];
    enabled = types & UIRemoteNotificationTypeAlert;
}

exception in initializer error in java when using Netbeans

I found that I had bound jFormattedCheckBox1.foreground to jCheckBox1[${selected}].... this was the problem. Thank you for your help.

It seems that a color should not be able to be bound to a boolean. I guess bindings are an advanced feature?

I found the problem by deleting all of the controls, then running, then undoing and then deleting one at a time. When I found the offending control, I examined the properties.

Excel "External table is not in the expected format."

"External table is not in the expected format." typically occurs when trying to use an Excel 2007 file with a connection string that uses: Microsoft.Jet.OLEDB.4.0 and Extended Properties=Excel 8.0

Using the following connection string seems to fix most problems.

public static string path = @"C:\src\RedirectApplication\RedirectApplication\301s.xlsx";
public static string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;";

Clear and reset form input fields

I don't know if this is still relevant. But when I had similar issue this is how I resolved it.

Where you need to clear an uncontrolled form you simply do this after submission.

this.<ref-name-goes-here>.setState({value: ''});

Hope this helps.

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

This was resolved by:

yum install gcc kernel-devel make

workaround is here: https://gist.github.com/larsar/1687725

set environment variable in python script

You can add elements to your environment by using

os.environ['LD_LIBRARY_PATH'] = 'my_path'

and run subprocesses in a shell (that uses your os.environ) by using

subprocess.call('sqsub -np ' + var1 + '/homedir/anotherdir/executable', shell=True)

Hibernate: Automatically creating/updating the db tables based on entity classes

I don't know if leaving hibernate off the front makes a difference.

The reference suggests it should be hibernate.hbm2ddl.auto

A value of create will create your tables at sessionFactory creation, and leave them intact.

A value of create-drop will create your tables, and then drop them when you close the sessionFactory.

Perhaps you should set the javax.persistence.Table annotation explicitly?

Hope this helps.

How to match all occurrences of a regex

To find all the matching strings, use String's scan method.

str = "A 54mpl3 string w1th 7 numb3rs scatter36 ar0und"
str.scan(/\d+/)
#=> ["54", "3", "1", "7", "3", "36", "0"]

If you want, MatchData, which is the type of the object returned by the Regexp match method, use:

str.to_enum(:scan, /\d+/).map { Regexp.last_match }
#=> [#<MatchData "54">, #<MatchData "3">, #<MatchData "1">, #<MatchData "7">, #<MatchData "3">, #<MatchData "36">, #<MatchData "0">]

The benefit of using MatchData is that you can use methods like offset:

match_datas = str.to_enum(:scan, /\d+/).map { Regexp.last_match }
match_datas[0].offset(0)
#=> [2, 4]
match_datas[1].offset(0)
#=> [7, 8]

See these questions if you'd like to know more:

Reading about special variables $&, $', $1, $2 in Ruby will be helpful too.

Change Background color (css property) using Jquery

You're using a colon instead of a comma. Try:

$(body).css("background-color","blue");

You also need to wrap the id in quotes or it will look for a variable called #co

$("#co").click(change()

There are many more issues here. click isn't an HTML attribute. You want onclick (which is redundant). Try this:

<div id="co"> <!-- no onclick method needed -->
<script>
$(document).ready(function() {
    $("#co").click(function() {
        $("body").css("background-color","blue"); //edit, body must be in quotes!
    });
});
</script>

You were trying to call an undefined method. It looks like you were trying to declare it inside the callback statement? I'm not sure. But please compare this to your code and see the differences.

http://jsfiddle.net/CLwE5/ demo fiddle

Initializing a two dimensional std::vector

The recommended approach is to use fill constructor to initialize a two-dimensional vector with a given default value :

std::vector<std::vector<int>> fog(M, std::vector<int>(N, default_value));

where, M and N are dimensions for your 2D vector.

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

Java Thread Example?

create java application in which you define two threads namely t1 and t2, thread t1 will generate random number 0 and 1 (simulate toss a coin ). 0 means head and one means tail. the other thread t2 will do the same t1 and t2 will repeat this loop 100 times and finally your application should determine how many times t1 guesses the number generated by t2 and then display the score. for example if thread t1 guesses 20 number out of 100 then the score of t1 is 20/100 =0.2 if t1 guesses 100 numbers then it gets score 1 and so on

Convert JSON String to JSON Object c#

string result = await resp.Content.ReadAsStringAsync(); List _Resp = JsonConvert.DeserializeObject<List>(result); //List _objList = new List((IEnumerable)_Resp);

            IList usll = _Resp.Select(a => a.lttsdata).ToList();
            // List<ListViewClass> _objList = new List<ListViewClass>((IEnumerable<ListViewClass>)_Resp);
            //IList usll = _objList.OrderBy(a=> a.ReqID).ToList();
            Lv.ItemsSource = usll;

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

How to get selenium to wait for ajax response?

This work for me

public  void waitForAjax(WebDriver driver) {
    new WebDriverWait(driver, 180).until(new ExpectedCondition<Boolean>(){
        public Boolean apply(WebDriver driver) {
            JavascriptExecutor js = (JavascriptExecutor) driver;
            return (Boolean) js.executeScript("return jQuery.active == 0");
        }
    });
}

JavaScript file not updating no matter what I do

I had this problem and solved in Chrome by just disabling Cache: - Click F12; - Go at Network tab; - Click on "Disable Cache".

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

For me, the problem that caused this error arose when I was saving a new row to the database, but a field was null. In the database table design, that field is NOT NULL. So when I tried to save a new row with a null value for not-null field, Visual Studio threw this error. Thus, I made sure that the field was assigned a value, and the problem was fixed.

how to select rows based on distinct values of A COLUMN only

I am not sure about your DBMS. So, I created a temporary table in Redshift and from my experience, I think this query should return what you are looking for:

select min(Id), distinct MailId, EmailAddress, Name
    from yourTableName
    group by MailId, EmailAddress, Name

I see that I am using a GROUP BY clause but you still won't have two rows against any particular MailId.

MySQL Like multiple values

Or if you need to match only the beginning of words:

WHERE interests LIKE 'sports%' OR interests LIKE 'pub%'

you can use the regexp caret matches:

WHERE interests REGEXP '^sports|^pub'

https://www.regular-expressions.info/anchors.html

Creating a JavaScript cookie on a domain and reading it across sub domains

You want:

document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;

As per the RFC 2109, to have a cookie available to all subdomains, you must put a . in front of your domain.

Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com).

Object does not support item assignment error

Another way would be adding __getitem__, __setitem__ function

def __getitem__(self, key):
    return getattr(self, key)

You can use self[key] to access now.

How to make space between LinearLayout children?

Try to add Space widget after adding view like this:

layout.addView(view)
val space = Space(context)
space.minimumHeight = spaceInterval
layout.addView(space)

How do I download a package from apt-get without installing it?

Try

apt-get -d install <packages>

It is documented in man apt-get.

Just for clarification; the downloaded packages are located in the apt package cache at

/var/cache/apt/archives

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstall?

I had the same problem until I realised I had the simulator running and adb was trying to install on that

How do I set a checkbox in razor view?

I did it using Razor , works for me

Razor Code

@Html.CheckBox("CashOnDelivery", CashOnDelivery) (This is a bit or bool value) Razor don't support nullable bool
@Html.CheckBox("OnlinePayment", OnlinePayment)

C# Code

 var CashOnDelivery = Convert.ToBoolean(Collection["CashOnDelivery"].Contains("true")?true:false);
 var OnlinePayment = Convert.ToBoolean(Collection["OnlinePayment"].Contains("true") ? true : false);

Throw away local commits in Git

If Your branch is ahead of 'origin/XXX' by 5 commits.

You can issue:

git reset --hard HEAD~5

And it should remove the last 5 commits.

Create an array of strings

one of the simplest ways to create a string matrix is as follow :

x = [ {'first string'} {'Second parameter} {'Third text'} {'Fourth component'} ]

How to get a cookie from an AJAX response?

xhr.getResponseHeader('Set-Cookie');

It won't work for me.

I use this

function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for(var i=0; i<ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1);
        if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
    }
    return "";
} 

success: function(output, status, xhr) {
    alert(getCookie("MyCookie"));
},

http://www.w3schools.com/js/js_cookies.asp

How to check if string contains Latin characters only?

No jQuery Needed

if (str.match(/[a-z]/i)) {
    // alphabet letters found
}

How can I implement a tree in Python?

anytree

I recommend https://pypi.python.org/pypi/anytree (I am the author)

Example

from anytree import Node, RenderTree

udo = Node("Udo")
marc = Node("Marc", parent=udo)
lian = Node("Lian", parent=marc)
dan = Node("Dan", parent=udo)
jet = Node("Jet", parent=dan)
jan = Node("Jan", parent=dan)
joe = Node("Joe", parent=dan)

print(udo)
Node('/Udo')
print(joe)
Node('/Udo/Dan/Joe')

for pre, fill, node in RenderTree(udo):
    print("%s%s" % (pre, node.name))
Udo
+-- Marc
¦   +-- Lian
+-- Dan
    +-- Jet
    +-- Jan
    +-- Joe

print(dan.children)
(Node('/Udo/Dan/Jet'), Node('/Udo/Dan/Jan'), Node('/Udo/Dan/Joe'))

Features

anytree has also a powerful API with:

  • simple tree creation
  • simple tree modification
  • pre-order tree iteration
  • post-order tree iteration
  • resolve relative and absolute node paths
  • walking from one node to an other.
  • tree rendering (see example above)
  • node attach/detach hookups

int to hex string

Use ToString("X4").

The 4 means that the string will be 4 digits long.

Reference: The Hexadecimal ("X") Format Specifier on MSDN.

Invoke a second script with arguments from a script

You can execute it same as SQL query. first, build your command/Expression and store in a variable and execute/invoke.

$command =  ".\yourExternalScriptFile.ps1" + " -param1 '$paramValue'"

It is pretty forward, I don't think it needs explanations. So all set to execute your command now,

Invoke-Expression $command

I would recommend catching the exception here

jQuery show for 5 seconds then hide

Just as simple as this:

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

How to find if div with specific id exists in jQuery?

Here is the jQuery function I use:

function isExists(var elemId){
    return jQuery('#'+elemId).length > 0;
}

This will return a boolean value. If element exists, it returns true. If you want to select element by class name, just replace # with .

How do I detect if software keyboard is visible on Android Device or not?

There is no direct way - see http://groups.google.com/group/android-platform/browse_thread/thread/1728f26f2334c060/5e4910f0d9eb898a where Dianne Hackborn from the Android team has replied. However, you can detect it indirectly by checking if the window size changed in #onMeasure. See How to check visibility of software keyboard in Android?.

Post multipart request with Android SDK

More easy, light (32k), and many more performance:

Android Asynchronous Http Client library: http://loopj.com/android-async-http/

Implementation:

How to send a “multipart/form-data” POST in Android with Volley

HTTP Request in Swift with POST method

All the answers here use JSON objects. This gave us problems with the $this->input->post() methods of our Codeigniter controllers. The CI_Controller cannot read JSON directly. We used this method to do it WITHOUT JSON

func postRequest() {
    // Create url object
    guard let url = URL(string: yourURL) else {return}

    // Create the session object
    let session = URLSession.shared

    // Create the URLRequest object using the url object
    var request = URLRequest(url: url)

    // Set the request method. Important Do not set any other headers, like Content-Type
    request.httpMethod = "POST" //set http method as POST

    // Set parameters here. Replace with your own.
    let postData = "param1_id=param1_value&param2_id=param2_value".data(using: .utf8)
    request.httpBody = postData

    // Create a task using the session object, to run and return completion handler
    let webTask = session.dataTask(with: request, completionHandler: {data, response, error in
    guard error == nil else {
        print(error?.localizedDescription ?? "Response Error")
        return
    }
    guard let serverData = data else {
        print("server data error")
        return
    }
    do {
        if let requestJson = try JSONSerialization.jsonObject(with: serverData, options: .mutableContainers) as? [String: Any]{
            print("Response: \(requestJson)")
        }
    } catch let responseError {
        print("Serialisation in error in creating response body: \(responseError.localizedDescription)")
        let message = String(bytes: serverData, encoding: .ascii)
        print(message as Any)
    }

    // Run the task
    webTask.resume()
}

Now your CI_Controller will be able to get param1 and param2 using $this->input->post('param1') and $this->input->post('param2')

How to find the difference in days between two dates?

This assumes that a month is 1/12 of a year:

#!/usr/bin/awk -f
function mktm(datespec) {
  split(datespec, q, "-")
  return q[1] * 365.25 + q[3] * 365.25 / 12 + q[2]
}
BEGIN {
  printf "%d\n", mktm(ARGV[2]) - mktm(ARGV[1])
}

Fatal error: Class 'Illuminate\Foundation\Application' not found

I just fixed this problem (Different Case with same error),
The answer above I tried may not work because My case were different but produced the same error.
I think my vendor libraries were jumbled,
I get this error by:
1. Pull from remote git, master branch is codeigniter then I do composer update on master branch, I wanted to work on laravel branch then I checkout and do composer update so I get the error,

Fatal error: Class 'Illuminate\Foundation\Application' not found in C:\cms\bootstrap\app.php on line 14

Solution: I delete the project on local and do a clone again, after that I checkout to my laravel file work's branch and do composer update then it is fixed.

Media Queries - In between two widths

@Jonathan Sampson i think your solution is wrong if you use multiple @media.

You should use (min-width first):

@media screen and (min-width:400px) and (max-width:900px){
   ...
}

How do I get started with Node.js

Use the source, Luke.

No, but seriously I found that building Node.js from source, running the tests, and looking at the benchmarks did get me on the right track. From there, the .js files in the lib directory are a good place to look, especially the file http.js.

Update: I wrote this answer over a year ago, and since that time there has an explosion in the number of great resources available for people learning Node.js. Though I still believe diving into the source is worthwhile, I think that there are now better ways to get started. I would suggest some of the books on Node.js that are starting to come out.

how does Request.QueryString work?

A query string is an array of parameters sent to a web page.

This url: http://page.asp?x=1&y=hello

Request.QueryString[0] is the same as 
Request.QueryString["x"] and holds a string value "1"

Request.QueryString[1] is the same as 
Request.QueryString["y"] and holds a string value "hello"

[Ljava.lang.Object; cannot be cast to

You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.

In Visual Basic how do you create a block comment

Not in VB.NET, you have to select all lines at then Edit, Advanced, Comment Selection menu, or a keyboard shortcut for that menu.

http://bytes.com/topic/visual-basic-net/answers/376760-how-block-comment

http://forums.asp.net/t/1011404.aspx/1

Reducing MongoDB database file size

mongoDB -repair is not recommended in case of sharded cluster.

If using replica set sharded cluster, use compact command, it will rewrites and defragments all data and index files of all collections. syntax:

db.runCommand( { compact : "collection_name" } )

when used with force:true, compact runs on primary of replica set. e.g. db.runCommand ( { command : "collection_name", force : true } )

Other points to consider: -It blocks the operations. so recommended to execute in maintenance window. -If replica sets running on different servers, needs to be execute on each member separately - In case of sharded cluster, compact needs to execute on each shard member separately. Cannot execute against mongos instance.

What is Android keystore file, and what is it used for?

Android Market requires you to sign all apps you publish with a certificate, using a public/private key mechanism (the certificate is signed with your private key). This provides a layer of security that prevents, among other things, remote attackers from pushing malicious updates to your application to market (all updates must be signed with the same key).

From The App-Signing Guide of the Android Developer's site:

In general, the recommended strategy for all developers is to sign all of your applications with the same certificate, throughout the expected lifespan of your applications. There are several reasons why you should do so...

Using the same key has a few benefits - One is that it's easier to share data between applications signed with the same key. Another is that it allows multiple apps signed with the same key to run in the same process, so a developer can build more "modular" applications.

Folder is locked and I can't unlock it

Using svn command line to unlock the local folders, just use svn cleanup.

Before:

# svn commit -m "fixing #1234"

commit

# svn st

before

# svn cleanup

After:

# svn st

after

# svn commit -m "fixing #1234"

after2

Plot a horizontal line using matplotlib

Use matplotlib.pyplot.hlines:

  • Plot multiple horizontal lines by passing a list to the y parameter.
  • y can be passed as a single location: y=40
  • y can be passed as multiple locations: y=[39, 40, 41]
  • If you're a plotting a figure with something like fig, ax = plt.subplots(), then replace plt.hlines or plt.axhline with ax.hlines or ax.axhline, respectively.
  • matplotlib.pyplot.axhline can only plot a single location (e.g. y=40)

plt.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(6, 3))
plt.hlines(y=39.5, xmin=100, xmax=175, colors='aqua', linestyles='-', lw=2, label='Single Short Line')
plt.hlines(y=[39, 40, 41], xmin=[0, 25, 50], xmax=[len(xs)], colors='purple', linestyles='--', lw=2, label='Multiple Lines')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)

enter image description here

ax.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6))

ax1.hlines(y=40, xmin=0, xmax=len(xs), colors='r', linestyles='--', lw=2)
ax1.set_title('One Line')

ax2.hlines(y=[39, 40, 41], xmin=0, xmax=len(xs), colors='purple', linestyles='--', lw=2)
ax2.set_title('Multiple Lines')

plt.tight_layout()
plt.show()

enter image description here

Time Series Axis

  • xmin and xmax will accept a date like '2020-09-10' or datetime(2020, 9, 10)
    • xmin=datetime(2020, 9, 10), xmax=datetime(2020, 9, 10) + timedelta(days=3)
    • Given date = df.index[9], xmin=date, xmax=date + pd.Timedelta(days=3), where the index is a DatetimeIndex.
import pandas_datareader as web  # conda or pip install this; not part of pandas
import pandas as pd
import matplotlib.pyplot as plt

# get test data
df = web.DataReader('^gspc', data_source='yahoo', start='2020-09-01', end='2020-09-28').iloc[:, :2]

# plot dataframe
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')

# add horizontal line
ax.hlines(y=3450, xmin='2020-09-10', xmax='2020-09-17', color='purple', label='test')

ax.legend()
plt.show()

enter image description here

  • Sample time series data if web.DataReader doesn't work.
data = {pd.Timestamp('2020-09-01 00:00:00'): {'High': 3528.03, 'Low': 3494.6}, pd.Timestamp('2020-09-02 00:00:00'): {'High': 3588.11, 'Low': 3535.23}, pd.Timestamp('2020-09-03 00:00:00'): {'High': 3564.85, 'Low': 3427.41}, pd.Timestamp('2020-09-04 00:00:00'): {'High': 3479.15, 'Low': 3349.63}, pd.Timestamp('2020-09-08 00:00:00'): {'High': 3379.97, 'Low': 3329.27}, pd.Timestamp('2020-09-09 00:00:00'): {'High': 3424.77, 'Low': 3366.84}, pd.Timestamp('2020-09-10 00:00:00'): {'High': 3425.55, 'Low': 3329.25}, pd.Timestamp('2020-09-11 00:00:00'): {'High': 3368.95, 'Low': 3310.47}, pd.Timestamp('2020-09-14 00:00:00'): {'High': 3402.93, 'Low': 3363.56}, pd.Timestamp('2020-09-15 00:00:00'): {'High': 3419.48, 'Low': 3389.25}, pd.Timestamp('2020-09-16 00:00:00'): {'High': 3428.92, 'Low': 3384.45}, pd.Timestamp('2020-09-17 00:00:00'): {'High': 3375.17, 'Low': 3328.82}, pd.Timestamp('2020-09-18 00:00:00'): {'High': 3362.27, 'Low': 3292.4}, pd.Timestamp('2020-09-21 00:00:00'): {'High': 3285.57, 'Low': 3229.1}, pd.Timestamp('2020-09-22 00:00:00'): {'High': 3320.31, 'Low': 3270.95}, pd.Timestamp('2020-09-23 00:00:00'): {'High': 3323.35, 'Low': 3232.57}, pd.Timestamp('2020-09-24 00:00:00'): {'High': 3278.7, 'Low': 3209.45}, pd.Timestamp('2020-09-25 00:00:00'): {'High': 3306.88, 'Low': 3228.44}, pd.Timestamp('2020-09-28 00:00:00'): {'High': 3360.74, 'Low': 3332.91}}

df = pd.DataFrame.from_dict(data, 'index')

List of all special characters that need to be escaped in a regex

On @Sorin's suggestion of the Java Pattern docs, it looks like chars to escape are at least:

\.[{(*+?^$|

Debug/run standard java in Visual Studio Code IDE and OS X?

There is a much easier way to run Java, no configuration needed:

  1. Install the Code Runner Extension
  2. Open your Java code file in Text Editor, then use shortcut Ctrl+Alt+N, or press F1 and then select/type Run Code, or right click the Text Editor and then click Run Code in context menu, the code will be compiled and run, and the output will be shown in the Output Window.

runJave

Display all views on oracle database

Open a new worksheet on the related instance (Alt-F10) and run the following query

SELECT view_name, owner
FROM sys.all_views 
ORDER BY owner, view_name

'printf' vs. 'cout' in C++

TL;DR: Always do your own research, in regard of generated machine code size, performance, readability and coding time before trusting random comments online, including this one.

I'm no expert. I just happened to overhear two co-workers talking about how we should avoid using C++ in embedded systems because of performance issues. Well, interesting enough, I did a benchmark based on a real project task.

In said task, we had to write some config to RAM. Something like:

coffee=hot
sugar=none
milk=breast
mac=AA:BB:CC:DD:EE:FF

Here's my benchmark programs (Yes, I know OP asked about printf(), not fprintf(). Try to capture the essence and by the way, OP's link points to fprintf() anyway.)

C program:

char coffee[10], sugar[10], milk[10];
unsigned char mac[6];

/* Initialize those things here. */

FILE * f = fopen("a.txt", "wt");

fprintf(f, "coffee=%s\nsugar=%s\nmilk=%s\nmac=%02X:%02X:%02X:%02X:%02X:%02X\n", coffee, sugar, milk, mac[0], mac[1],mac[2],mac[3],mac[4],mac[5]);

fclose(f);

C++ program:

//Everything else is identical except:

std::ofstream f("a.txt", std::ios::out);

f << "coffee=" << coffee << "\n";
f << "sugar=" << sugar << "\n";
f << "milk=" << milk << "\n";
f << "mac=" << (int)mac[0] << ":"
    << (int)mac[1] << ":"
    << (int)mac[2] << ":"
    << (int)mac[3] << ":"
    << (int)mac[4] << ":"
    << (int)mac[5] << endl;
f.close();

I did my best to polish them before I looped them both 100,000 times. Here are the results:

C program:

real    0m 8.01s
user    0m 2.37s
sys     0m 5.58s

C++ program:

real    0m 6.07s
user    0m 3.18s
sys     0m 2.84s

Object file size:

C   - 2,092 bytes
C++ - 3,272 bytes

Conclusion: On my very specific platform, with a very specific processor, running a very specific version of Linux kernel, to run a program which is compiled with a very specific version of GCC, in order to accomplish a very specific task, I would say the C++ approach is more suitable because it runs significantly faster and provide much better readability. On the other hand, C offers small footprint, in my opinion, means nearly nothing because program size is not of our concern.

Remeber, YMMV.

tar: file changed as we read it

I am not sure does it suit you but I noticed that tar does not fail on changed/deleted files in pipe mode. See what I mean.

Test script:

#!/usr/bin/env bash
set -ex
tar cpf - ./files | aws s3 cp - s3://my-bucket/files.tar
echo $?

Deleting random files manually...

Output:

+ aws s3 cp - s3://my-bucket/files.tar
+ tar cpf - ./files
tar: ./files/default_images: File removed before we read it
tar: ./files: file changed as we read it
+ echo 0
0

Google Play Services GCM 9.2.0 asks to "update" back to 9.0.0

For Cordova OR Ionic Hybrid App

I have the very similar problem with my Ionic 1 Cordova Build after Integrating the Firebase Cloud Messaging ( FCM )

I fixed this issue by the following steps

So one fix will be: inside platforms/android open project.properties (Its a file ) , you will have something like this

cordova.system.library.1=com.google.android.gms:play-services-ads:+
cordova.system.library.2=com.google.firebase:firebase-core:+
cordova.system.library.3=com.google.firebase:firebase-messaging:+

Replace the

+

Sign with your target version number - like the following

cordova.system.library.1=com.google.android.gms:play-services-ads:9.0.0
cordova.system.library.2=com.google.firebase:firebase-core:9.0.0
cordova.system.library.3=com.google.firebase:firebase-messaging:9.0.0

Save the file

Then take build using

 ionic cordova run android

I hope this will work for everyone

Reminder - \r\n or \n\r?

If you are using C# you should use Environment.NewLine, which accordingly to MSDN it is:

A string containing "\r\n" for non-Unix platforms, or a string containing "\n" for Unix platforms.

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

In C#, how to check if a TCP port is available?

string hostname = "localhost";
int portno = 9081;
IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];


try
{
    System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
    sock.Connect(ipa, portno);
    if (sock.Connected == true)  // Port is in use and connection is successful
            MessageBox.Show("Port is Closed");
    sock.Close();

}
catch (System.Net.Sockets.SocketException ex)
{
    if (ex.ErrorCode == 10061)  // Port is unused and could not establish connection 
        MessageBox.Show("Port is Open!");
    else
        MessageBox.Show(ex.Message);
}

C++ equivalent of StringBuffer/StringBuilder?

NOTE this answer has received some attention recently. I am not advocating this as a solution (it is a solution I have seen in the past, before the STL). It is an interesting approach and should only be applied over std::string or std::stringstream if after profiling your code you discover this makes an improvement.

I normally use either std::string or std::stringstream. I have never had any problems with these. I would normally reserve some room first if I know the rough size of the string in advance.

I have seen other people make their own optimized string builder in the distant past.

class StringBuilder {
private:
    std::string main;
    std::string scratch;

    const std::string::size_type ScratchSize = 1024;  // or some other arbitrary number

public:
    StringBuilder & append(const std::string & str) {
        scratch.append(str);
        if (scratch.size() > ScratchSize) {
            main.append(scratch);
            scratch.resize(0);
        }
        return *this;
    }

    const std::string & str() {
        if (scratch.size() > 0) {
            main.append(scratch);
            scratch.resize(0);
        }
        return main;
    }
};

It uses two strings one for the majority of the string and the other as a scratch area for concatenating short strings. It optimise's appends by batching the short append operations in one small string then appending this to the main string, thus reducing the number of reallocations required on the main string as it gets larger.

I have not required this trick with std::string or std::stringstream. I think it was used with a third party string library before std::string, it was that long ago. If you adopt a strategy like this profile your application first.

Keep CMD open after BAT file executes

In Windows add '& Pause' to the end of your command in the file.

How can I reduce the waiting (ttfb) time

TTFB is something that happens behind the scenes. Your browser knows nothing about what happens behind the scenes.

You need to look into what queries are being run and how the website connects to the server.

This article might help understand TTFB, but otherwise you need to dig deeper into your application.

What are the best practices for using a GUID as a primary key, specifically regarding performance?

I've been using GUIDs as PKs since 2005. In this distributed database world, it is absolutely the best way to merge distributed data. You can fire and forget merge tables without all the worry of ints matching across joined tables. GUIDs joins can be copied without any worry.

This is my setup for using GUIDs:

  1. PK = GUID. GUIDs are indexed similar to strings, so high row tables (over 50 million records) may need table partitioning or other performance techniques. SQL Server is getting extremely efficient, so performance concerns are less and less applicable.

  2. PK Guid is NON-Clustered index. Never cluster index a GUID unless it is NewSequentialID. But even then, a server reboot will cause major breaks in ordering.

  3. Add ClusterID Int to every table. This is your CLUSTERED Index... that orders your table.

  4. Joining on ClusterIDs (int) is more efficient, but I work with 20-30 million record tables, so joining on GUIDs doesn't visibly affect performance. If you want max performance, use the ClusterID concept as your primary key & join on ClusterID.

Here is my Email table...

CREATE TABLE [Core].[Email] (
    [EmailID]      UNIQUEIDENTIFIER CONSTRAINT [DF_Email_EmailID] DEFAULT (newsequentialid()) NOT NULL,        
    [EmailAddress] NVARCHAR (50)    CONSTRAINT [DF_Email_EmailAddress] DEFAULT ('') NOT NULL,        
    [CreatedDate]  DATETIME         CONSTRAINT [DF_Email_CreatedDate] DEFAULT (getutcdate()) NOT NULL,      
    [ClusterID] INT NOT NULL IDENTITY,
    CONSTRAINT [PK_Email] PRIMARY KEY NonCLUSTERED ([EmailID] ASC)
);
GO

CREATE UNIQUE CLUSTERED INDEX [IX_Email_ClusterID] ON [Core].[Email] ([ClusterID])
GO

CREATE UNIQUE NONCLUSTERED INDEX [IX_Email_EmailAddress] ON [Core].[Email] ([EmailAddress] Asc)

Convert Java Array to Iterable

You can use IterableOf from Cactoos:

Iterable<String> names = new IterableOf<>(
  "Scott Fitzgerald", "Fyodor Dostoyevsky"
);

Then, you can turn it into a list using ListOf:

List<String> names = new ListOf<>(
  new IterableOf<>(
    "Scott Fitzgerald", "Fyodor Dostoyevsky"
  )
);

Or simply this:

List<String> names = new ListOf<>(
  "Scott Fitzgerald", "Fyodor Dostoyevsky"
);

How to create a temporary directory?

My favorite one-liner for this is

cd $(mktemp -d)

Codeigniter displays a blank page instead of error messages

you can set it in the main index.php

    define('ENVIRONMENT', 'development');
/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'development':
            error_reporting(E_ALL);
        break;

    case 'testing':
    case 'production':
        error_reporting(0);
    break;

    default:
        exit('The application environment is not set correctly.');
}
}

How can I find the number of years between two dates?

Here's what I think is a better method:

public int getYearsBetweenDates(Date first, Date second) {
    Calendar firstCal = GregorianCalendar.getInstance();
    Calendar secondCal = GregorianCalendar.getInstance();

    firstCal.setTime(first);
    secondCal.setTime(second);

    secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));

    return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
}

EDIT

Apart from a bug which I fixed, this method does not work well with leap years. Here's a complete test suite. I guess you're better off using the accepted answer.

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

class YearsBetweenDates {
    public static int getYearsBetweenDates(Date first, Date second) {
        Calendar firstCal = GregorianCalendar.getInstance();
        Calendar secondCal = GregorianCalendar.getInstance();

        firstCal.setTime(first);
        secondCal.setTime(second);

        secondCal.add(Calendar.DAY_OF_YEAR, 1 - firstCal.get(Calendar.DAY_OF_YEAR));

        return secondCal.get(Calendar.YEAR) - firstCal.get(Calendar.YEAR);
    }

    private static class TestCase {
        public Calendar date1;
        public Calendar date2;
        public int expectedYearDiff;
        public String comment;

        public TestCase(Calendar date1, Calendar date2, int expectedYearDiff, String comment) {
            this.date1 = date1;
            this.date2 = date2;
            this.expectedYearDiff = expectedYearDiff;
            this.comment = comment;
        }
    }

    private static TestCase[] tests = {
        new TestCase(
                new GregorianCalendar(2014, Calendar.JULY, 15),
                new GregorianCalendar(2015, Calendar.JULY, 15),
                1,
                "exactly one year"),
        new TestCase(
                new GregorianCalendar(2014, Calendar.JULY, 15),
                new GregorianCalendar(2017, Calendar.JULY, 14),
                2,
                "one day less than 3 years"),
        new TestCase(
                new GregorianCalendar(2015, Calendar.NOVEMBER, 3),
                new GregorianCalendar(2017, Calendar.MAY, 3),
                1,
                "a year and a half"),
        new TestCase(
                new GregorianCalendar(2016, Calendar.JULY, 15),
                new GregorianCalendar(2017, Calendar.JULY, 15),
                1,
                "leap years do not compare correctly"),
    };

    public static void main(String[] args) {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        for (TestCase t : tests) {
            int diff = getYearsBetweenDates(t.date1.getTime(), t.date2.getTime());
            String result = diff == t.expectedYearDiff ? "PASS" : "FAIL";
            System.out.println(t.comment + ": " +
                    df.format(t.date1.getTime()) + " -> " +
                    df.format(t.date2.getTime()) + " = " +
                    diff + ": " + result);
        }
    }
}

What causes this error? "Runtime error 380: Invalid property value"

error 380 windows 7 solution very easy just check your date time & regional setting do them correct.

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

How to split a string in Haskell?

Use Data.List.Split, which uses split:

[me@localhost]$ ghci
Prelude> import Data.List.Split
Prelude Data.List.Split> let l = splitOn "," "1,2,3,4"
Prelude Data.List.Split> :t l
l :: [[Char]]
Prelude Data.List.Split> l
["1","2","3","4"]
Prelude Data.List.Split> let { convert :: [String] -> [Integer]; convert = map read }
Prelude Data.List.Split> let l2 = convert l
Prelude Data.List.Split> :t l2
l2 :: [Integer]
Prelude Data.List.Split> l2
[1,2,3,4]

How to change Navigation Bar color in iOS 7?

For Color :

[[UINavigationBar appearance] setBarTintColor:[UIColor blackColor]];

For Image

[[UINavigationBar appearance] setBackgroundImage:[UIImage imageNamed:@"navigationBar_320X44.png"] forBarMetrics:UIBarMetricsDefault];

Display label text with line breaks in c#

Or simply add one line of:

Text='<%# Eval("Comments").ToString().Replace("\n","<br />") %>'

Difference between h:button and h:commandButton

This is taken from the book - The Complete Reference by Ed Burns & Chris Schalk

h:commandButton vs h:button

What’s the difference between h:commandButton|h:commandLink and h:button|h:link ?

The latter two components were introduced in 2.0 to enable bookmarkable JSF pages, when used in concert with the View Parameters feature.

There are 3 main differences between h:button|h:link and h:commandButton|h:commandLink.

First, h:button|h:link causes the browser to issue an HTTP GET request, while h:commandButton|h:commandLink does a form POST. This means that any components in the page that have values entered by the user, such as text fields, checkboxes, etc., will not automatically be submitted to the server when using h:button|h:link. To cause values to be submitted with h:button|h:link, extra action has to be taken, using the “View Parameters” feature.

The second main difference between the two kinds of components is that h:button|h:link has an outcome attribute to describe where to go next while h:commandButton|h:commandLink uses an action attribute for this purpose. This is because the former does not result in an ActionEvent in the event system, while the latter does.

Finally, and most important to the complete understanding of this feature, the h:button|h:link components cause the navigation system to be asked to derive the outcome during the rendering of the page, and the answer to this question is encoded in the markup of the page. In contrast, the h:commandButton|h:commandLink components cause the navigation system to be asked to derive the outcome on the POSTBACK from the page. This is a difference in timing. Rendering always happens before POSTBACK.

Unable to resolve dependency for ':app@debug/compileClasspath': Could not resolve

Try to add type of configuration in dependency line. For example:

implementation project(path: ':some_module', **configuration: 'default'**)`

Sublime Text 2 Code Formatting

A similar option in Sublime Text is the built in Edit->Line->Reindent. You can put this code in Preferences -> Key Bindings User:

{ "keys": ["alt+shift+f"], "command": "reindent"} 

I use alt+shift+f because I'm a Netbeans user.

To format your code, select all by pressing ctrl+a and "your key combination". Excuse me for my bad english.


Or if you don't want to select all before formatting, add an argument to the command instead:

{ "keys": ["alt+shift+f"], "command": "reindent", "args": {"single_line": false} }

(as per comment by @Supr below)

Gradle build without tests

You will have to add -x test

e.g. ./gradlew build -x test

or

gradle build -x test

Reference to non-static member function must be called

You may want to have a look at https://isocpp.org/wiki/faq/pointers-to-members#fnptr-vs-memfnptr-types, especially [33.1] Is the type of "pointer-to-member-function" different from "pointer-to-function"?

Convert char to int in C and C++

Use static_cast<int>:

int num = static_cast<int>(letter); // if letter='a', num=97

Edit: You probably should try to avoid to use (int)

int num = (int) letter;

check out Why use static_cast<int>(x) instead of (int)x? for more info.

Scala list concatenation, ::: vs ++

Always use :::. There are two reasons: efficiency and type safety.

Efficiency

x ::: y ::: z is faster than x ++ y ++ z, because ::: is right associative. x ::: y ::: z is parsed as x ::: (y ::: z), which is algorithmically faster than (x ::: y) ::: z (the latter requires O(|x|) more steps).

Type safety

With ::: you can only concatenate two Lists. With ++ you can append any collection to List, which is terrible:

scala> List(1, 2, 3) ++ "ab"
res0: List[AnyVal] = List(1, 2, 3, a, b)

++ is also easy to mix up with +:

scala> List(1, 2, 3) + "ab"
res1: String = List(1, 2, 3)ab

Java - Create a new String instance with specified length and filled with specific character. Best solution?

Mi solution :

  pw = "1321";
    if (pw.length() < 16){
      for(int x = pw.length() ; x < 16 ; x++){
        pw  += "*";
      }
    }

The output :

1321************

Block direct access to a file over http but allow php script access

How about custom module based .htaccess script (like its used in CodeIgniter)? I tried and it worked good in CodeIgniter apps. Any ideas to use it on other apps?

<IfModule authz_core_module>
    Require all denied
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

How to split a number into individual digits in c#?

You can simply do:

"123456".Select(q => new string(q,1)).ToArray();

to have an enumerable of integers, as per comment request, you can:

"123456".Select(q => int.Parse(new string(q,1))).ToArray();

It is a little weak since it assumes the string actually contains numbers.

Convert array to JSON string in swift

Hint: To convert an NSArray containing JSON compatible objects to an NSData object containing a JSON document, use the appropriate method of NSJSONSerialization. JSONObjectWithData is not it.

Hint 2: You rarely want that data as a string; only for debugging purposes.

How to disable mouse right click on a web page?

Firstly, if you are doing this just to prevent people viewing the source of your page - it won't work, because they can always use a keyboard shortcut to view it.

Secondly, you will have to use JavaScript to accomplish this. If the user has JS disabled, you cannot prevent the right click.

That said, add this to your body tag to disable right clicks.

<body oncontextmenu="return false;">

How do I count the number of rows and columns in a file using bash?

If your file is big but you are certain that the number of columns remains the same for each row (and you have no heading) use:

head -n 1 FILE | awk '{print NF}'

to find the number of columns, where FILE is your file name.

To find the number of lines 'wc -l FILE' will work.

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

JAVA Unsupported major.minor version 51.0

This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7

You may also check Unsupported major.minor version 51.0

Is it possible in Java to catch two exceptions in the same catch block?

Java <= 6.x just allows you to catch one exception for each catch block:

try {

} catch (ExceptionType name) {

} catch (ExceptionType name) {

}

Documentation:

Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.

For Java 7 you can have multiple Exception caught on one catch block:

catch (IOException|SQLException ex) {
    logger.log(ex);
    throw ex;
}

Documentation:

In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.

Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html

How to select records without duplicate on just one field in SQL?

DISTINCT is the keyword
For me your query is correct

Just try to do this first

SELECT DISTINCT title,id FROM tbl_countries

Later on you can try with order by.

Python: list of lists

Lists are a mutable type - in order to create a copy (rather than just passing the same list around), you need to do so explicitly:

listoflists.append((list[:], list[0]))

However, list is already the name of a Python built-in - it'd be better not to use that name for your variable. Here's a version that doesn't use list as a variable name, and makes a copy:

listoflists = []
a_list = []
for i in range(0,10):
    a_list.append(i)
    if len(a_list)>3:
        a_list.remove(a_list[0])
        listoflists.append((list(a_list), a_list[0]))
print listoflists

Note that I demonstrated two different ways to make a copy of a list above: [:] and list().

The first, [:], is creating a slice (normally often used for getting just part of a list), which happens to contain the entire list, and thus is effectively a copy of the list.

The second, list(), is using the actual list type constructor to create a new list which has contents equal to the first list. (I didn't use it in the first example because you were overwriting that name in your code - which is a good example of why you don't want to do that!)

How to edit default.aspx on SharePoint site without SharePoint Designer

I was able to accomplish editing the default.aspx page by:

  • Opening the site in SharePoint Designer 2013
  • Then clicking 'All Files' to view all of the files,
  • Then right-click -> Edit file in Advanced Mode.

By doing that I was able to remove the tagprefix causing a problem on my page.

d3 add text to circle

Extended the example above to fit the actual requirements, where circled is filled with solid background color, then with striped pattern & after that text node is placed on the center of the circle.

_x000D_
_x000D_
var width = 960,_x000D_
  height = 500,_x000D_
  json = {_x000D_
    "nodes": [{_x000D_
      "x": 100,_x000D_
      "r": 20,_x000D_
      "label": "Node 1",_x000D_
      "color": "red"_x000D_
    }, {_x000D_
      "x": 200,_x000D_
      "r": 25,_x000D_
      "label": "Node 2",_x000D_
      "color": "blue"_x000D_
    }, {_x000D_
      "x": 300,_x000D_
      "r": 30,_x000D_
      "label": "Node 3",_x000D_
      "color": "green"_x000D_
    }]_x000D_
  };_x000D_
_x000D_
var svg = d3.select("body").append("svg")_x000D_
  .attr("width", width)_x000D_
  .attr("height", height)_x000D_
_x000D_
svg.append("defs")_x000D_
  .append("pattern")_x000D_
  .attr({_x000D_
    "id": "stripes",_x000D_
    "width": "8",_x000D_
    "height": "8",_x000D_
    "fill": "red",_x000D_
    "patternUnits": "userSpaceOnUse",_x000D_
    "patternTransform": "rotate(60)"_x000D_
  })_x000D_
  .append("rect")_x000D_
  .attr({_x000D_
    "width": "4",_x000D_
    "height": "8",_x000D_
    "transform": "translate(0,0)",_x000D_
    "fill": "grey"_x000D_
  });_x000D_
_x000D_
function plotChart(json) {_x000D_
  /* Define the data for the circles */_x000D_
  var elem = svg.selectAll("g myCircleText")_x000D_
    .data(json.nodes)_x000D_
_x000D_
  /*Create and place the "blocks" containing the circle and the text */_x000D_
  var elemEnter = elem.enter()_x000D_
    .append("g")_x000D_
    .attr("class", "node-group")_x000D_
    .attr("transform", function(d) {_x000D_
      return "translate(" + d.x + ",80)"_x000D_
    })_x000D_
_x000D_
  /*Create the circle for each block */_x000D_
  var circleInner = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", function(d) {_x000D_
      return d.color;_x000D_
    });_x000D_
_x000D_
  var circleOuter = elemEnter.append("circle")_x000D_
    .attr("r", function(d) {_x000D_
      return d.r_x000D_
    })_x000D_
    .attr("stroke", function(d) {_x000D_
      return d.color;_x000D_
    })_x000D_
    .attr("fill", "url(#stripes)");_x000D_
_x000D_
  /* Create the text for each block */_x000D_
  elemEnter.append("text")_x000D_
    .text(function(d) {_x000D_
      return d.label_x000D_
    })_x000D_
    .attr({_x000D_
      "text-anchor": "middle",_x000D_
      "font-size": function(d) {_x000D_
        return d.r / ((d.r * 10) / 100);_x000D_
      },_x000D_
      "dy": function(d) {_x000D_
        return d.r / ((d.r * 25) / 100);_x000D_
      }_x000D_
    });_x000D_
};_x000D_
_x000D_
plotChart(json);
_x000D_
.node-group {_x000D_
  fill: #ffffff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
_x000D_
_x000D_
_x000D_

Output:

enter image description here

Below is the link to codepen also:

See the Pen D3-Circle-Pattern-Text by Manish Kumar (@mkdudeja) on CodePen.

Thanks, Manish Kumar

Assign value from successful promise resolve to external variable

The then() method returns a Promise. It takes two arguments, both are callback functions for the success and failure cases of the Promise. the promise object itself doesn't give you the resolved data directly, the interface of this object only provides the data via callbacks supplied. So, you have to do this like this:

getFeed().then(function(data) { vm.feed = data;});

The then() function returns the promise with a resolved value of the previous then() callback, allowing you the pass the value to subsequent callbacks:

promiseB = promiseA.then(function(result) {
  return result + 1;
});

// promiseB will be resolved immediately after promiseA is resolved
// and its value will be the result of promiseA incremented by 1

PostgreSQL - fetch the row which has the Max value for a column

SELECT  l.*
FROM    (
        SELECT DISTINCT usr_id
        FROM   lives
        ) lo, lives l
WHERE   l.ctid = (
        SELECT ctid
        FROM   lives li
        WHERE  li.usr_id = lo.usr_id
        ORDER BY
          time_stamp DESC, trans_id DESC
        LIMIT 1
        )

Creating an index on (usr_id, time_stamp, trans_id) will greatly improve this query.

You should always, always have some kind of PRIMARY KEY in your tables.

How can I directly view blobs in MySQL Workbench

casting works, but it is a pain, so I would recommend using spioter's method unless you are using a lot of truly blob data.

SELECT CAST(OLD_PASSWORD("test") AS CHAR)

You can also cast as other types, and even restrict the size, but most of the time I just use CHAR: http://dev.mysql.com/doc/refman/5.5/en/cast-functions.html#function_cast

canvas.toDataURL() SecurityError

In my case I was using the WebBrowser control (forcing IE 11) and I could not get past the error. Switching to CefSharp which uses Chrome solved it for me.

How get the base URL via context path in JSF?

URLs are not resolved based on the file structure in the server side. URLs are resolved based on the real public web addresses of the resources in question. It's namely the webbrowser who has got to invoke them, not the webserver.

There are several ways to soften the pain:

JSF EL offers a shorthand to ${pageContext.request} in flavor of #{request}:

<li><a href="#{request.contextPath}/index.xhtml">Home</a></li>
<li><a href="#{request.contextPath}/about_us.xhtml">About us</a></li>

You can if necessary use <c:set> tag to make it yet shorter. Put it somewhere in the master template, it'll be available to all pages:

<c:set var="root" value="#{request.contextPath}/" />
...
<li><a href="#{root}index.xhtml">Home</a></li>
<li><a href="#{root}about_us.xhtml">About us</a></li>

JSF 2.x offers the <h:link> which can take a view ID relative to the context root in outcome and it will append the context path and FacesServlet mapping automatically:

<li><h:link value="Home" outcome="index" /></li>
<li><h:link value="About us" outcome="about_us" /></li>

HTML offers the <base> tag which makes all relative URLs in the document relative to this base. You could make use of it. Put it in the <h:head>.

<base href="#{request.requestURL.substring(0, request.requestURL.length() - request.requestURI.length())}#{request.contextPath}/" />
...
<li><a href="index.xhtml">Home</a></li>
<li><a href="about_us.xhtml">About us</a></li>

(note: this requires EL 2.2, otherwise you'd better use JSTL fn:substring(), see also this answer)

This should end up in the generated HTML something like as

<base href="http://example.com/webname/" />

Note that the <base> tag has a caveat: it makes all jump anchors in the page like <a href="#top"> relative to it as well! See also Is it recommended to use the <base> html tag? In JSF you could solve it like <a href="#{request.requestURI}#top">top</a> or <h:link value="top" fragment="top" />.

How can I change default dialog button text color in android 5

The color of the buttons and other text can also be changed via theme:

values-21/styles.xml

<style name="AppTheme" parent="...">
  ...
  <item name="android:timePickerDialogTheme">@style/AlertDialogCustom</item>
  <item name="android:datePickerDialogTheme">@style/AlertDialogCustom</item>
  <item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>

<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
  <item name="android:colorPrimary">#00397F</item>
  <item name="android:colorAccent">#0AAEEF</item>
</style>

The result:

Dialog Date picker

Convert base64 string to image

Server side encoding files/Images to base64String ready for client side consumption

public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
    if (inputStream.isPresent()) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        FileCopyUtils.copy(inputStream.get(), output);
        //TODO retrieve content type from file, & replace png below with it
        return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
    }

    return Optional.empty();
}

Server side base64 Image/File decoder

public Optional<InputStream> Base64InputStream(Optional<String> base64String)throws IOException {
    if (base64String.isPresent()) {
        return Optional.ofNullable(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(base64String.get())));
    }

    return Optional.empty();
}

Git Pull While Ignoring Local Changes?

If you are on Linux:

git fetch
for file in `git diff origin/master..HEAD --name-only`; do rm -f "$file"; done
git pull

The for loop will delete all tracked files which are changed in the local repo, so git pull will work without any problems.
The nicest thing about this is that only the tracked files will be overwritten by the files in the repo, all other files will be left untouched.

Drop primary key using script in SQL Server database

simply click

'Database'>tables>your table name>keys>copy the constraints like 'PK__TableName__30242045'

and run the below query is :

Query:alter Table 'TableName' drop constraint PK__TableName__30242045

python: NameError:global name '...‘ is not defined

You need to call self.a() to invoke a from b. a is not a global function, it is a method on the class.

You may want to read through the Python tutorial on classes some more to get the finer details down.

Changing the git user inside Visual Studio Code

I resolved this issue by setting an email address in Git:

git config --global user.email "[email protected]"

How to run jenkins as a different user

If you really want to run Jenkins as you, I suggest you check out my Jenkins.app. An alternative, easy way to run Jenkins on Mac.

See https://github.com/stisti/jenkins-app/

Download it from https://github.com/stisti/jenkins-app/downloads

Error while trying to run project: Unable to start program. Cannot find the file specified

I personally have this issue in Visual 2012 with x64 applications when I check the option "Managed C++ Compatibility Mode" of Debugging->General options of Tools->Options menu. => Unchecking this option fixes the problem.

How to create an array for JSON using PHP?

Simple: Just create a (nested) PHP array and call json_encode on it. Numeric arrays translate into JSON lists ([]), associative arrays and PHP objects translate into objects ({}). Example:

$a = array(
        array('foo' => 'bar'),
        array('foo' => 'baz'));
$json = json_encode($a);

Gives you:

[{"foo":"bar"},{"foo":"baz"}]

Is there a way to crack the password on an Excel VBA Project?

your excel file's extension change to xml. And open it in notepad. password text find in xml file.

you see like below line;

Sheets("Sheet1").Unprotect Password:="blabla"

(sorry for my bad english)

How to label scatterplot points by name?

Well I did not think this was possible until I went and checked. In some previous version of Excel I could not do this. I am currently using Excel 2013.

This is what you want to do in a scatter plot:

  1. right click on your data point

  2. select "Format Data Labels" (note you may have to add data labels first)

  3. put a check mark in "Values from Cells"
  4. click on "select range" and select your range of labels you want on the points

Example Graph

UPDATE: Colouring Individual Labels

In order to colour the labels individually use the following steps:

  1. select a label. When you first select, all labels for the series should get a box around them like the graph above.
  2. Select the individual label you are interested in editing. Only the label you have selected should have a box around it like the graph below.
  3. On the right hand side, as shown below, Select "TEXT OPTIONS".
  4. Expand the "TEXT FILL" category if required.
  5. Second from the bottom of the category list is "COLOR", select the colour you want from the pallet.

If you have the entire series selected instead of the individual label, text formatting changes should apply to all labels instead of just one.

Colouring

Cannot use a leading ../ to exit above the top directory

I know these answers are enough, but I'll show the place that's throwing an error.

If you have the structure like the below:

  • ./Src/Master.cs - (Master Form Page)
  • ./Invoice/SubFolder/InvoiceEdit.aspx - (Sub Form Page)

If you enter the sub form page, you'll get an error when you use similar like that you've used in master page: Page.ResolveClientUrl("~/Style/img/logo_small.png").

Now ResolveClientUrl is situated in the master page and trying to serve the root folder. But since you are in the subfolder, the function returns something like ../../Style/img/logo_small.png. This is the wrong way.

Because when you're up two levels, you are not in the right place; you need to go up only one level, so something like ../.

Input size vs width

size is inconsistent across different browsers and their possible font settings.

The width style set in px will at least be consistent, modulo box-sizing issues. You might also want to set the style in ‘em’ if you want to size it relative to the font (though again, this will be inconsistent unless you set the input's font family and size explicitly), or ‘%’ if you are making a liquid-layout form. Either way, a stylesheet is probably preferable to the inline style attribute.

You still need size for <select multiple> to get the height to line up with the options properly. But I'd not use it on an <input>.

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

Python: Total sum of a list of numbers with the for loop

x=[1,2,3,4,5]
sum=0
for s in range(0,len(x)):
   sum=sum+x[s]
print sum   

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

Invoking Java main method with parameters from Eclipse

AFAIK there isn't a built-in mechanism in Eclipse for this.

The closest you can get is to create a wrapper that prompts you for these values and invokes the (hardcoded) main. You then get you execution history as long as you don't clear terminated processes. Two variations on this are either to use JUNit, or to use injection or parameter so that your wrapper always connects to the correct class for its main.

package javax.mail and javax.mail.internet do not exist

  1. Download the Java mail jars.

  2. Extract the downloaded file.

  3. Copy the ".jar" file and paste it into ProjectName\WebContent\WEB-INF\lib folder

  4. Right click on the Project and go to Properties

  5. Select Java Build Path and then select Libraries

  6. Add JARs...

  7. Select the .jar file from ProjectName\WebContent\WEB-INF\lib and click OK

    that's all

Forward host port to docker container

You could also create an ssh tunnel.

docker-compose.yml:

---

version: '2'

services:
  kibana:
    image: "kibana:4.5.1"
    links:
      - elasticsearch
    volumes:
      - ./config/kibana:/opt/kibana/config:ro

  elasticsearch:
    build:
      context: .
      dockerfile: ./docker/Dockerfile.tunnel
    entrypoint: ssh
    command: "-N elasticsearch -L 0.0.0.0:9200:localhost:9200"

docker/Dockerfile.tunnel:

FROM buildpack-deps:jessie

RUN apt-get update && \
    DEBIAN_FRONTEND=noninteractive \
    apt-get -y install ssh && \
    apt-get clean && \
    rm -rf /var/lib/apt/lists/*

COPY ./config/ssh/id_rsa /root/.ssh/id_rsa
COPY ./config/ssh/config /root/.ssh/config
COPY ./config/ssh/known_hosts /root/.ssh/known_hosts
RUN chmod 600 /root/.ssh/id_rsa && \
    chmod 600 /root/.ssh/config && \
    chown $USER:$USER -R /root/.ssh

config/ssh/config:

# Elasticsearch Server
Host elasticsearch
    HostName jump.host.czerasz.com
    User czerasz
    ForwardAgent yes
    IdentityFile ~/.ssh/id_rsa

This way the elasticsearch has a tunnel to the server with the running service (Elasticsearch, MongoDB, PostgreSQL) and exposes port 9200 with that service.

R object identification

str(x)

It's all you need to remember for 99% of cases.

How to trim a list in Python

To trim a list in place without creating copies of it, use del:

>>> t = [1, 2, 3, 4, 5]
>>> # delete elements starting from index 4 to the end
>>> del t[4:]
>>> t
[1, 2, 3, 4]
>>> # delete elements starting from index 5 to the end
>>> # but the list has only 4 elements -- no error
>>> del t[5:]
>>> t
[1, 2, 3, 4]
>>> 

How to list all AWS S3 objects in a bucket using Java

I am processing a large collection of objects generated by our system; we changed the format of the stored data and needed to check each file, determine which ones were in the old format, and convert them. There are other ways to do this, but this one relates to your question.

    ObjectListing list = amazonS3Client.listObjects(contentBucketName, contentKeyPrefix);

    do {                

        List<S3ObjectSummary> summaries = list.getObjectSummaries();

        for (S3ObjectSummary summary : summaries) {

            String summaryKey = summary.getKey();               

            /* Retrieve object */

            /* Process it */

        }

        list = amazonS3Client.listNextBatchOfObjects(list);

    }while (list.isTruncated());

java.io.StreamCorruptedException: invalid stream header: 7371007E

when I send only one object from the client to server all works well.

when I attempt to send several objects one after another on the same stream I get StreamCorruptedException.

Actually, your client code is writing one object to the server and reading multiple objects from the server. And there is nothing on the server side that is writing the objects that the client is trying to read.

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

How to return a value from try, catch, and finally?

It is because you are in a try statement. Since there could be an error, sum might not get initialized, so put your return statement in the finally block, that way it will for sure be returned.

Make sure that you initialize sum outside the try/catch/finally so that it is in scope.

Minimum and maximum date

As you can see, 01/01/1970 returns 0, which means it is the lowest possible date.

new Date('1970-01-01Z00:00:00:000') //returns Thu Jan 01 1970 01:00:00 GMT+0100 (Central European Standard Time)
new Date('1970-01-01Z00:00:00:000').getTime() //returns 0
new Date('1970-01-01Z00:00:00:001').getTime() //returns 1

Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug

Re-enabling the Application Experience service of Windows has fixed that kind of problems for me.

See the following links:

I had the problem using Visual Studio 2008, 2010 and 2013 with Windows 7 64-bit.

What is Bit Masking?

A mask defines which bits you want to keep, and which bits you want to clear.

Masking is the act of applying a mask to a value. This is accomplished by doing:

  • Bitwise ANDing in order to extract a subset of the bits in the value
  • Bitwise ORing in order to set a subset of the bits in the value
  • Bitwise XORing in order to toggle a subset of the bits in the value

Below is an example of extracting a subset of the bits in the value:

Mask:   00001111b
Value:  01010101b

Applying the mask to the value means that we want to clear the first (higher) 4 bits, and keep the last (lower) 4 bits. Thus we have extracted the lower 4 bits. The result is:

Mask:   00001111b
Value:  01010101b
Result: 00000101b

Masking is implemented using AND, so in C we get:

uint8_t stuff(...) {
  uint8_t mask = 0x0f;   // 00001111b
  uint8_t value = 0x55;  // 01010101b
  return mask & value;
}

Here is a fairly common use-case: Extracting individual bytes from a larger word. We define the high-order bits in the word as the first byte. We use two operators for this, &, and >> (shift right). This is how we can extract the four bytes from a 32-bit integer:

void more_stuff(uint32_t value) {             // Example value: 0x01020304
    uint32_t byte1 = (value >> 24);           // 0x01020304 >> 24 is 0x01 so
                                              // no masking is necessary
    uint32_t byte2 = (value >> 16) & 0xff;    // 0x01020304 >> 16 is 0x0102 so
                                              // we must mask to get 0x02
    uint32_t byte3 = (value >> 8)  & 0xff;    // 0x01020304 >> 8 is 0x010203 so
                                              // we must mask to get 0x03
    uint32_t byte4 = value & 0xff;            // here we only mask, no shifting
                                              // is necessary
    ...
}

Notice that you could switch the order of the operators above, you could first do the mask, then the shift. The results are the same, but now you would have to use a different mask:

uint32_t byte3 = (value & 0xff00) >> 8;

How to fix .pch file missing on build?

In case this is happening to you on a server build (AppCenter) and yo uaer using CocoaPods ensure that your Podfile is checked in.

AppCenter only runs the "pod install" command if it finds a Pofile and it DOES NOT find the PODS folder on the files.

I had the folder checked-in, but because git automatically ignores .pch files (check you .gitignore to veryfy this), my .pch weren'nt being checked in.

I sorted my issue by forcing the .pch files to check it, but Deleting the PODS folder should work too, since Appcenter will run the pod install command in that case.

Hoppefully this helps somebody.

Convert Dictionary to JSON in Swift

Swift 5:

let dic = ["2": "B", "1": "A", "3": "C"]
let encoder = JSONEncoder()
if let jsonData = try? encoder.encode(dic) {
    if let jsonString = String(data: jsonData, encoding: .utf8) {
        print(jsonString)
    }
}

Note that keys and values must implement Codable. Strings, Ints, and Doubles (and more) are already Codable. See Encoding and Decoding Custom Types.

How to Install Sublime Text 3 using Homebrew

An update

Turns out now brew cask install sublime-text installs the most up to date version (e.g. 3) by default and brew cask is now part of the standard brew-installation.

how to access downloads folder in android?

You should add next permission:

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

And then here is usages in code:

val externalFilesDir = context.getExternalFilesDir(DIRECTORY_DOWNLOADS)

How to remove element from array in forEach loop?

You could also use indexOf instead to do this

var i = review.indexOf('\u2022 \u2022 \u2022');
if (i !== -1) review.splice(i,1);

How to place a div below another div?

what about changing the position: relative on your #content #text div to position: absolute

#content #text {
   position:absolute;
   width:950px;
   height:215px;
   color:red;
}

http://jsfiddle.net/CaZY7/12/

then you can use the css properties left and top to position within the #content div

Creating .pem file for APNS?

I would suggest a much more simple solution. Just use Certifire.
Certifire is a macOS application that generates Apple Push Notification Certificates with just one click in a couple of seconds.

Here are the steps:
1. Download the app.
2. Log in using your Apple Developer Account credentials.
3. Choose the App-ID
4. Click "Generate" button
5. You're done!

You will get APN certificates in .pem format as well as in .p12 format. Even more, you will get also combined .pem and .p12 too (key+cert)!
Much more, you will get no-passphrase versions of all these certificates also!

enter image description here

enter image description here

Vuejs and Vue.set(), update array

EDIT 2

  • For all object changes that need reactivity use Vue.set(object, prop, value)
  • For array mutations, you can look at the currently supported list here

EDIT 1

For vuex you will want to do Vue.set(state.object, key, value)


Original

So just for others who come to this question. It appears at some point in Vue 2.* they removed this.items.$set(index, val) in favor of this.$set(this.items, index, val).

Splice is still available and here is a link to array mutation methods available in vue link.

Is there a vr (vertical rule) in html?

No there is not. And I will tell you a little story on why it is not. But first, quick solutions:

a) Use CSS class for basic elements span/div, e.g.: <span class="vr"></span>:

.vr{ 
   display: inline-block; 
   vertical-align: middle; 
   /* note that height must be precise, 100% does not work in some major browsers */
   height: 100px; 
   width: 1px; 
   background-color: #000;
}

Demonstration of use => https://jsfiddle.net/fe3tasa0/

b) Make a use of a one-side-only border and possibly CSS :first-child selector if you want to apply a general dividers among sibling/neigbour elements.

The story about <vr> FITTING in the original paradigm,
but still not being there:

Many answers here suggest, that vertical divider does not fit the original HTML paradigm/approach ... that is completely wrong. Also the answers contradict themselves a lot.

Those same people are probably calling their clear CSS class "clearfix" - there is nothing to fix about floating, you are just clearing it ... There was even an element in HTML3: <clear>. Sadly, this and clearance of floating is one of the few common misconceptions.

Anyway. "Back then" in the "original HTML ages", there was no thought about something like inline-block, there were just blocks, inlines and tables.

The last one is actually the reason why <vr> does not exist.
Back then it was assumed that:
If you want to verticaly divide something and/or make more blocks from left to right =>
=> you are making/want to make columns =>
=> that implies you are creating a table =>
=> tables have natural borders between their cells =>
no reason to make a <vr>

This approach is actually still valid, but as time showed, the syntax made for tables is not suitable for every case as well as it's default styles.


Another, probably later, assumption was that if you are not creating table, you are probably floating block elements. That meaning they are sticking together, and again, you can set a border, and those days probably even use the :first-child selector I suggested above...

How do we control web page caching, across all browsers?

The headers in the answer provided by BalusC does not prevent Safari 5 (and possibly older versions as well) from displaying content from the browser cache when using the browser's back button. A way to prevent this is to add an empty onunload event handler attribute to the body tag:

<body onunload=""> 

This hack apparently breaks the back-forward cache in Safari: Is there a cross-browser onload event when clicking the back button?

How to set a value for a span using jQuery

The solution that work for me is the following:

$("#spanId").text("text to show");

Bootstrap: Collapse other sections when one is expanded

If you don't want to change your markup, this function does the trick:

jQuery('button').click( function(e) {
    jQuery('.collapse').collapse('hide');
});

Whenever a BUTTON is clicked, all sections become collapsed. Then bootstrap opens the one you selected.

Eclipse doesn't stop at breakpoints

It has also happened to me, in my case it was due to the GDB launcher, which I needed to turn to "Legacy Create Process Launcher". To do so,

  • either change the default launchers to the "Legacy Create Process Launcher", in Windows>Preferences>Run/Debug>Launching>Default Launchers.

  • or choose this launcher in the debug configuration of your application (Run>Debug configurations>choose your debug configuration). Under the "main" tab at the bottom, click on "Select other...", check the box "Use configuration specific settings" and choose "Legacy Create Process Launcher".

Sorting dropdown alphabetically in AngularJS

For anyone who wants to sort the variable in third layer:

<select ng-option="friend.pet.name for friend in friends"></select>

you can do it like this

<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>

how can I Update top 100 records in sql server

Without an ORDER BY the whole idea of TOP doesn't make much sense. You need to have a consistent definition of which direction is "up" and which is "down" for the concept of top to be meaningful.

Nonetheless SQL Server allows it but doesn't guarantee a deterministic result.

The UPDATE TOP syntax in the accepted answer does not support an ORDER BY clause but it is possible to get deterministic semantics here by using a CTE or derived table to define the desired sort order as below.

;WITH CTE AS 
( 
SELECT TOP 100 * 
FROM T1 
ORDER BY F2 
) 
UPDATE CTE SET F1='foo'

Proper way to return JSON using node or Express

If you're using Express, you can use this:

res.setHeader('Content-Type', 'application/json');
res.send(JSON.stringify({key:"value"}));

or just this

res.json({key:"value"});

The maximum recursion 100 has been exhausted before statement completion

it is just a sample to avoid max recursion error. we have to use option (maxrecursion 365); or option (maxrecursion 0);

DECLARE @STARTDATE datetime; 
DECLARE @EntDt datetime; 
set @STARTDATE = '01/01/2009';  
set @EntDt = '12/31/2009'; 
declare @dcnt int; 
;with DateList as   
 (   
    select @STARTDATE DateValue   
    union all   
    select DateValue + 1 from    DateList      
    where   DateValue + 1 < convert(VARCHAR(15),@EntDt,101)   
 )   
  select count(*) as DayCnt from (   
  select DateValue,DATENAME(WEEKDAY, DateValue ) as WEEKDAY from DateList
  where DATENAME(WEEKDAY, DateValue ) not IN ( 'Saturday','Sunday' )     
  )a
option (maxrecursion 365);

Inserting an item in a Tuple

def tuple_insert(tup,pos,ele):
    tup = tup[:pos]+(ele,)+tup[pos:]
    return tup

tuple_insert(tup,pos,9999)

tup: tuple
pos: Position to insert
ele: Element to insert

How to run .jar file by double click on Windows 7 64-bit?

For Windows 7:

  1. Start "Control Panel"
  2. Click "Default Programs"
  3. Click "Associate a file type or protocol with a specific program"
  4. Double click .jar
  5. Browse C:\Program Files\Java\jre7\bin\javaw.exe
  6. Click the button Open
  7. Click the button OK

No tests found with test runner 'JUnit 4'

Check for updates! Eclipse is no doubt fully aware of this problem considering how many workarounds have been presented. There is obviously something systemic involved...something that defies explanation or any sense of consistency. It would have been useful if Eclipse would have let the community know what the problem was and how it was fixed.

Another recent find for me was to delete any source directories that had no files or the all files were excluded.

Why Would I Ever Need to Use C# Nested Classes

A nested class can have private, protected and protected internal access modifiers along with public and internal.

For example, you are implementing the GetEnumerator() method that returns an IEnumerator<T> object. The consumers wouldn't care about the actual type of the object. All they know about it is that it implements that interface. The class you want to return doesn't have any direct use. You can declare that class as a private nested class and return an instance of it (this is actually how the C# compiler implements iterators):

class MyUselessList : IEnumerable<int> {
    // ...
    private List<int> internalList;
    private class UselessListEnumerator : IEnumerator<int> {
        private MyUselessList obj;
        public UselessListEnumerator(MyUselessList o) {
           obj = o;
        }
        private int currentIndex = -1;
        public int Current {
           get { return obj.internalList[currentIndex]; }
        }
        public bool MoveNext() { 
           return ++currentIndex < obj.internalList.Count;
        }
    }
    public IEnumerator<int> GetEnumerator() {
        return new UselessListEnumerator(this);
    }
}

how to change php version in htaccess in server

An addition to the current marked answer:

Place the addhandler inside the following scope, like so:

<IfModule mod_rewrite.c>

   AddHandler application/x-httpd-php71 .php
   RewriteEngine On

   ....

</IfModule>

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

For all still having this problem and as for me none of the posted solutions worked out.

I've had the similar issue. The image was showing correctly in all other share dialogs. Only WhatsApp couldnt display the image, even though the facebook debugger has the og:image tag correctly.

The solution that worked for me: I am using firebase. For uploaded content in their storage, you get a unique Download URL with a media token. Something like:

https://firebasestorage.googleapis.com/v0/b/XXXX.XXXXXXX.com/?alt=media&token=YYYYYYYY-YYYYYYYYYY-YYYYYYYYYYYYY

I used this URL in the og:image meta tag. It worked for Facebook etc., but it seems like WhatsApp couldnt download the image from this URL. Instead you need to include the image in your project directory and use this link for the og:image tag. Now it works properly in WhatsApp too.

Before (not working in WhatsApp, but facebook etc.)

<meta property="og:image" itemprop="image" content="https://firebasestorage.googleapis.com/v0/b/XXXX.XXXXXXX.com/your_image?alt=media&token=YYYYYYYY-YYYYYYYYYY-YYYYYYYYYYYYY">

After (now working in all shared dialogs tested, including WhatsApp)

<meta property="og:image" itemprop="image" content="https://domain_name/path_to_image">

Hope it might help some of you :)

Limiting the number of characters per line with CSS

Another approach to this would put a span element with a display:block style inside the p element each time you need the content to break. It would only be useful when your p content is static.

<p>this is a not-dynamic text and I want to put<span style="display:block">the following words in the next line</span>and these other words in a third one</p>

It would output:

This is a not-dynamic text and I want to put

the following words in the next line

and these others in a third one

This allows you to change your text line-breaks in different viewports without JS.

Untrack files from git temporarily

The git-book mentions this in section 2.4: "Undoing Things". Basically, what you have to do is reset the state of the index for some files back to the HEAD state, that is to the state of the latest checkout (or commit). This undoes staging the file to the current index. The command for this task is git reset.[1]

So, the command you have to execute is:

git reset HEAD /path/to/file

The newer versions of git (I believe since 1.6 or so) gives this command (and many more) as a tip when executing git status. These versions are very user-friendly. A personal tip: if you are only staging a few files, use git add -i. This will launch the interactive staging tool, which makes thing particularly easy. Also, I highly recommend reading the book, as it is very explicit on the use of git in practical situations.

[1] http://www.git-scm.com/book

JavaScript for...in vs for

There is an important difference between both. The for-in iterates over the properties of an object, so when the case is an array it will not only iterate over its elements but also over the "remove" function it has.

for (var i = 0; i < myArray.length; i++) { 
    console.log(i) 
}

//Output
0
1

for (var i in myArray) { 
    console.log(i) 
} 

// Output
0 
1 
remove

You could use the for-in with an if(myArray.hasOwnProperty(i)). Still, when iterating over arrays I always prefer to avoid this and just use the for(;;) statement.

Location of the mongodb database on mac

I had the same problem, with version 3.4.2

to run it (if you installed it with homebrew) run the process like this:

$ mongod --dbpath /usr/local/var/mongodb

Clear icon inside input text

Add a type="search" to your input
The support is pretty decent but will not work in IE<10

_x000D_
_x000D_
<input type="search">
_x000D_
_x000D_
_x000D_


Older browsers

If you need IE9 support here are some workarounds

Using a standard <input type="text"> and some HTML elements:

_x000D_
_x000D_
/**
 * Clearable text inputs
 */
$(".clearable").each(function() {
  
  const $inp = $(this).find("input:text"),
      $cle = $(this).find(".clearable__clear");

  $inp.on("input", function(){
    $cle.toggle(!!this.value);
  });
  
  $cle.on("touchstart click", function(e) {
    e.preventDefault();
    $inp.val("").trigger("input");
  });
  
});
_x000D_
/* Clearable text inputs */
.clearable{
  position: relative;
  display: inline-block;
}
.clearable input[type=text]{
  padding-right: 24px;
  width: 100%;
  box-sizing: border-box;
}
.clearable__clear{
  display: none;
  position: absolute;
  right:0; top:0;
  padding: 0 8px;
  font-style: normal;
  font-size: 1.2em;
  user-select: none;
  cursor: pointer;
}
.clearable input::-ms-clear {  /* Remove IE default X */
  display: none;
}
_x000D_
<span class="clearable">
  <input type="text" name="" value="" placeholder="">
  <i class="clearable__clear">&times;</i>
</span>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Using only a <input class="clearable" type="text"> (No additional elements)

Clear icon inside input element

set a class="clearable" and play with it's background image:

_x000D_
_x000D_
/**
 * Clearable text inputs
 */
function tog(v){return v ? "addClass" : "removeClass";} 
$(document).on("input", ".clearable", function(){
    $(this)[tog(this.value)]("x");
}).on("mousemove", ".x", function( e ){
    $(this)[tog(this.offsetWidth-18 < e.clientX-this.getBoundingClientRect().left)]("onX");
}).on("touchstart click", ".onX", function( ev ){
    ev.preventDefault();
    $(this).removeClass("x onX").val("").change();
});

// $('.clearable').trigger("input");
// Uncomment the line above if you pre-fill values from LS or server
_x000D_
/*
    Clearable text inputs
*/
.clearable{
  background: #fff url(http://i.stack.imgur.com/mJotv.gif) no-repeat right -10px center;
  border: 1px solid #999;
  padding: 3px 18px 3px 4px; /* Use the same right padding (18) in jQ! */
  border-radius: 3px;
  transition: background 0.4s;
}
.clearable.x  { background-position: right 5px center; } /* (jQ) Show icon */
.clearable.onX{ cursor: pointer; } /* (jQ) hover cursor style */
.clearable::-ms-clear {display: none; width:0; height:0;} /* Remove IE default X */
_x000D_
<input class="clearable" type="text" name="" value="" placeholder="" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

The trick is to set some right padding (I used 18px) to the input and push the background-image right, out of sight (I used right -10px center).
That 18px padding will prevent the text hide underneath the icon (while visible).
jQuery will add the class "x" (if input has value) showing the clear icon.
Now all we need is to target with jQ the inputs with class x and detect on mousemove if the mouse is inside that 18px "x" area; if inside, add the class onX.
Clicking the onX class removes all classes, resets the input value and hides the icon.


7x7px gif: Clear icon 7x7

Base64 string:

data:image/gif;base64,R0lGODlhBwAHAIAAAP///5KSkiH5BAAAAAAALAAAAAAHAAcAAAIMTICmsGrIXnLxuDMLADs=

How can I count the occurrences of a string within a file?

None of the existing answers worked for me with a single-line 10GB file. Grep runs out of memory even on a machine with 768 GB of RAM!

$ cat /proc/meminfo | grep MemTotal
MemTotal:       791236260 kB
$ ls -lh test.json
-rw-r--r-- 1 me all 9.2G Nov 18 15:54 test.json
$ grep -o '0,0,0,0,0,0,0,0,' test.json  | wc -l
grep: memory exhausted
0

So I wrote a very simple Rust program to do it.

  1. Install Rust.
  2. cargo install count_occurences
$ count_occurences '0,0,0,0,0,0,0,0,' test.json
99094198

It's a little slow (1 minute for 10GB), but at least it doesn't run out of memory!

Please explain the exec() function and its family

exec is often used in conjunction with fork, which I saw that you also asked about, so I will discuss this with that in mind.

exec turns the current process into another program. If you ever watched Doctor Who, then this is like when he regenerates -- his old body is replaced with a new body.

The way that this happens with your program and exec is that a lot of the resources that the OS kernel checks to see if the file you are passing to exec as the program argument (first argument) is executable by the current user (user id of the process making the exec call) and if so it replaces the virtual memory mapping of the current process with a virtual memory the new process and copies the argv and envp data that were passed in the exec call into an area of this new virtual memory map. Several other things may also happen here, but the files that were open for the program that called exec will still be open for the new program and they will share the same process ID, but the program that called exec will cease (unless exec failed).

The reason that this is done this way is that by separating running a new program into two steps like this you can do some things between the two steps. The most common thing to do is to make sure that the new program has certain files opened as certain file descriptors. (remember here that file descriptors are not the same as FILE *, but are int values that the kernel knows about). Doing this you can:

int X = open("./output_file.txt", O_WRONLY);

pid_t fk = fork();
if (!fk) { /* in child */
    dup2(X, 1); /* fd 1 is standard output,
                   so this makes standard out refer to the same file as X  */
    close(X);

    /* I'm using execl here rather than exec because
       it's easier to type the arguments. */
    execl("/bin/echo", "/bin/echo", "hello world");
    _exit(127); /* should not get here */
} else if (fk == -1) {
    /* An error happened and you should do something about it. */
    perror("fork"); /* print an error message */
}
close(X); /* The parent doesn't need this anymore */

This accomplishes running:

/bin/echo "hello world" > ./output_file.txt

from the command shell.