Programs & Examples On #Jrockit

JRockit is a High performance JVM built into Oracle Fusion Middleware.

"java.lang.OutOfMemoryError : unable to create new native Thread"

your JBoss configuration has some issues, /opt/jrockit-jdk1.6/bin/java -Xms512m -Xmx512m Xms and Xmx are limiting your JBoss memory usage, to the configured value, so from the 8Gb you have the server is only ussing 512M + some extra for his own purpose, increase that number, remember to leave some free for the OS and other stuff running there and may be you get it running despite de unsavoury code. Fixing the code would be nice too, if you can.

Importing a csv into mysql via command line

I know this says command line, but just a tidbit of something quick to try that might work, if you've got MySQL workbench and the csv isn't too large, you can simply

  • SELECT * FROM table
  • Copy entire CSV
  • Paste csv into the query results section of Workbench
  • Hope for the best

I say hope for the best because this is MySQL Workbench. You never know when it's going to explode


If you want to do this on a remote server, you would do

mysql -h<server|ip> -u<username> -p --local-infile bark -e "LOAD DATA LOCAL INFILE '<filename.csv>'  INTO TABLE <table>  FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'"

Note, I didn't put a password after -p as putting one on the command line is considered bad practice

Sharepoint: How do I filter a document library view to show the contents of a subfolder?

With Sharepoint Designer you can edit the CAML of your XSLT List View.

If you set the Scope attribute of the View element to Recursive or RecursiveAll, which returns all Files and Folders, you can filter the documents by FileDirRef:

<Where>
   <Contains>
      <FieldRef Name='FileDirRef' />
      <Value Type='Lookup'>MyFolder</Value>
   </Contains>
</Where>

This returns all documents which contain the string 'MyFolder' in their path.

I found infos about this on http://platinumdogs.wordpress.com/2009/07/21/querying-document-libraries-or-pulling-teeth-with-caml/ and useful information abouts fields at http://blog.thekid.me.uk/archive/2007/03/21/wss-field-display-amp-internal-names-for-lists-amp-document-libraries.aspx

Node.js check if file exists

Edit: Since node v10.0.0we could use fs.promises.access(...)

Example async code that checks if file exists:

async function checkFileExists(file) {
  return fs.promises.access(file, fs.constants.F_OK)
           .then(() => true)
           .catch(() => false)
}

An alternative for stat might be using the new fs.access(...):

minified short promise function for checking:

s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))

Sample usage:

let checkFileExists = s => new Promise(r=>fs.access(s, fs.constants.F_OK, e => r(!e)))
checkFileExists("Some File Location")
  .then(bool => console.log(´file exists: ${bool}´))

expanded Promise way:

// returns a promise which resolves true if file exists:
function checkFileExists(filepath){
  return new Promise((resolve, reject) => {
    fs.access(filepath, fs.constants.F_OK, error => {
      resolve(!error);
    });
  });
}

or if you wanna do it synchronously:

function checkFileExistsSync(filepath){
  let flag = true;
  try{
    fs.accessSync(filepath, fs.constants.F_OK);
  }catch(e){
    flag = false;
  }
  return flag;
}

Error: request entity too large

If you are using express.json() and bodyParser together it will give error as express sets its own limit.

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

remove above code and just add below code

app.use(bodyParser.json({ limit: "200mb" }));
app.use(bodyParser.urlencoded({ limit: "200mb",  extended: true, parameterLimit: 1000000 }));

Append TimeStamp to a File Name

For Current date and time as the name for a file on the file system. Now call the string.Format method, and combine it with DateTime.Now, for a method that outputs the correct string based on the date and time.

using System;
using System.IO;

class Program
{
    static void Main()
    {
        //
        // Write file containing the date with BIN extension
        //
        string n = string.Format("text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin",
            DateTime.Now);
        File.WriteAllText(n, "abc");
    }
}

Output :

C:\Users\Fez\Documents\text-2020-01-08_05-23-13-PM.bin

"text-{0:yyyy-MM-dd_hh-mm-ss-tt}.bin"

text- The first part of the output required Files will all start with text-

{0: Indicates that this is a string placeholder The zero indicates the index of the parameters inserted here

yyyy- Prints the year in four digits followed by a dash This has a "year 10000" problem

MM- Prints the month in two digits

dd_ Prints the day in two digits followed by an underscore

hh- Prints the hour in two digits

mm- Prints the minute, also in two digits

ss- As expected, it prints the seconds

tt Prints AM or PM depending on the time of day

how to rotate a bitmap 90 degrees

Short extension for Kotlin

fun Bitmap.rotate(degrees: Float): Bitmap {
    val matrix = Matrix().apply { postRotate(degrees) }
    return Bitmap.createBitmap(this, 0, 0, width, height, matrix, true)
}

And usage:

val rotatedBitmap = bitmap.rotate(90f)

Calculate the number of business days between two dates?

Works and without loops

This method doesn't use any loops and is actually quite simple. It expands the date range to full weeks since we know that each week has 5 business days. It then uses a lookup table to find the number of business days to subtract from the start and end to get the right result. I've expanded out the calculation to help show what's going on, but the whole thing could be condensed into a single line if needed.

Anyway, this works for me and so I thought I'd post it here in case it might help others. Happy coding.

Calculation

  • t : Total number of days between dates (1 if min = max)
  • a + b : Extra days needed to expand total to full weeks
  • k : 1.4 is number of weekdays per week, i.e., (t / 7) * 5
  • c : Number of weekdays to subtract from the total
  • m : A lookup table used to find the value of "c" for each day of the week

Culture

Code assumes a Monday to Friday work week. For other cultures, such as Sunday to Thursday, you'll need to offset the dates prior to calculation.

Method

public int Weekdays(DateTime min, DateTime max) 
{       
        if (min.Date > max.Date) throw new Exception("Invalid date span");
        var t = (max.AddDays(1).Date - min.Date).TotalDays;
        var a = (int) min.DayOfWeek;
        var b = 6 - (int) max.DayOfWeek;
        var k = 1.4;
        var m = new int[]{0, 0, 1, 2, 3, 4, 5}; 
        var c = m[a] + m[b];
        return (int)((t + a + b) / k) - c;
}

How exactly do you configure httpOnlyCookies in ASP.NET?

With props to Rick (second comment down in the blog post mentioned), here's the MSDN article on httpOnlyCookies.

Bottom line is that you just add the following section in your system.web section in your web.config:

<httpCookies domain="" httpOnlyCookies="true|false" requireSSL="true|false" />

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

Eclipse gives “Java was started but returned exit code 13”

Check you PATH environment variable once. Make sure the correct location of your JDK is specified there.

How to copy JavaScript object to new variable NOT by reference?

I've found that the following works if you're not using jQuery and only interested in cloning simple objects (see comments).

JSON.parse(JSON.stringify(json_original));

Documentation

Can't install APK from browser downloads

I had this problem. Couldn't install apk via the Downloads app. However opening the apk in a file manager app allowed me to install it fine. Using OI File Manager on stock Nexus 7 4.2.1

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

With out typescript error

    const formData = new FormData();
    Object.keys(newCategory).map((k,i)=>{  
        var d =Object.values(newCategory)[i];
        formData.append(k,d) 
    })

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

Here are three different checkmark styles you can use:

_x000D_
_x000D_
ul:first-child  li:before { content:"\2713\0020"; }  /* OR */_x000D_
ul:nth-child(2) li:before { content:"\2714\0020"; }  /* OR */_x000D_
ul:last-child   li:before { content:"\2611\0020"; }_x000D_
ul { list-style-type: none; }
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>_x000D_
_x000D_
<ul><!-- not working on Stack snippet; check fiddle demo -->_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

jsFiddle

References:

Can curl make a connection to any TCP ports, not just HTTP/HTTPS?

Since you're using PHP, you will probably need to use the CURLOPT_PORT option, like so:

curl_setopt($ch, CURLOPT_PORT, 11740);

Bear in mind, you may face problems with SELinux:

Unable to make php curl request with port number

What is the use of a private static variable in Java?

For some people this makes more sense if they see it in a couple different languages so I wrote an example in Java, and PHP on my page where I explain some of these modifiers. You might be thinking about this incorrectly.

You should look at my examples if it doesn't make sense below. Go here http://www.siteconsortium.com/h/D0000D.php

The bottom line though is that it is pretty much exactly what it says it is. It's a static member variable that is private. For example if you wanted to create a Singleton object why would you want to make the SingletonExample.instance variable public. If you did a person who was using the class could easily overwrite the value.

That's all it is.


    public class SingletonExample {
      private static SingletonExample instance = null;
      private static int value = 0;
      private SingletonExample() {
        ++this.value;
      }
      public static SingletonExample getInstance() {
        if(instance!=null)
        return instance;
        synchronized(SingletonExample.class) {
        instance = new SingletonExample();
        return instance;
        }
      }
      public void printValue() {
        System.out.print( this.value );
      }

      public static void main(String [] args) {
        SingletonExample instance = getInstance();
        instance.printValue();
        instance = getInstance();
        instance.printValue();
         }
    }

getaddrinfo: nodename nor servname provided, or not known

The error occurs when the DNS resolution fails. Check if you can wget (or curl) the api url from the command line. Changing the DNS server and testing it might help.

How does the "position: sticky;" property work?

from my comment:

position:sticky needs a coordonate to tel where to stick

_x000D_
_x000D_
nav {_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
.nav-selections {_x000D_
  text-transform: uppercase;_x000D_
  letter-spacing: 5px;_x000D_
  font: 18px "lato", sans-serif;_x000D_
  display: inline-block;_x000D_
  text-decoration: none;_x000D_
  color: white;_x000D_
  padding: 18px;_x000D_
  float: right;_x000D_
  margin-left: 50px;_x000D_
  transition: 1.5s;_x000D_
}_x000D_
_x000D_
.nav-selections:hover {_x000D_
  transition: 1.5s;_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  background-color: #B79b58;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
li {_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
body {_x000D_
  height: 200vh;_x000D_
}
_x000D_
<nav>_x000D_
  <ul align="left">_x000D_
    <li><a href="#/contact" class="nav-selections" style="margin-right:35px;">Contact</a></li>_x000D_
    <li><a href="#/about" class="nav-selections">About</a></li>_x000D_
    <li><a href="#/products" class="nav-selections">Products</a></li>_x000D_
    <li><a href="#" class="nav-selections">Home</a></li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

There is polyfill to use for other browsers than FF and Chrome . This is an experimental rules that can be implemented or not at any time through browsers. Chrome add it a couple of years ago and then dropped it, it seems back ... but for how long ?

The closest would be position:relative + coordonates updated while scrolling once reached the sticky point, if you want to turn this into a javascript script

Find multiple files and rename them in Linux

If you just want to rename and don't mind using an external tool, then you can use rnm. The command would be:

#on current folder
rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' *

-dp -1 will make it recursive to all subdirectories.

-fo implies file only mode.

-ssf '_dbg' searches for files with _dbg in the filename.

-rs '/_dbg//' replaces _dbg with empty string.

You can run the above command with the path of the CURRENT_FOLDER too:

rnm -dp -1 -fo -ssf '_dbg' -rs '/_dbg//' /path/to/the/directory

How to limit text width

Try this:

<style> 
p
{
    width:100px; 
    word-wrap:break-word;
}
</style>

<p>Loremipsumdolorsitamet,consecteturadipiscingelit.Fusce non nisl
non ante malesuada mollis quis ut ipsum. Cum sociis natoque penatibus et magnis dis 
parturient montes, nascetur ridiculus mus. Cras ut adipiscing dolor. Nunc congue, 
tellus vehicula mattis porttitor, justo nisi sollicitudin nulla, a rhoncus lectus lacus 
id turpis. Vivamus diam lacus, egestas nec bibendum eu, mattis eget risus</p>

Replace HTML page with contents retrieved via AJAX

You could try doing

document.getElementById(id).innerHTML = ajax_response

What is the proper way to format a multi-line dict in Python?

Since your keys are strings and since we are talking about readability, I prefer :

mydict = dict(
    key1 = 1,
    key2 = 2,
    key3 = 3
)

Setting onClickListener for the Drawable right of an EditText

You don't have access to the right image as far my knowledge, unless you override the onTouch event. I suggest to use a RelativeLayout, with one editText and one imageView, and set OnClickListener over the image view as below:

<RelativeLayout
        android:id="@+id/rlSearch"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:drawable/edit_text"
        android:padding="5dip" >

        <EditText
            android:id="@+id/txtSearch"
            android:layout_width="match_parent"

            android:layout_height="wrap_content"
            android:layout_centerVertical="true"
            android:layout_toLeftOf="@+id/imgSearch"
            android:background="#00000000"
            android:ems="10"/>

        <ImageView
            android:id="@+id/imgSearch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_centerVertical="true"
            android:src="@drawable/btnsearch" />
    </RelativeLayout>

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

I Found the best way to increase Font Size in Eclipse:

Follow this path : Eclipse-Folder\plugins\org.eclipse.ui.themes_1.2.100.v20180514-1547\css

--There are a bunch of Files here and it depends on user system which file to change.

* {
  font-size:13;
  font-family: Helvetica, Arial, sans-serif;
  font-weight: normal;
} 

you can even change Font Family if you like.

  1. For Windows Users add the following piece of css at BOTTOM of these files: File Names: e4_default_gtk.css & e4_default_win.css

  2. For Mac Users: e4_default_mac.css

Convert Enum to String

I don't know what the "preferred" method is (ask 100 people and get 100 different opinions) but do what's simplest and what works. GetName works but requires a lot more keystrokes. ToString() seems to do the job very well.

SQL Server AS statement aliased column within WHERE statement

This would work on your edited question !

SELECT * FROM (SELECT <Column_List>,  
( 6371*1000 * acos( cos( radians(42.3936868308) ) * cos( radians( lat ) ) * cos( radians( lon ) - radians(-72.5277256966) ) + sin( radians(42.3936868308) ) * sin( radians( lat ) ) ) )  
AS distance 
FROM poi_table) TMP
WHERE distance < 500; 

Reverse / invert a dictionary mapping

Not something completely different, just a bit rewritten recipe from Cookbook. It's futhermore optimized by retaining setdefault method, instead of each time getting it through the instance:

def inverse(mapping):
    '''
    A function to inverse mapping, collecting keys with simillar values
    in list. Careful to retain original type and to be fast.
    >> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
    >> inverse(d)
    {1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
    '''
    res = {}
    setdef = res.setdefault
    for key, value in mapping.items():
        setdef(value, []).append(key)
    return res if mapping.__class__==dict else mapping.__class__(res)

Designed to be run under CPython 3.x, for 2.x replace mapping.items() with mapping.iteritems()

On my machine runs a bit faster, than other examples here

A weighted version of random.choice

Since Python 3.6 there is a method choices from the random module.

Python 3.6.1 (v3.6.1:69c0db5050, Mar 21 2017, 01:21:04)
Type 'copyright', 'credits' or 'license' for more information
IPython 6.0.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import random

In [2]: random.choices(
...:     population=[['a','b'], ['b','a'], ['c','b']],
...:     weights=[0.2, 0.2, 0.6],
...:     k=10
...: )

Out[2]:
[['c', 'b'],
 ['c', 'b'],
 ['b', 'a'],
 ['c', 'b'],
 ['c', 'b'],
 ['b', 'a'],
 ['c', 'b'],
 ['b', 'a'],
 ['c', 'b'],
 ['c', 'b']]

Note that random.choices will sample with replacement, per the docs:

Return a k sized list of elements chosen from the population with replacement.

Note for completeness of answer:

When a sampling unit is drawn from a finite population and is returned to that population, after its characteristic(s) have been recorded, before the next unit is drawn, the sampling is said to be "with replacement". It basically means each element may be chosen more than once.

If you need to sample without replacement, then as @ronan-paixão's brilliant answer states, you can use numpy.choice, whose replace argument controls such behaviour.

Compare two dates with JavaScript

Comparing dates in JavaScript is quite easy... JavaScript has built-in comparison system for dates which makes it so easy to do the comparison...

Just follow these steps for comparing 2 dates value, for example you have 2 inputs which each has a Date value in String and you to compare them...

1. you have 2 string values you get from an input and you'd like to compare them, they are as below:

var date1 = '01/12/2018';
var date2 = '12/12/2018';

2. They need to be Date Object to be compared as date values, so simply convert them to date, using new Date(), I just re-assign them for simplicity of explanation, but you can do it anyway you like:

date1 = new Date(date1);
date2 = new Date(date2);

3. Now simply compare them, using the > < >= <=

date1 > date2;  //false
date1 < date2;  //true
date1 >= date2; //false
date1 <= date2; //true

compare dates in javascript

Using Intent in an Android application to show another activity

Add this line to your AndroidManifest.xml:

<activity android:name=".OrderScreen" /> 

How to change the name of an iOS app?

A note on the bundle display name -- this is the right way to change the name in your app menu, but you'll likely have to reset content and settings in your iOS simulator before you see the change actually take effect.

Explicit Return Type of Lambda

The return type of a lambda (in C++11) can be deduced, but only when there is exactly one statement, and that statement is a return statement that returns an expression (an initializer list is not an expression, for example). If you have a multi-statement lambda, then the return type is assumed to be void.

Therefore, you should do this:

  remove_if(rawLines.begin(), rawLines.end(), [&expression, &start, &end, &what, &flags](const string& line) -> bool
  {
    start = line.begin();
    end = line.end();
    bool temp = boost::regex_search(start, end, what, expression, flags);
    return temp;
  })

But really, your second expression is a lot more readable.

Fill Combobox from database

            SqlConnection conn = new SqlConnection(@"Data Source=TOM-PC\sqlexpress;Initial Catalog=Northwind;User ID=sa;Password=xyz") ;
            conn.Open();
            SqlCommand sc = new SqlCommand("select customerid,contactname from customers", conn);
            SqlDataReader reader;

            reader = sc.ExecuteReader();
            DataTable dt = new DataTable();
            dt.Columns.Add("customerid", typeof(string));
            dt.Columns.Add("contactname", typeof(string));
            dt.Load(reader);

            comboBox1.ValueMember = "customerid";
            comboBox1.DisplayMember = "contactname";
            comboBox1.DataSource = dt;

            conn.Close();

Loading .sql files from within PHP

This The Best Code For restore sql by php can use 100% Goooood! Thank A lot

$file_content = file('myfile.sql');
$query = "";
foreach($file_content as $sql_line){
if(trim($sql_line) != "" && strpos($sql_line, "--") === false){
 $query .= $sql_line;
 if (substr(rtrim($query), -1) == ';'){
   echo $query;
   $result = mysql_query($query)or die(mysql_error());
   $query = "";
  }
 }
}

scikit-learn random state in splitting dataset

The random_state is an integer value which implies the selection of a random combination of train and test. When you set the test_size as 1/4 the there is a set generated of permutation and combination of train and test and each combination has one state. Suppose you have a dataset---> [1,2,3,4]

Train   |  Test   | State
[1,2,3]    [4]      **0**
[1,3,4]    [2]      **1**
[4,2,3]    [1]      **2**
[2,4,1]    [3]      **3**

We need it because while param tuning of model same state will considered again and again. So that there won't be any inference with the accuracy.

But in case of Random forest there is also similar story but in a different way w.r.t the variables.

Vibrate and Sound defaults on notification

// set notification audio

builder.setDefaults(Notification.DEFAULT_VIBRATE);
//OR 
builder.setDefaults(Notification.DEFAULT_SOUND);

What is the shortcut in IntelliJ IDEA to find method / functions?

Windows : ctrl + F12

MacOS : cmd + F12

Above commands will show the functions/methods in the current class.

Press SHIFT TWO times if you want to search both class and method in the whole project.

JavaScript click event listener on class

* This was edited to allow for children of the target class to trigger the events. See bottom of the answer for details. *

An alternative answer to add an event listener to a class where items are frequently being added and removed. This is inspired by jQuery's on function where you can pass in a selector for a child element that the event is listening on.

var base = document.querySelector('#base'); // the container for the variable content
var selector = '.card'; // any css selector for children

base.addEventListener('click', function(event) {
  // find the closest parent of the event target that
  // matches the selector
  var closest = event.target.closest(selector);
  if (closest && base.contains(closest)) {
    // handle class event
  }
});

Fiddle: https://jsfiddle.net/u6oje7af/94/

This will listen for clicks on children of the base element and if the target of a click has a parent matching the selector, the class event will be handled. You can add and remove elements as you like without having to add more click listeners to the individual elements. This will catch them all even for elements added after this listener was added, just like the jQuery functionality (which I imagine is somewhat similar under the hood).

This depends on the events propagating, so if you stopPropagation on the event somewhere else, this may not work. Also, the closest function has some compatibility issues with IE apparently (what doesn't?).

This could be made into a function if you need to do this type of action listening repeatedly, like

function addChildEventListener(base, eventName, selector, handler) {
  base.addEventListener(eventName, function(event) {
    var closest = event.target.closest(selector);
    if (closest && base.contains(closest)) {
      // passes the event to the handler and sets `this`
      // in the handler as the closest parent matching the
      // selector from the target element of the event
      handler.call(closest, event);
    }
  });
}

=========================================
EDIT: This post originally used the matches function for DOM elements on the event target, but this restricted the targets of events to the direct class only. It has been updated to use the closest function instead, allowing for events on children of the desired class to trigger the events as well. The original matches code can be found at the original fiddle: https://jsfiddle.net/u6oje7af/23/

How to make a stable two column layout in HTML/CSS

Here you go:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
  <title>Cols</title>_x000D_
  <style>_x000D_
    #left {_x000D_
      width: 200px;_x000D_
      float: left;_x000D_
    }_x000D_
    #right {_x000D_
      margin-left: 200px;_x000D_
      /* Change this to whatever the width of your left column is*/_x000D_
    }_x000D_
    .clear {_x000D_
      clear: both;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="container">_x000D_
    <div id="left">_x000D_
      Hello_x000D_
    </div>_x000D_
    <div id="right">_x000D_
      <div style="background-color: red; height: 10px;">Hello</div>_x000D_
    </div>_x000D_
    <div class="clear"></div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

See it in action here: http://jsfiddle.net/FVLMX/

How to Display Multiple Google Maps per page with API V3

Here is how I have been able to generate multiple maps on the same page using Google Map API V3. Kindly note that this is an off the cuff code that addresses the issue above.

The HTML bit

<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;"></div>
<div id="map_canvas2" style="width:700px; height:500px; margin-left:80px;"></div>

Javascript for map initialization

<script type="text/javascript">
var map, map2;

function initialize(condition) {
    // create the maps
    var myOptions = {
        zoom: 14,
        center: new google.maps.LatLng(0.0, 0.0),
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
}
</script> 

NULL values inside NOT IN clause

It may be concluded from answers here that NOT IN (subquery) doesn't handle nulls correctly and should be avoided in favour of NOT EXISTS. However, such a conclusion may be premature. In the following scenario, credited to Chris Date (Database Programming and Design, Vol 2 No 9, September 1989), it is NOT IN that handles nulls correctly and returns the correct result, rather than NOT EXISTS.

Consider a table sp to represent suppliers (sno) who are known to supply parts (pno) in quantity (qty). The table currently holds the following values:

      VALUES ('S1', 'P1', NULL), 
             ('S2', 'P1', 200),
             ('S3', 'P1', 1000)

Note that quantity is nullable i.e. to be able to record the fact a supplier is known to supply parts even if it is not known in what quantity.

The task is to find the suppliers who are known supply part number 'P1' but not in quantities of 1000.

The following uses NOT IN to correctly identify supplier 'S2' only:

WITH sp AS 
     ( SELECT * 
         FROM ( VALUES ( 'S1', 'P1', NULL ), 
                       ( 'S2', 'P1', 200 ),
                       ( 'S3', 'P1', 1000 ) )
              AS T ( sno, pno, qty )
     )
SELECT DISTINCT spx.sno
  FROM sp spx
 WHERE spx.pno = 'P1'
       AND 1000 NOT IN (
                        SELECT spy.qty
                          FROM sp spy
                         WHERE spy.sno = spx.sno
                               AND spy.pno = 'P1'
                       );

However, the below query uses the same general structure but with NOT EXISTS but incorrectly includes supplier 'S1' in the result (i.e. for which the quantity is null):

WITH sp AS 
     ( SELECT * 
         FROM ( VALUES ( 'S1', 'P1', NULL ), 
                       ( 'S2', 'P1', 200 ),
                       ( 'S3', 'P1', 1000 ) )
              AS T ( sno, pno, qty )
     )
SELECT DISTINCT spx.sno
  FROM sp spx
 WHERE spx.pno = 'P1'
       AND NOT EXISTS (
                       SELECT *
                         FROM sp spy
                        WHERE spy.sno = spx.sno
                              AND spy.pno = 'P1'
                              AND spy.qty = 1000
                      );

So NOT EXISTS is not the silver bullet it may have appeared!

Of course, source of the problem is the presence of nulls, therefore the 'real' solution is to eliminate those nulls.

This can be achieved (among other possible designs) using two tables:

  • sp suppliers known to supply parts
  • spq suppliers known to supply parts in known quantities

noting there should probably be a foreign key constraint where spq references sp.

The result can then be obtained using the 'minus' relational operator (being the EXCEPT keyword in Standard SQL) e.g.

WITH sp AS 
     ( SELECT * 
         FROM ( VALUES ( 'S1', 'P1' ), 
                       ( 'S2', 'P1' ),
                       ( 'S3', 'P1' ) )
              AS T ( sno, pno )
     ),
     spq AS 
     ( SELECT * 
         FROM ( VALUES ( 'S2', 'P1', 200 ),
                       ( 'S3', 'P1', 1000 ) )
              AS T ( sno, pno, qty )
     )
SELECT sno
  FROM spq
 WHERE pno = 'P1'
EXCEPT 
SELECT sno
  FROM spq
 WHERE pno = 'P1'
       AND qty = 1000;

jQuery Cross Domain Ajax

The response from server is JSON String format. If the set dataType as 'json' jquery will attempt to use it directly. You need to set dataType as 'text' and then parse it manually.

$.ajax({
    type: 'GET',
    dataType: "text", // You need to use dataType text else it will try to parse it.
    url: "http://someotherdomain.com/service.svc",
    success: function (responseData, textStatus, jqXHR) {
        console.log("in");
        var data = JSON.parse(responseData['AuthenticateUserResult']);
        console.log(data);
    },
    error: function (responseData, textStatus, errorThrown) {
        alert('POST failed.');
    }
});

How to run a hello.js file in Node.js on windows?

The problem was that you opened the Node.js repl while everyone automatically assumed you were in the command prompt. For what it's worth you can run a javascript file from the repl with the .load command. For example:

.load c:/users/username/documents/script.js

The same command can also be used in the command prompt if you first start node inside the command prompt by entering node with no arguments (assuming node is in PATH).

I find it fascinating that 1)everyone assumed you were in the command prompt rather than repl, 2)no one seems to know about .load, and 3)this has 273 upvotes, proving that a lot of other node.js beginners are similarly confused.

Perl: Use s/ (replace) and return new string

If you have Perl 5.14 or greater, you can use the /r option with the substitution operator to perform non-destructive substitution:

print "bla: ", $myvar =~ s/a/b/r, "\n";

In earlier versions you can achieve the same using a do() block with a temporary lexical variable, e.g.:

print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";

How to Right-align flex item?

If you need one item to be left aligned (like a header) but then multiple items right aligned (like 3 images), then you would do something like this:

h1 {
   flex-basis: 100%; // forces this element to take up any remaining space
}

img {
   margin: 0 5px; // small margin between images
   height: 50px; // image width will be in relation to height, in case images are large - optional if images are already the proper size
}

Here's what that will look like (only relavent CSS was included in snippet above)

enter image description here

File Not Found when running PHP with Nginx

in case it helps someone, my issue seems to be just because I was using a subfolder under my home directory, even though permissions seem correct and I don't have SELinux or anything like that. changing it to be under /var/www/something/something made it work.

(if I ever found the real cause, and remember this answer, I'll update it)

What are the differences between numpy arrays and matrices? Which one should I use?

As per the official documents, it's not anymore advisable to use matrix class since it will be removed in the future.

https://numpy.org/doc/stable/reference/generated/numpy.matrix.html

As other answers already state that you can achieve all the operations with NumPy arrays.

How can I get a value from a map?

map.at("key") throws exception if missing key

If k does not match the key of any element in the container, the function throws an out_of_range exception.

http://www.cplusplus.com/reference/map/map/at/

How do I create an Excel chart that pulls data from multiple sheets?

2007 is more powerful with ribbon..:=) To add new series in chart do: Select Chart, then click Design in Chart Tools on the ribbon, On the Design ribbon, select "Select Data" in Data Group, Then you will see the button for Add to add new series.

Hope that will help.

pointer to array c++

int g[] = {9,8};

This declares an object of type int[2], and initializes its elements to {9,8}

int (*j) = g;

This declares an object of type int *, and initializes it with a pointer to the first element of g.

The fact that the second declaration initializes j with something other than g is pretty strange. C and C++ just have these weird rules about arrays, and this is one of them. Here the expression g is implicitly converted from an lvalue referring to the object g into an rvalue of type int* that points at the first element of g.

This conversion happens in several places. In fact it occurs when you do g[0]. The array index operator doesn't actually work on arrays, only on pointers. So the statement int x = j[0]; works because g[0] happens to do that same implicit conversion that was done when j was initialized.

A pointer to an array is declared like this

int (*k)[2];

and you're exactly right about how this would be used

int x = (*k)[0];

(note how "declaration follows use", i.e. the syntax for declaring a variable of a type mimics the syntax for using a variable of that type.)

However one doesn't typically use a pointer to an array. The whole purpose of the special rules around arrays is so that you can use a pointer to an array element as though it were an array. So idiomatic C generally doesn't care that arrays and pointers aren't the same thing, and the rules prevent you from doing much of anything useful directly with arrays. (for example you can't copy an array like: int g[2] = {1,2}; int h[2]; h = g;)


Examples:

void foo(int c[10]); // looks like we're taking an array by value.
// Wrong, the parameter type is 'adjusted' to be int*

int bar[3] = {1,2};
foo(bar); // compile error due to wrong types (int[3] vs. int[10])?
// No, compiles fine but you'll probably get undefined behavior at runtime

// if you want type checking, you can pass arrays by reference (or just use std::array):
void foo2(int (&c)[10]); // paramater type isn't 'adjusted'
foo2(bar); // compiler error, cannot convert int[3] to int (&)[10]

int baz()[10]; // returning an array by value?
// No, return types are prohibited from being an array.

int g[2] = {1,2};
int h[2] = g; // initializing the array? No, initializing an array requires {} syntax
h = g; // copying an array? No, assigning to arrays is prohibited

Because arrays are so inconsistent with the other types in C and C++ you should just avoid them. C++ has std::array that is much more consistent and you should use it when you need statically sized arrays. If you need dynamically sized arrays your first option is std::vector.

How to restart Activity in Android

The solution for your question is:

public static void restartActivity(Activity act){
    Intent intent=new Intent();
    intent.setClass(act, act.getClass());
    ((Activity)act).startActivity(intent);
    ((Activity)act).finish();
}

You need to cast to activity context to start new activity and as well as to finish the current activity.

Hope this helpful..and works for me.

What's the most useful and complete Java cheat sheet?

  1. I have personally found the dzone cheatsheet on core java to be really handy in the beginning. However the needs change as we grow and get used to things.

  2. There are a few listed (at the end of the post) in on this java learning resources article too

  3. For the most practical use, in recent past I have found Java API doc to be the best place to cheat code and learn new api. This helps specially when you want to focus on latest version of java.

  4. mkyong - is one my fav places to cheat a lot of code for quick start - http://www.mkyong.com/

  5. And last but not the least, Stackoverflow is king of all small handy code snippets. Just google a stuff you are trying and there is a chance that a page will be top of search results, most of my google search results end at stackoverflow. Many of the common questions are available here - https://stackoverflow.com/questions/tagged/java?sort=frequent

adding x and y axis labels in ggplot2

since the data ex1221new was not given, so I have created a dummy data and added it to a data frame. Also, the question which was asked has few changes in codes like then ggplot package has deprecated the use of

"scale_area()" and nows uses scale_size_area()
"opts()" has changed to theme()

In my answer,I have stored the plot in mygraph variable and then I have used

mygraph$labels$x="Discharge of materials" #changes x axis title
       mygraph$labels$y="Area Affected" # changes y axis title

And the work is done. Below is the complete answer.

install.packages("Sleuth2")
library(Sleuth2)
library(ggplot2)

ex1221new<-data.frame(Discharge<-c(100:109),Area<-c(120:129),NO3<-seq(2,5,length.out = 10))
discharge<-ex1221new$Discharge
area<-ex1221new$Area
nitrogen<-ex1221new$NO3
p <- ggplot(ex1221new, aes(discharge, area), main="Point")
mygraph<-p + geom_point(aes(size= nitrogen)) + 
  scale_size_area() + ggtitle("Weighted Scatterplot of Watershed Area vs. Discharge and Nitrogen Levels (PPM)")+
theme(
 plot.title =  element_text(color="Blue", size=30, hjust = 0.5), 

 # change the styling of both the axis simultaneously from this-
 axis.title = element_text(color = "Green", size = 20, family="Courier",)
 

   # you can change the  axis title from the code below
   mygraph$labels$x="Discharge of materials" #changes x axis title
   mygraph$labels$y="Area Affected" # changes y axis title
   mygraph



   

Also, you can change the labels title from the same formula used above -

mygraph$labels$size= "N2" #size contains the nitrogen level 

How do I check if a directory exists? "is_dir", "file_exists" or both?

I think realpath() may be the best way to validate if a path exist http://www.php.net/realpath

Here is an example function:

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (long version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    if($path !== false AND is_dir($path))
    {
        // Return canonicalized absolute pathname
        return $path;
    }

    // Path/folder does not exist
    return false;
}

Short version of the same function

<?php
/**
 * Checks if a folder exist and return canonicalized absolute pathname (sort version)
 * @param string $folder the path being checked.
 * @return mixed returns the canonicalized absolute pathname on success otherwise FALSE is returned
 */
function folder_exist($folder)
{
    // Get canonicalized absolute pathname
    $path = realpath($folder);

    // If it exist, check if it's a directory
    return ($path !== false AND is_dir($path)) ? $path : false;
}

Output examples

<?php
/** CASE 1 **/
$input = '/some/path/which/does/not/exist';
var_dump($input);               // string(31) "/some/path/which/does/not/exist"
$output = folder_exist($input);
var_dump($output);              // bool(false)

/** CASE 2 **/
$input = '/home';
var_dump($input);
$output = folder_exist($input);         // string(5) "/home"
var_dump($output);              // string(5) "/home"

/** CASE 3 **/
$input = '/home/..';
var_dump($input);               // string(8) "/home/.."
$output = folder_exist($input);
var_dump($output);              // string(1) "/"

Usage

<?php

$folder = '/foo/bar';

if(FALSE !== ($path = folder_exist($folder)))
{
    die('Folder ' . $path . ' already exist');
}

mkdir($folder);
// Continue do stuff

How to give a pandas/matplotlib bar graph custom colors

For a more detailed answer on creating your own colormaps, I highly suggest visiting this page

If that answer is too much work, you can quickly make your own list of colors and pass them to the color parameter. All the colormaps are in the cm matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.

from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color

array([[ 0.865006,  0.316822,  0.226055,  1.      ],
       [ 0.851384,  0.30226 ,  0.239636,  1.      ],
       [ 0.832299,  0.283913,  0.257383,  1.      ],
       [ 0.817341,  0.270954,  0.27039 ,  1.      ],
       [ 0.796607,  0.254728,  0.287264,  1.      ],
       [ 0.775059,  0.239667,  0.303526,  1.      ],
       [ 0.758422,  0.229097,  0.315266,  1.      ],
       [ 0.735683,  0.215906,  0.330245,  1.      ],
       .....

Then we can use this to plot, using the data from the original post:

import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))

enter image description here

Set focus on TextBox in WPF from view model

I use WPF / Caliburn Micro a found that "dfaivre" has made a general and workable solution here: http://caliburnmicro.codeplex.com/discussions/222892

How to update Python?

The best solution is to install the different Python versions in multiple paths.

eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.

Read this for more info: How to run multiple Python versions on Windows

How can you determine a point is between two other points on a line segment?

Here is my solution with C# in Unity.

private bool _isPointOnLine( Vector2 ptLineStart, Vector2 ptLineEnd, Vector2 ptPoint )
{
    bool bRes = false;
    if((Mathf.Approximately(ptPoint.x, ptLineStart.x) || Mathf.Approximately(ptPoint.x, ptLineEnd.x)))
    {
        if(ptPoint.y > ptLineStart.y && ptPoint.y < ptLineEnd.y)
        {
            bRes = true;
        }
    }
    else if((Mathf.Approximately(ptPoint.y, ptLineStart.y) || Mathf.Approximately(ptPoint.y, ptLineEnd.y)))
    {
        if(ptPoint.x > ptLineStart.x && ptPoint.x < ptLineEnd.x)
        {
            bRes = true;
        }
    }
    return bRes;
}

Can I use jQuery to check whether at least one checkbox is checked?

$('#frmTest').submit(function(){
    if(!$('#frmTest input[type="checkbox"]').is(':checked')){
      alert("Please check at least one.");
      return false;
    }
});

is(':checked') will return true if at least one or more of the checkboxes are checked.

What is Type-safe?

An explanation from a liberal arts major, not a comp sci major:

When people say that a language or language feature is type safe, they mean that the language will help prevent you from, for example, passing something that isn't an integer to some logic that expects an integer.

For example, in C#, I define a function as:

 void foo(int arg)

The compiler will then stop me from doing this:

  // call foo
  foo("hello world")

In other languages, the compiler would not stop me (or there is no compiler...), so the string would be passed to the logic and then probably something bad will happen.

Type safe languages try to catch more at "compile time".

On the down side, with type safe languages, when you have a string like "123" and you want to operate on it like an int, you have to write more code to convert the string to an int, or when you have an int like 123 and want to use it in a message like, "The answer is 123", you have to write more code to convert/cast it to a string.

how to set imageview src?

What you are looking for is probably this:

ImageView myImageView;
myImageView = mDialog.findViewById(R.id.image_id);
String src = "imageFileName"

int drawableId = this.getResources().getIdentifier(src, "drawable", context.getPackageName())
popupImageView.setImageResource(drawableId);

Let me know if this was helpful :)

Running vbscript from batch file

Batch files are processed row by row and terminate whenever you call an executable directly.
- To make the batch file wait for the process to terminate and continue, put call in front of it.
- To make the batch file continue without waiting, put start "" in front of it.

I recommend using this single line script to accomplish your goal:

@call cscript "%~dp0necdaily.vbs"

(because this is a single line, you can use @ instead of @echo off)

If you believe your script can only be called from the SysWOW64 versions of cmd.exe, you might try:

@%WINDIR%\SysWOW64\cmd.exe /c call cscript "%~dp0necdaily.vbs"

If you need the window to remain, you can replace /c with /k

Open PDF in new browser full window

I'm going to take a chance here and actually advise against this. I suspect that people wanting to view your PDFs will already have their viewers set up the way they want, and will not take kindly to you taking that choice away from them :-)

Why not just stream down the content with the correct content specifier?

That way, newbies will get whatever their browser developer has a a useful default, and those of us that know how to configure such things will see it as we want to.

What is an attribute in Java?

A class contains data field descriptions (or properties, fields, data members, attributes), i.e., field types and names, that will be associated with either per-instance or per-class state variables at program run time.

How can I make a list of lists in R?

Using your example::

list1 <- list()
list1[1] = 1
list1[2] = 2
list2 <- list()
list2[1] = 'a'
list2[2] = 'b'
list_all <- list(list1, list2)

Use '[[' to retrieve an element of a list:

b = list_all[[1]]
 b
[[1]]
[1] 1

[[2]]
[1] 2

class(b)
[1] "list"

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

Exception: There is already an open DataReader associated with this Connection which must be closed first

Add MultipleActiveResultSets=true to the provider part of your connection string example in the file appsettings.json

"ConnectionStrings": {
"EmployeeDBConnection": "server=(localdb)\\MSSQLLocalDB;database=YourDatabasename;Trusted_Connection=true;MultipleActiveResultSets=true"}

Push existing project into Github

you will need to specify which branch and which remote when pushing:

? git init ./
? git add Readme.md
? git commit -m "Initial Commit"
? git remote add github <project url>
? git push github master

Will work as expected.

You can set this up by default by doing:

? git branch -u github/master master

which will allow you to do a git push from master without specifying the remote or branch.

to_string is not a member of std, says g++ (mingw)

For me, ensuring that I had:

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

in my file made something like to_string(12345) work.

Nginx not running with no error message

First, always sudo nginx -t to verify your config files are good.

I ran into the same problem. The reason I had the issue was twofold. First, I had accidentally copied a log file into my site-enabled folder. I deleted the log file and made sure that all the files in sites-enabled were proper nginx site configs. I also noticed two of my virtual hosts were listening for the same domain. So I made sure that each of my virtual hosts had unique domain names.

sudo service nginx restart

Then it worked.

How to show particular image as thumbnail while implementing share on Facebook?

My tags were correct but Facebook only scrapes every 24 hours, according to their documentation. Using the Facebook Lint page got the image into Facebook.

Enter your URL here and FB will update the metadata from your page:

https://developers.facebook.com/tools/debug (updated link)

How can you get the build/version number of your Android application?

try {
    PackageInfo packageInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
    String versionName = packageInfo.versionName;
    int versionCode = packageInfo.versionCode;
    //binding.tvVersionCode.setText("v" + packageInfo.versionName);
}
catch (PackageManager.NameNotFoundException e) {
    e.printStackTrace();
}

Python constructors and __init__

Classes are simply blueprints to create objects from. The constructor is some code that are run every time you create an object. Therefor it does'nt make sense to have two constructors. What happens is that the second over write the first.

What you typically use them for is create variables for that object like this:

>>> class testing:
...     def __init__(self, init_value):
...         self.some_value = init_value

So what you could do then is to create an object from this class like this:

>>> testobject = testing(5)

The testobject will then have an object called some_value that in this sample will be 5.

>>> testobject.some_value
5

But you don't need to set a value for each object like i did in my sample. You can also do like this:

>>> class testing:
...     def __init__(self):
...         self.some_value = 5

then the value of some_value will be 5 and you don't have to set it when you create the object.

>>> testobject = testing()
>>> testobject.some_value
5

the >>> and ... in my sample is not what you write. It's how it would look in pyshell...

How to enable remote access of mysql in centos?

so do the following edit my.cnf:

[mysqld]
user = mysql
pid-file = /var/run/mysqld/mysqld.pid
socket = /var/run/mysqld/mysqld.sock
port = 3306
basedir = /usr
datadir = /var/lib/mysql
tmpdir = /tmp
language = /usr/share/mysql/English
bind-address = xxx.xxx.xxx.xxx
# skip-networking

after edit hit service mysqld restart

login into mysql and hit this query:

GRANT ALL ON foo.* TO bar@'xxx.xxx.xxx.xxx' IDENTIFIED BY 'PASSWORD';

thats it make sure your iptables allow connection from 3306 if not put the following:

iptables -A INPUT -i lo -p tcp --dport 3306 -j ACCEPT

iptables -A OUTPUT -p tcp --sport 3306 -j ACCEPT

$ is not a function - jQuery error

As RPM1984 refers to, this is mostly likely caused by the fact that your script is loading before jQuery is loaded.

Any easy way to use icons from resources?

After adding the ICO file to your apps resources, you can use references it using My.Resources.YourIconNameWithoutExtension

For example if I had a file called Logo-square.ico added to my apps resources, I can set it to an icon with:

NotifyIcon1.Icon = My.Resources.Logo_square

C# Get/Set Syntax Usage

Assuming you have access to them (the properties you've declared are protected), you use them like this:

Person tom = new Person();
tom.Title = "A title";
string hisTitle = tom.Title;

These are properties. They're basically pairs of getter/setter methods (although you can have just a getter, or just a setter) with appropriate metadata. The example you've given is of automatically implemented properties where the compiler is adding a backing field. You can write the code yourself though. For example, the Title property you've declared is like this:

private string title; // Backing field
protected string Title
{
    get { return title; }  // Getter
    set { title = value; } // Setter
}

... except that the backing field is given an "unspeakable name" - one you can't refer to in your C# code. You're forced to go through the property itself.

You can make one part of a property more restricted than another. For example, this is quite common:

private string foo;
public string Foo
{
    get { return foo; }
    private set { foo = value; }
}

or as an automatically implemented property:

public string Foo { get; private set; }

Here the "getter" is public but the "setter" is private.

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.

Could not find a base address that matches scheme https for the endpoint with binding WebHttpBinding. Registered base address schemes are [http]

Change

<serviceMetadata httpsGetEnabled="true"/>

to

<serviceMetadata httpsGetEnabled="false"/>

You're telling WCF to use https for the metadata endpoint and I see that your'e exposing your service on http, and then you get the error in the title.

You also have to set <security mode="None" /> if you want to use HTTP as your URL suggests.

How to send a message to a particular client with socket.io

SURE: Simply,

This is what you need :

io.to(socket.id).emit("event", data);

whenever a user joined to the server, socket details will be generated including ID. This is the ID really helps to send a message to particular people.

first we need to store all the socket.ids in array,

var people={};

people[name] =  socket.id;

here name is the receiver name. Example:

people["ccccc"]=2387423cjhgfwerwer23;

So, now we can get that socket.id with the receiver name whenever we are sending message:

for this we need to know the receivername. You need to emit receiver name to the server.

final thing is:

 socket.on('chat message', function(data){
io.to(people[data.receiver]).emit('chat message', data.msg);
});

Hope this works well for you.

Good Luck!!

ListBox with ItemTemplate (and ScrollBar!)

ListBox will try to expand in height that is available.. When you set the Height property of ListBox you get a scrollviewer that actually works...

If you wish your ListBox to accodate the height available, you might want to try to regulate the Height from your parent controls.. In a Grid for example, setting the Height to Auto in your RowDefinition might do the trick...

HTH

Android Studio rendering problems

it still happens in Android Studio 1.5.1. on Ubuntu and you can solve it simply changing a setting from Gradle:

1) on app/build.gradle dependencies change from:

compile 'com.android.support:design:23.2.0'

to:

compile 'com.android.support:design:23.1.0'

2) rebuild project

3) refresh view

Best regards,

/Angel

When use getOne and findOne methods Spring Data JPA

The basic difference is that getOne is lazy loaded and findOne is not.

Consider the following example:

public static String NON_EXISTING_ID = -1;
...
MyEntity getEnt = myEntityRepository.getOne(NON_EXISTING_ID);
MyEntity findEnt = myEntityRepository.findOne(NON_EXISTING_ID);

if(findEnt != null) {
     findEnt.getText(); // findEnt is null - this code is not executed
}

if(getEnt != null) {
     getEnt.getText(); // Throws exception - no data found, BUT getEnt is not null!!!
}

Python: Ignore 'Incorrect padding' error when base64 decoding

Simply add additional characters like "=" or any other and make it a multiple of 4 before you try decoding the target string value. Something like;

if len(value) % 4 != 0: #check if multiple of 4
    while len(value) % 4 != 0:
        value = value + "="
    req_str = base64.b64decode(value)
else:
    req_str = base64.b64decode(value)

Why use Optional.of over Optional.ofNullable?

Optional should mainly be used for results of Services anyway. In the service you know what you have at hand and return Optional.of(someValue) if you have a result and return Optional.empty() if you don't. In this case, someValue should never be null and still, you return an Optional.

How to change MySQL column definition?

Do you mean altering the table after it has been created? If so you need to use alter table, in particular:

ALTER TABLE tablename MODIFY COLUMN new-column-definition

e.g.

ALTER TABLE test MODIFY COLUMN locationExpect VARCHAR(120);

Initialization of an ArrayList in one line

Here is code by AbacusUtil

// ArrayList
List<String> list = N.asList("Buenos Aires", "Córdoba", "La Plata");
// HashSet
Set<String> set = N.asSet("Buenos Aires", "Córdoba", "La Plata");
// HashMap
Map<String, Integer> map = N.asMap("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);

// Or for Immutable List/Set/Map
ImmutableList.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", "Córdoba", "La Plata");
ImmutableSet.of("Buenos Aires", 1, "Córdoba", 2, "La Plata", 3);

// The most efficient way, which is similar with Arrays.asList(...) in JDK. 
// but returns a flexible-size list backed by the specified array.
List<String> set = Array.asList("Buenos Aires", "Córdoba", "La Plata");

Declaration: I'm the developer of AbacusUtil.

json Uncaught SyntaxError: Unexpected token :

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

offsetting an html anchor to adjust for fixed header

I added 40px-height .vspace element holding the anchor before each of my h1 elements.

<div class="vspace" id="gherkin"></div>
<div class="page-header">
  <h1>Gherkin</h1>
</div>

In the CSS:

.vspace { height: 40px;}

It's working great and the space is not chocking.

SQL permissions for roles

USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO  ---- Assign Role To users -------  CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username'  ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO 

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

If you want to show/hide an element based on the status of one {{expression}} you can use ng-switch:

<p ng-switch="foo.bar">I could be shown, or I could be hidden</p>

The paragraph will be displayed when foo.bar is true, hidden when false.

Difference between volatile and synchronized in Java

synchronized is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.

volatile is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile variables. All threads can access volatile variable value at same time.

A good example to use volatile variable : Date variable.

Assume that you have made Date variable volatile. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.

enter image description here

Have a look at this article for better understanding of volatile concept.

Lawrence Dol cleary explained your read-write-update query.

Regarding your other queries

When is it more suitable to declare variables volatile than access them through synchronized?

You have to use volatile if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.

Is it a good idea to use volatile for variables that depend on input?

Answer will be same as in first query.

Refer to this article for better understanding.

In C/C++ what's the simplest way to reverse the order of bits in a byte?

This one is based on the one BobStein-VisiBone provided

#define reverse_1byte(b)    ( ((uint8_t)b & 0b00000001) ? 0b10000000 : 0 ) | \
                            ( ((uint8_t)b & 0b00000010) ? 0b01000000 : 0 ) | \
                            ( ((uint8_t)b & 0b00000100) ? 0b00100000 : 0 ) | \
                            ( ((uint8_t)b & 0b00001000) ? 0b00010000 : 0 ) | \
                            ( ((uint8_t)b & 0b00010000) ? 0b00001000 : 0 ) | \
                            ( ((uint8_t)b & 0b00100000) ? 0b00000100 : 0 ) | \
                            ( ((uint8_t)b & 0b01000000) ? 0b00000010 : 0 ) | \
                            ( ((uint8_t)b & 0b10000000) ? 0b00000001 : 0 ) 

I really like this one a lot because the compiler automatically handle the work for you, thus require no further resources.

this can also be extended to 16-Bits...

#define reverse_2byte(b)    ( ((uint16_t)b & 0b0000000000000001) ? 0b1000000000000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000000000000010) ? 0b0100000000000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000000000000100) ? 0b0010000000000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000000000001000) ? 0b0001000000000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000000000010000) ? 0b0000100000000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000000000100000) ? 0b0000010000000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000000001000000) ? 0b0000001000000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000000010000000) ? 0b0000000100000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000000100000000) ? 0b0000000010000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000001000000000) ? 0b0000000001000000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000010000000000) ? 0b0000000000100000 : 0 ) | \
                            ( ((uint16_t)b & 0b0000100000000000) ? 0b0000000000010000 : 0 ) | \
                            ( ((uint16_t)b & 0b0001000000000000) ? 0b0000000000001000 : 0 ) | \
                            ( ((uint16_t)b & 0b0010000000000000) ? 0b0000000000000100 : 0 ) | \
                            ( ((uint16_t)b & 0b0100000000000000) ? 0b0000000000000010 : 0 ) | \
                            ( ((uint16_t)b & 0b1000000000000000) ? 0b0000000000000001 : 0 ) 

How to parse XML in Bash?

starting from the chad's answer, here is the COMPLETE working solution to parse UML, with propper handling of comments, with just 2 little functions (more than 2 bu you can mix them all). I don't say chad's one didn't work at all, but it had too much issues with badly formated XML files: So you have to be a bit more tricky to handle comments and misplaced spaces/CR/TAB/etc.

The purpose of this answer is to give ready-2-use, out of the box bash functions to anyone needing parsing UML without complex tools using perl, python or anything else. As for me, I cannot install cpan, nor perl modules for the old production OS i'm working on, and python isn't available.

First, a definition of the UML words used in this post:

<!-- comment... -->
<tag attribute="value">content...</tag>

EDIT: updated functions, with handle of:

  • Websphere xml (xmi and xmlns attributes)
  • must have a compatible terminal with 256 colors
  • 24 shades of grey
  • compatibility added for IBM AIX bash 3.2.16(1)

The functions, first is the xml_read_dom which's called recursively by xml_read:

xml_read_dom() {
# https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash
local ENTITY IFS=\>
if $ITSACOMMENT; then
  read -d \< COMMENTS
  COMMENTS="$(rtrim "${COMMENTS}")"
  return 0
else
  read -d \< ENTITY CONTENT
  CR=$?
  [ "x${ENTITY:0:1}x" == "x/x" ] && return 0
  TAG_NAME=${ENTITY%%[[:space:]]*}
  [ "x${TAG_NAME}x" == "x?xmlx" ] && TAG_NAME=xml
  TAG_NAME=${TAG_NAME%%:*}
  ATTRIBUTES=${ENTITY#*[[:space:]]}
  ATTRIBUTES="${ATTRIBUTES//xmi:/}"
  ATTRIBUTES="${ATTRIBUTES//xmlns:/}"
fi

# when comments sticks to !-- :
[ "x${TAG_NAME:0:3}x" == "x!--x" ] && COMMENTS="${TAG_NAME:3} ${ATTRIBUTES}" && ITSACOMMENT=true && return 0

# http://tldp.org/LDP/abs/html/string-manipulation.html
# INFO: oh wait it doesn't work on IBM AIX bash 3.2.16(1):
# [ "x${ATTRIBUTES:(-1):1}x" == "x/x" -o "x${ATTRIBUTES:(-1):1}x" == "x?x" ] && ATTRIBUTES="${ATTRIBUTES:0:(-1)}"
[ "x${ATTRIBUTES:${#ATTRIBUTES} -1:1}x" == "x/x" -o "x${ATTRIBUTES:${#ATTRIBUTES} -1:1}x" == "x?x" ] && ATTRIBUTES="${ATTRIBUTES:0:${#ATTRIBUTES} -1}"
return $CR
}

and the second one :

xml_read() {
# https://stackoverflow.com/questions/893585/how-to-parse-xml-in-bash
ITSACOMMENT=false
local MULTIPLE_ATTR LIGHT FORCE_PRINT XAPPLY XCOMMAND XATTRIBUTE GETCONTENT fileXml tag attributes attribute tag2print TAGPRINTED attribute2print XAPPLIED_COLOR PROSTPROCESS USAGE
local TMP LOG LOGG
LIGHT=false
FORCE_PRINT=false
XAPPLY=false
MULTIPLE_ATTR=false
XAPPLIED_COLOR=g
TAGPRINTED=false
GETCONTENT=false
PROSTPROCESS=cat
Debug=${Debug:-false}
TMP=/tmp/xml_read.$RANDOM
USAGE="${C}${FUNCNAME}${c} [-cdlp] [-x command <-a attribute>] <file.xml> [tag | \"any\"] [attributes .. | \"content\"]
${nn[2]}  -c = NOCOLOR${END}
${nn[2]}  -d = Debug${END}
${nn[2]}  -l = LIGHT (no \"attribute=\" printed)${END}
${nn[2]}  -p = FORCE PRINT (when no attributes given)${END}
${nn[2]}  -x = apply a command on an attribute and print the result instead of the former value, in green color${END}
${nn[1]}  (no attribute given will load their values into your shell; use '-p' to print them as well)${END}"

! (($#)) && echo2 "$USAGE" && return 99
(( $# < 2 )) && ERROR nbaram 2 0 && return 99
# getopts:
while getopts :cdlpx:a: _OPT 2>/dev/null
do
{
  case ${_OPT} in
    c) PROSTPROCESS="${DECOLORIZE}" ;;
    d) local Debug=true ;;
    l) LIGHT=true; XAPPLIED_COLOR=END ;;
    p) FORCE_PRINT=true ;;
    x) XAPPLY=true; XCOMMAND="${OPTARG}" ;;
    a) XATTRIBUTE="${OPTARG}" ;;
    *) _NOARGS="${_NOARGS}${_NOARGS+, }-${OPTARG}" ;;
  esac
}
done
shift $((OPTIND - 1))
unset _OPT OPTARG OPTIND
[ "X${_NOARGS}" != "X" ] && ERROR param "${_NOARGS}" 0

fileXml=$1
tag=$2
(( $# > 2 )) && shift 2 && attributes=$*
(( $# > 1 )) && MULTIPLE_ATTR=true

[ -d "${fileXml}" -o ! -s "${fileXml}" ] && ERROR empty "${fileXml}" 0 && return 1
$XAPPLY && $MULTIPLE_ATTR && [ -z "${XATTRIBUTE}" ] && ERROR param "-x command " 0 && return 2
# nb attributes == 1 because $MULTIPLE_ATTR is false
[ "${attributes}" == "content" ] && GETCONTENT=true

while xml_read_dom; do
  # (( CR != 0 )) && break
  (( PIPESTATUS[1] != 0 )) && break

  if $ITSACOMMENT; then
    # oh wait it doesn't work on IBM AIX bash 3.2.16(1):
    # if [ "x${COMMENTS:(-2):2}x" == "x--x" ]; then COMMENTS="${COMMENTS:0:(-2)}" && ITSACOMMENT=false
    # elif [ "x${COMMENTS:(-3):3}x" == "x-->x" ]; then COMMENTS="${COMMENTS:0:(-3)}" && ITSACOMMENT=false
    if [ "x${COMMENTS:${#COMMENTS} - 2:2}x" == "x--x" ]; then COMMENTS="${COMMENTS:0:${#COMMENTS} - 2}" && ITSACOMMENT=false
    elif [ "x${COMMENTS:${#COMMENTS} - 3:3}x" == "x-->x" ]; then COMMENTS="${COMMENTS:0:${#COMMENTS} - 3}" && ITSACOMMENT=false
    fi
    $Debug && echo2 "${N}${COMMENTS}${END}"
  elif test "${TAG_NAME}"; then
    if [ "x${TAG_NAME}x" == "x${tag}x" -o "x${tag}x" == "xanyx" ]; then
      if $GETCONTENT; then
        CONTENT="$(trim "${CONTENT}")"
        test ${CONTENT} && echo "${CONTENT}"
      else
        # eval local $ATTRIBUTES => eval test "\"\$${attribute}\"" will be true for matching attributes
        eval local $ATTRIBUTES
        $Debug && (echo2 "${m}${TAG_NAME}: ${M}$ATTRIBUTES${END}"; test ${CONTENT} && echo2 "${m}CONTENT=${M}$CONTENT${END}")
        if test "${attributes}"; then
          if $MULTIPLE_ATTR; then
            # we don't print "tag: attr=x ..." for a tag passed as argument: it's usefull only for "any" tags so then we print the matching tags found
            ! $LIGHT && [ "x${tag}x" == "xanyx" ] && tag2print="${g6}${TAG_NAME}: "
            for attribute in ${attributes}; do
              ! $LIGHT && attribute2print="${g10}${attribute}${g6}=${g14}"
              if eval test "\"\$${attribute}\""; then
                test "${tag2print}" && ${print} "${tag2print}"
                TAGPRINTED=true; unset tag2print
                if [ "$XAPPLY" == "true" -a "${attribute}" == "${XATTRIBUTE}" ]; then
                  eval ${print} "%s%s\ " "\${attribute2print}" "\${${XAPPLIED_COLOR}}\"\$(\$XCOMMAND \$${attribute})\"\${END}" && eval unset ${attribute}
                else
                  eval ${print} "%s%s\ " "\${attribute2print}" "\"\$${attribute}\"" && eval unset ${attribute}
                fi
              fi
            done
            # this trick prints a CR only if attributes have been printed durint the loop:
            $TAGPRINTED && ${print} "\n" && TAGPRINTED=false
          else
            if eval test "\"\$${attributes}\""; then
              if $XAPPLY; then
                eval echo "\${g}\$(\$XCOMMAND \$${attributes})" && eval unset ${attributes}
              else
                eval echo "\$${attributes}" && eval unset ${attributes}
              fi
            fi
          fi
        else
          echo eval $ATTRIBUTES >>$TMP
        fi
      fi
    fi
  fi
  unset CR TAG_NAME ATTRIBUTES CONTENT COMMENTS
done < "${fileXml}" | ${PROSTPROCESS}
# http://mywiki.wooledge.org/BashFAQ/024
# INFO: I set variables in a "while loop" that's in a pipeline. Why do they disappear? workaround:
if [ -s "$TMP" ]; then
  $FORCE_PRINT && ! $LIGHT && cat $TMP
  # $FORCE_PRINT && $LIGHT && perl -pe 's/[[:space:]].*?=/ /g' $TMP
  $FORCE_PRINT && $LIGHT && sed -r 's/[^\"]*([\"][^\"]*[\"][,]?)[^\"]*/\1 /g' $TMP
  . $TMP
  rm -f $TMP
fi
unset ITSACOMMENT
}

and lastly, the rtrim, trim and echo2 (to stderr) functions:

rtrim() {
local var=$@
var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
echo -n "$var"
}
trim() {
local var=$@
var="${var#"${var%%[![:space:]]*}"}"   # remove leading whitespace characters
var="${var%"${var##*[![:space:]]}"}"   # remove trailing whitespace characters
echo -n "$var"
}
echo2() { echo -e "$@" 1>&2; }

Colorization:

oh and you will need some neat colorizing dynamic variables to be defined at first, and exported, too:

set -a
TERM=xterm-256color
case ${UNAME} in
AIX|SunOS)
  M=$(${print} '\033[1;35m')
  m=$(${print} '\033[0;35m')
  END=$(${print} '\033[0m')
;;
*)
  m=$(tput setaf 5)
  M=$(tput setaf 13)
  # END=$(tput sgr0)          # issue on Linux: it can produces ^[(B instead of ^[[0m, more likely when using screenrc
  END=$(${print} '\033[0m')
;;
esac
# 24 shades of grey:
for i in $(seq 0 23); do eval g$i="$(${print} \"\\033\[38\;5\;$((232 + i))m\")" ; done
# another way of having an array of 5 shades of grey:
declare -a colorNums=(238 240 243 248 254)
for num in 0 1 2 3 4; do nn[$num]=$(${print} "\033[38;5;${colorNums[$num]}m"); NN[$num]=$(${print} "\033[48;5;${colorNums[$num]}m"); done
# piped decolorization:
DECOLORIZE='eval sed "s,${END}\[[0-9;]*[m|K],,g"'

How to load all that stuff:

Either you know how to create functions and load them via FPATH (ksh) or an emulation of FPATH (bash)

If not, just copy/paste everything on the command line.

How does it work:

xml_read [-cdlp] [-x command <-a attribute>] <file.xml> [tag | "any"] [attributes .. | "content"]
  -c = NOCOLOR
  -d = Debug
  -l = LIGHT (no \"attribute=\" printed)
  -p = FORCE PRINT (when no attributes given)
  -x = apply a command on an attribute and print the result instead of the former value, in green color
  (no attribute given will load their values into your shell as $ATTRIBUTE=value; use '-p' to print them as well)

xml_read server.xml title content     # print content between <title></title>
xml_read server.xml Connector port    # print all port values from Connector tags
xml_read server.xml any port          # print all port values from any tags

With Debug mode (-d) comments and parsed attributes are printed to stderr

How to sort ArrayList<Long> in decreasing order?

You can use the following code which is given below;

Collections.sort(list, Collections.reverseOrder());

or if you are going to use custom comparator you can use as it is given below

Collections.sort(list, Collections.reverseOrder(new CustomComparator());

Where CustomComparator is a comparator class that compares the object which is present in the list.

How to add Action bar options menu in Android Fragments

in AndroidManifest.xml set theme holo like this:

<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >

Store a closure as a variable in Swift

Objective-C

@interface PopupView : UIView
@property (nonatomic, copy) void (^onHideComplete)();
@end

@interface PopupView ()

...

- (IBAction)hideButtonDidTouch:(id sender) {
    // Do something
    ...
    // Callback
    if (onHideComplete) onHideComplete ();
}

@end

PopupView * popupView = [[PopupView alloc] init]
popupView.onHideComplete = ^() {
    ...
}

Swift

class PopupView: UIView {
    var onHideComplete: (() -> Void)?

    @IBAction func hideButtonDidTouch(sender: AnyObject) {
        // Do something
        ....
        // Callback
        if let callback = self.onHideComplete {
            callback ()
        }
    }
}

var popupView = PopupView ()
popupView.onHideComplete = {
    () -> Void in 
    ...
}

Upgrade Node.js to the latest version on Mac OS

I use Node version manager (called n) for it.

npm install -g n

then

n latest

OR

n stable

How to insert new cell into UITableView in Swift

For Swift 5

Remove Cell

    let indexPath = [NSIndexPath(row: yourArray-1, section: 0)]
    yourArray.remove(at: buttonTag)
    self.tableView.beginUpdates()

    self.tableView.deleteRows(at: indexPath as [IndexPath] , with: .fade)
    self.tableView.endUpdates()
    self.tableView.reloadData()// Not mendatory, But In my case its requires

Add new cell

    yourArray.append(4)

    tableView.beginUpdates()
    tableView.insertRows(at: [
        (NSIndexPath(row: yourArray.count-1, section: 0) as IndexPath)], with: .automatic)
    tableView.endUpdates()

XAMPP Apache won't start

Open services.msc directly from command prompt and disabled SQL Server reporting services

& SQL Server analysis services.

Trying to make bootstrap modal wider

Always have handy the un-minified CSS for bootstrap so you can see what styles they have on their components, then create a CSS file AFTER it, if you don't use LESS and over-write their mixins or whatever

This is the default modal css for 768px and up:

@media (min-width: 768px) {
  .modal-dialog {
    width: 600px;
    margin: 30px auto;
  }
  ...
}

They have a class modal-lg for larger widths

@media (min-width: 992px) {
  .modal-lg {
    width: 900px;
  }
}

If you need something twice the 600px size, and something fluid, do something like this in your CSS after the Bootstrap css and assign that class to the modal-dialog.

@media (min-width: 768px) {
  .modal-xl {
    width: 90%;
   max-width:1200px;
  }
}

HTML

<div class="modal-dialog modal-xl">

Demo: http://jsbin.com/yefas/1

C# Reflection: How to get class reference from string?

You can use Type.GetType(string), but you'll need to know the full class name including namespace, and if it's not in the current assembly or mscorlib you'll need the assembly name instead. (Ideally, use Assembly.GetType(typeName) instead - I find that easier in terms of getting the assembly reference right!)

For instance:

// "I know String is in the same assembly as Int32..."
Type stringType = typeof(int).Assembly.GetType("System.String");

// "It's in the current assembly"
Type myType = Type.GetType("MyNamespace.MyType");

// "It's in System.Windows.Forms.dll..."
Type formType = Type.GetType ("System.Windows.Forms.Form, " + 
    "System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " + 
    "PublicKeyToken=b77a5c561934e089");

How to write and read java serialized objects into a file

Why not serialize the whole list at once?

FileOutputStream fout = new FileOutputStream("G:\\address.ser");
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(MyClassList);

Assuming, of course, that MyClassList is an ArrayList or LinkedList, or another Serializable collection.

In the case of reading it back, in your code you ready only one item, there is no loop to gather all the item written.

sprintf like functionality in Python

Something like...

greetings = 'Hello {name}'.format(name = 'John')

Hello John

How to play .wav files with java

You can use an event listener to close the clip after it is played

import java.io.File;
import javax.sound.sampled.*;

public void play(File file) 
{
    try
    {
        final Clip clip = (Clip)AudioSystem.getLine(new Line.Info(Clip.class));

        clip.addLineListener(new LineListener()
        {
            @Override
            public void update(LineEvent event)
            {
                if (event.getType() == LineEvent.Type.STOP)
                    clip.close();
            }
        });

        clip.open(AudioSystem.getAudioInputStream(file));
        clip.start();
    }
    catch (Exception exc)
    {
        exc.printStackTrace(System.out);
    }
}

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

You should probably set all of the cookie properties not just the value of it. setPath(), setDomain() ... etc

C++ program converts fahrenheit to celsius

The answer has already been found although I would also like to share my answer:

int main(void)
{
using namespace std;

short tempC;
cout << "Please enter a Celsius value: ";
cin >> tempC;
double tempF = convert(tempC);
cout << tempC << " degrees Celsius is " << tempF << " degrees Fahrenheit." << endl;
cin.get();
cin.get();
return 0;

}

int convert(short nT)
{
return nT * 1.8 + 32;
}

This is a more proper way to do this; however, it is slightly more complex then what you were going for.

Why does calling sumr on a stream with 50 tuples not complete

sumr is implemented in terms of foldRight:

 final def sumr(implicit A: Monoid[A]): A = F.foldRight(self, A.zero)(A.append) 

foldRight is not always tail recursive, so you can overflow the stack if the collection is too long. See Why foldRight and reduceRight are NOT tail recursive? for some more discussion of when this is or isn't true.

shuffling/permutating a DataFrame in pandas

Sampling randomizes, so just sample the entire data frame.

df.sample(frac=1)

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

Get the value of bootstrap Datetimepicker in JavaScript

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

ActiveModel::ForbiddenAttributesError when creating new user

If using ActiveAdmin don't forget that there is also a permit_params in the model register block:

ActiveAdmin.register Api::V1::Person do
  permit_params :name, :address, :etc
end

These need to be set along with those in the controller:

def api_v1_person_params
  params.require(:api_v1_person).permit(:name, :address, :etc)
end

Otherwise you will get the error:

ActiveModel::ForbiddenAttributesError

Spring MVC - HttpMediaTypeNotAcceptableException

In my case, just add @ResponseBody annotation to solve this issue.

Counting null and non-null values in a single query

In my case I wanted the "null distribution" amongst multiple columns:

SELECT
       (CASE WHEN a IS NULL THEN 'NULL' ELSE 'NOT-NULL' END) AS a_null,
       (CASE WHEN b IS NULL THEN 'NULL' ELSE 'NOT-NULL' END) AS b_null,
       (CASE WHEN c IS NULL THEN 'NULL' ELSE 'NOT-NULL' END) AS c_null,
       ...
       count(*)
FROM us
GROUP BY 1, 2, 3,...
ORDER BY 1, 2, 3,...

As per the '...' it is easily extendable to more columns, as many as needed

Parsing huge logfiles in Node.js - read in line-by-line

I searched for a solution to parse very large files (gbs) line by line using a stream. All the third-party libraries and examples did not suit my needs since they processed the files not line by line (like 1 , 2 , 3 , 4 ..) or read the entire file to memory

The following solution can parse very large files, line by line using stream & pipe. For testing I used a 2.1 gb file with 17.000.000 records. Ram usage did not exceed 60 mb.

First, install the event-stream package:

npm install event-stream

Then:

var fs = require('fs')
    , es = require('event-stream');

var lineNr = 0;

var s = fs.createReadStream('very-large-file.csv')
    .pipe(es.split())
    .pipe(es.mapSync(function(line){

        // pause the readstream
        s.pause();

        lineNr += 1;

        // process line here and call s.resume() when rdy
        // function below was for logging memory usage
        logMemoryUsage(lineNr);

        // resume the readstream, possibly from a callback
        s.resume();
    })
    .on('error', function(err){
        console.log('Error while reading file.', err);
    })
    .on('end', function(){
        console.log('Read entire file.')
    })
);

enter image description here

Please let me know how it goes!

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

Go to dev.twitter.com and create an application. This will provide you with the credentials you need. Here is an implementation I've recently written with PHP and cURL.

<?php
    function buildBaseString($baseURI, $method, $params) {
        $r = array();
        ksort($params);
        foreach($params as $key=>$value){
            $r[] = "$key=" . rawurlencode($value);
        }
        return $method."&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $r));
    }

    function buildAuthorizationHeader($oauth) {
        $r = 'Authorization: OAuth ';
        $values = array();
        foreach($oauth as $key=>$value)
            $values[] = "$key=\"" . rawurlencode($value) . "\"";
        $r .= implode(', ', $values);
        return $r;
    }

    $url = "https://api.twitter.com/1.1/statuses/user_timeline.json";

    $oauth_access_token = "YOURVALUE";
    $oauth_access_token_secret = "YOURVALUE";
    $consumer_key = "YOURVALUE";
    $consumer_secret = "YOURVALUE";

    $oauth = array( 'oauth_consumer_key' => $consumer_key,
                    'oauth_nonce' => time(),
                    'oauth_signature_method' => 'HMAC-SHA1',
                    'oauth_token' => $oauth_access_token,
                    'oauth_timestamp' => time(),
                    'oauth_version' => '1.0');

    $base_info = buildBaseString($url, 'GET', $oauth);
    $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
    $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
    $oauth['oauth_signature'] = $oauth_signature;

    // Make requests
    $header = array(buildAuthorizationHeader($oauth), 'Expect:');
    $options = array( CURLOPT_HTTPHEADER => $header,
                      //CURLOPT_POSTFIELDS => $postfields,
                      CURLOPT_HEADER => false,
                      CURLOPT_URL => $url,
                      CURLOPT_RETURNTRANSFER => true,
                      CURLOPT_SSL_VERIFYPEER => false);

    $feed = curl_init();
    curl_setopt_array($feed, $options);
    $json = curl_exec($feed);
    curl_close($feed);

    $twitter_data = json_decode($json);

//print it out
print_r ($twitter_data);

?>

This can be run from the command line:

$ php <name of PHP script>.php

How to exit an Android app programmatically?

How about this.finishAffinity()

From the docs,

Finish this activity as well as all activities immediately below it in the current task that have the same affinity. This is typically used when an application can be launched on to another task (such as from an ACTION_VIEW of a content type it understands) and the user has used the up navigation to switch out of the current task and in to its own task. In this case, if the user has navigated down into any other activities of the second application, all of those should be removed from the original task as part of the task switch. Note that this finish does not allow you to deliver results to the previous activity, and an exception will be thrown if you are trying to do so.

Can I load a .NET assembly at runtime and instantiate a type knowing only the name?

((ISomeInterface)Activator.CreateInstance(Assembly.LoadFile("somePath").GetTypes()[0])).SomeInterfaceMethod();

How to find the minimum value of a column in R?

If you prefer using column names, you could do something like this as an alternative:

min(data$column_name)

How do I open a second window from the first window in WPF?

Write your code in window1.

private void Button_Click(object sender, RoutedEventArgs e)
{
    window2 win2 = new window2();
    win2.Show();
}

Write to CSV file and export it?

Here's a very simple free open-source CsvExport class for C#. There's an ASP.NET MVC example at the bottom.

https://github.com/jitbit/CsvExport

It takes care about line-breaks, commas, escaping quotes, MS Excel compatibilty... Just add one short .cs file to your project and you're good to go.

(disclaimer: I'm one of the contributors)

How do I restrict a float value to only two places after the decimal point in C?

Let me first attempt to justify my reason for adding yet another answer to this question. In an ideal world, rounding is not really a big deal. However, in real systems, you may need to contend with several issues that can result in rounding that may not be what you expect. For example, you may be performing financial calculations where final results are rounded and displayed to users as 2 decimal places; these same values are stored with fixed precision in a database that may include more than 2 decimal places (for various reasons; there is no optimal number of places to keep...depends on specific situations each system must support, e.g. tiny items whose prices are fractions of a penny per unit); and, floating point computations performed on values where the results are plus/minus epsilon. I have been confronting these issues and evolving my own strategy over the years. I won't claim that I have faced every scenario or have the best answer, but below is an example of my approach so far that overcomes these issues:

Suppose 6 decimal places is regarded as sufficient precision for calculations on floats/doubles (an arbitrary decision for the specific application), using the following rounding function/method:

double Round(double x, int p)
{
    if (x != 0.0) {
        return ((floor((fabs(x)*pow(double(10.0),p))+0.5))/pow(double(10.0),p))*(x/fabs(x));
    } else {
        return 0.0;
    }
}

Rounding to 2 decimal places for presentation of a result can be performed as:

double val;
// ...perform calculations on val
String(Round(Round(Round(val,8),6),2));

For val = 6.825, result is 6.83 as expected.

For val = 6.824999, result is 6.82. Here the assumption is that the calculation resulted in exactly 6.824999 and the 7th decimal place is zero.

For val = 6.8249999, result is 6.83. The 7th decimal place being 9 in this case causes the Round(val,6) function to give the expected result. For this case, there could be any number of trailing 9s.

For val = 6.824999499999, result is 6.83. Rounding to the 8th decimal place as a first step, i.e. Round(val,8), takes care of the one nasty case whereby a calculated floating point result calculates to 6.8249995, but is internally represented as 6.824999499999....

Finally, the example from the question...val = 37.777779 results in 37.78.

This approach could be further generalized as:

double val;
// ...perform calculations on val
String(Round(Round(Round(val,N+2),N),2));

where N is precision to be maintained for all intermediate calculations on floats/doubles. This works on negative values as well. I do not know if this approach is mathematically correct for all possibilities.

When & why to use delegates?

I consider delegates to be Anonymous Interfaces. In many cases you can use them whenever you need an interface with a single method, but you don't want the overhead of defining that interface.

How to delete multiple rows in SQL where id = (x to y)

You can use BETWEEN:

DELETE FROM table
where id between 163 and 265

What is the difference between a token and a lexeme?

Let's see the working of a lexical analyser ( also called Scanner )

Let's take an example expression :

INPUT : cout << 3+2+3;

FORMATTING PERFORMED BY SCANNER :  {cout}|space|{<<}|space|{3}{+}{2}{+}{3}{;} 

not the actual output though .

SCANNER SIMPLY LOOKS REPEATEDLY FOR A LEXEME IN SOURCE-PROGRAM TEXT UNTIL INPUT IS EXHAUSTED

Lexeme is a substring of input that forms a valid string-of-terminals present in grammar . Every lexeme follows a pattern which is explained at the end ( the part that reader may skip at last )

( Important rule is to look for the longest possible prefix forming a valid string-of-terminals until next whitespace is encountered ... explained below )

LEXEMES :

  1. cout
  2. <<

( although "<" is also valid terminal-string but above mentioned rule shall select the pattern for lexeme "<<" in order to generate token returned by scanner )

  1. 3
  2. +
  3. 2
  4. ;

TOKENS : Tokens are returned one at a time ( by Scanner when requested by Parser ) each time Scanner finds a (valid) lexeme. Scanner creates ,if not already present, a symbol-table entry ( having attributes : mainly token-category and few others ) , when it finds a lexeme, in order to generate it's token

'#' denotes a symbol table entry . I have pointed to lexeme number in above list for ease of understanding but it technically should be actual index of record in symbol table.

The following tokens are returned by scanner to parser in specified order for above example.

  1. < identifier , #1 >

  2. < Operator , #2 >

  3. < Literal , #3 >

  4. < Operator , #4 >

  5. < Literal , #5 >

  6. < Operator , #4 >

  7. < Literal , #3 >

  8. < Punctuator , #6 >

As you can see the difference , a token is a pair unlike lexeme which is a substring of input.

And first element of the pair is the token-class/category

Token Classes are listed below:

  • KEYWORDS
  • IDENTIFIERS
  • LITERALS
  • PUNCTUATORS
  • OPERATORS
  • And one more thing , Scanner detects whitespaces , ignores them and does not form any token for a whitespace at all. Not all delimiters are whitespaces, a whitespace is one form of delimiter used by scanners for it's purpose . Tabs , Newlines , Spaces , Escaped Characters in input all are collectively called Whitespace delimiters. Few other delimiters are ';' ',' ':' etc, which are widely recognised as lexemes that form token.

    Total number of tokens returned are 8 here , however only 6 symbol table entries are made for lexemes . Lexemes are also 8 in total ( see definition of lexeme )

    --- You can skip this part

    A ***pattern*** is a rule ( say, a regular expression ) that is used to check if a string-of-terminals is valid or not.

    If a substring of input composed only of grammar terminals is following the rule specified by any of the listed patterns , it is validated as a lexeme and selected pattern will identify the category of lexeme, else a lexical error is reported due to either (i) not following any of the rules or (ii) input consists of a bad terminal-character not present in grammar itself.

    for example :
    
    1. No Pattern Exists : In C++ , "99Id_Var" is grammar-supported string-of-terminals but is not recognised by any of patterns hence lexical error is reported .
    
    2. Bad Input Character : $,@,unicode characters may not be supported as a valid character in few programming languages.`
    

    How can I access each element of a pair in a pair list?

    A 2-tuple is a pair. You can access the first and second elements like this:

    x = ('a', 1) # make a pair
    x[0] # access 'a'
    x[1] # access 1
    

    Python Iterate Dictionary by Index

    There are some very good answers here. I'd like to add the following here as well:

    some_dict = {
        "foo": "bar",
        "lorem": "ipsum"
    }
    
    for index, (key, value) in enumerate(some_dict.items()):
        print(index, key, value)
    

    results in

    0 foo bar
    1 lorem ipsum
    

    Appears to work with Python 2.7 and 3.5

    How do I read a date in Excel format in Python?

    This is a revised version from @hounded. My code handles both date and time, something like 43705.591795706

        import math
        import datetime
    
    
        def xldate_to_datetime(xldatetime): #something like 43705.6158241088
    
          tempDate = datetime.datetime(1899, 12, 31)
          (days, portion) = math.modf(xldatetime)
    
          deltaDays = datetime.timedelta(days=days)
          #changing the variable name in the edit
          secs = int(24 * 60 * 60 * portion)
          detlaSeconds = datetime.timedelta(seconds=secs)
          TheTime = (tempDate + deltaDays + detlaSeconds )
          return TheTime.strftime("%Y-%m-%d %H:%M:%S")
    
    
    xldate_to_datetime(43705.6158241088)
    # 2019-08-29 14:46:47
    

    Angular 2 Scroll to bottom (Chat style)

    In angular using material design sidenav I had to use the following:

    let ele = document.getElementsByClassName('md-sidenav-content');
        let eleArray = <Element[]>Array.prototype.slice.call(ele);
        eleArray.map( val => {
            val.scrollTop = val.scrollHeight;
        });
    

    How to export a table dataframe in PySpark to csv?

    For Apache Spark 2+, in order to save dataframe into single csv file. Use following command

    query.repartition(1).write.csv("cc_out.csv", sep='|')
    

    Here 1 indicate that I need one partition of csv only. you can change it according to your requirements.

    File changed listener in Java

    I run this snippet of code every time I go to read the properties file, only actually reading the file if it has been modified since the last time I read it. Hope this helps someone.

    private long timeStamp;
    private File file;
    
    private boolean isFileUpdated( File file ) {
      this.file = file;
      this.timeStamp = file.lastModified();
    
      if( this.timeStamp != timeStamp ) {
        this.timeStamp = timeStamp;
        //Yes, file is updated
        return true;
      }
      //No, file is not updated
      return false;
    }
    

    Similar approach is used in Log4J FileWatchdog.

    What is the result of % in Python?

    The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type.

    3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6 = 7

    This is based on operator precedence.

    Descending order by date filter in AngularJs

    You can prefix the argument in orderBy with a '-' to have descending order instead of ascending. I would write it like this:

    <div class="recent" 
       ng-repeat="reader in book.reader | orderBy: '-created_at' | limitTo: 1">
    </div>
    

    This is also stated in the documentation for the filter orderBy.

    Testing if value is a function

    You can try modifying this technique to suit your needs:

     function isFunction() {
       var functionName = window.prompt('Function name: ');
       var isDefined = eval('(typeof ' + functionName + '==\'function\');');
       if (isDefined)
         eval(functionName + '();');
       else
         alert('Function ' + functionName + ' does not exist');
     }
     function anotherFunction() {
       alert('message from another function.');
     }
    

    Select Row number in postgres

    SELECT tab.*,
        row_number() OVER () as rnum
      FROM tab;
    

    Here's the relevant section in the docs.

    P.S. This, in fact, fully matches the answer in the referenced question.

    How to export a mysql database using Command Prompt?

    Simply use the following command,

    For Export:

    mysqldump -u [user] -p [db_name] | gzip > [filename_to_compress.sql.gz] 
    

    For Import:

    gunzip < [compressed_filename.sql.gz]  | mysql -u [user] -p[password] [databasename] 
    

    Note: There is no space between the keyword '-p' and your password.

    Can't connect to localhost on SQL Server Express 2012 / 2016

    According to Aaron Bertand:

    1. You need to verify that the SQL Server service is running. You can do this by going to Start > Control Panel > Administrative Tools > Services, and checking that the service SQL Server (SQLEXPRESS) is running. If not, start it.

    2. While you're in the services applet, also make sure that the service SQL Browser is started. If not, start it.

    3. You need to make sure that SQL Server is allowed to use TCP/IP or named pipes. You can turn these on by opening the SQL Server Configuration Manager in Start > Programs > Microsoft SQL Server 2012 > Configuration Tools (or SQL Server Configuration Manager), and make sure that TCP/IP and Named Pipes are enabled. If you don't find the SQL Server Configuration Manager in the Start Menu you can launch the MMC snap-in manually. Check SQL Server Configuration Manager for the path to the snap-in according to your version.

      SQL Server Configuration Manager

    4. Verify your SQL Server connection authentication mode matches your connection string:

      • If you're connecting using a username and password, you need to configure SQL Server to accept "SQL Server Authentication Mode":

        -- YOU MUST RESTART YOUR SQL SERVER AFTER RUNNING THIS!
        USE [master]
        GO
        DECLARE @SqlServerAndWindowsAuthenticationMode INT = 2;
        EXEC xp_instance_regwrite
          N'HKEY_LOCAL_MACHINE',
          N'Software\Microsoft\MSSQLServer\MSSQLServer',
          N'LoginMode',
          REG_DWORD,
          @SqlServerAndWindowsAuthenticationMode;
        GO
        
      • If you're connecting using "Integrated Security=true" (Windows Mode), and this error only comes up when debugging in web applications, then you need to add the ApplicationPoolIdentity as a SQL Server login:
    5. otherwise, run Start -> Run -> Services.msc If so, is it running?

    If it's not running then

    It sounds like you didn't get everything installed. Launch the install file and chose the option "New installation or add features to an existing installation". From there you should be able to make sure the database engine service gets installed.

    Error:attempt to apply non-function

    I got the error because of a clumsy typo:

    This errors:

    knitr::opts_chunk$seet(echo = FALSE)
    

    Error: attempt to apply non-function

    After correcting the typo, it works:

    knitr::opts_chunk$set(echo = FALSE)
    

    How to find out line-endings in a text file?

    You can use vim -b filename to edit a file in binary mode, which will show ^M characters for carriage return and a new line is indicative of LF being present, indicating Windows CRLF line endings. By LF I mean \n and by CR I mean \r. Note that when you use the -b option the file will always be edited in UNIX mode by default as indicated by [unix] in the status line, meaning that if you add new lines they will end with LF, not CRLF. If you use normal vim without -b on a file with CRLF line endings, you should see [dos] shown in the status line and inserted lines will have CRLF as end of line. The vim documentation for fileformats setting explains the complexities.

    Also, I don't have enough points to comment on the Notepad++ answer, but if you use Notepad++ on Windows, use the View / Show Symbol / Show End of Line menu to display CR and LF. In this case LF is shown whereas for vim the LF is indicated by a new line.

    Identify duplicate values in a list in Python

    I tried below code to find duplicate values from list

    1) create a set of duplicate list

    2) Iterated through set by looking in duplicate list.

    glist=[1, 2, 3, "one", 5, 6, 1, "one"]
    x=set(glist)
    dup=[]
    for c in x:
        if(glist.count(c)>1):
            dup.append(c)
    print(dup)
    

    OUTPUT

    [1, 'one']

    Now get the all index for duplicate element

    glist=[1, 2, 3, "one", 5, 6, 1, "one"]
    x=set(glist)
    dup=[]
    for c in x:
        if(glist.count(c)>1):
            indices = [i for i, x in enumerate(glist) if x == c]
            dup.append((c,indices))
    print(dup)
    

    OUTPUT

    [(1, [0, 6]), ('one', [3, 7])]

    Hope this helps someone

    Regular expressions inside SQL Server

    SQL Wildcards are enough for this purpose. Follow this link: http://www.w3schools.com/SQL/sql_wildcards.asp

    you need to use a query like this:

    select * from mytable where msisdn like '%7%'
    

    or

    select * from mytable where msisdn like '56655%'
    

    How to make a JTable non-editable

    You can use a TableModel.

    Define a class like this:

    public class MyModel extends AbstractTableModel{
        //not necessary
    }
    

    actually isCellEditable() is false by default so you may omit it. (see: http://docs.oracle.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html)

    Then use the setModel() method of your JTable.

    JTable myTable = new JTable();
    myTable.setModel(new MyModel());
    

    How to compile without warnings being treated as errors?

    Thanks for all the helpful suggestions. I finally made sure that there are no warnings in my code, but again was getting this warning from sqlite3:

    Assuming signed overflow does not occur when assuming that (X - c) <= X is always true
    

    which I fixed by adding the following CFLAG:

    -fno-strict-overflow
    

    How to merge two json string in Python?

    You can load both json strings into Python Dictionaries and then combine. This will only work if there are unique keys in each json string.

    import json
    
    a = json.loads(jsonStringA)
    b = json.loads(jsonStringB)
    c = dict(a.items() + b.items())
    # or c =  dict(a, **b)
    

    How to create a file name with the current date & time in Python?

    This prints in an easy to read format -

    import datetime
    
    time_now  = datetime.datetime.now().strftime('%m_%d_%Y_%H_%M_%S') 
    
    print(time_now)
    

    Output: 02_03_2021_22_44_50

    RegEx for valid international mobile phone number

    Even if you write a regular expression that matches exactly the subset "valid phone numbers" out of strings, there is no way to guarantee (by way of a regular expression) that they are valid mobile phone numbers. In several countries, mobile phone numbers are indistinguishable from landline phone numbers without at least a number plan lookup, and in some cases, even that won't help. For example, in Sweden, lots of people have "ported" their regular, landline-like phone number to their mobile phone. It's still the same number as they had before, but now it goes to a mobile phone instead of a landline.

    Since valid phone numbers consist only of digits, I doubt that rolling your own would risk missing some obscure case of phone number at least. If you want to have better certainty, write a generator that takes a list of all valid country codes, and requires one of them at the beginning of the phone number to be matched by the generated regular expression.

    Temporary table in SQL server causing ' There is already an object named' error

    You are dropping it, then creating it, then trying to create it again by using SELECT INTO. Change to:

    DROP TABLE #TMPGUARDIAN
    CREATE TABLE #TMPGUARDIAN(
    LAST_NAME NVARCHAR(30),
    FRST_NAME NVARCHAR(30))  
    
    INSERT INTO #TMPGUARDIAN 
    SELECT LAST_NAME,FRST_NAME  
    FROM TBL_PEOPLE
    

    In MS SQL Server you can create a table without a CREATE TABLE statement by using SELECT INTO

    Escaping quotation marks in PHP

    You can use the PHP function addslashes() to any string to make it compatible

    maven error: package org.junit does not exist

    if you are using Eclipse watch your POM dependencies and your Eclipse buildpath dependency on junit

    if you select use Junit4 eclipse create TestCase using org.junit package but your POM use by default Junit3 (junit.framework package) that is the cause, like this picture:

    see JUNIT conflict

    Just update your Junit dependency in your POM file to Junit4 or your Eclipse BuildPath to Junit3

    jQuery keypress() event not firing?

    e.which doesn't work in IE try e.keyCode, also you probably want to use keydown() instead of keypress() if you are targeting IE.

    See http://unixpapa.com/js/key.html for more information.

    How to install a specific version of package using Composer?

    As @alucic mentioned, use:

    composer require vendor/package:version
    

    or you can use:

    composer update vendor/package:version
    

    You should probably review this StackOverflow post about differences between composer install and composer update.

    Related to question about version numbers, you can review Composer documentation on versions, but here in short:

    • Tilde Version Range (~) - ~1.2.3 is equivalent to >=1.2.3 <1.3.0
    • Caret Version Range (^) - ^1.2.3 is equivalent to >=1.2.3 <2.0.0

    So, with Tilde you will get automatic updates of patches but minor and major versions will not be updated. However, if you use Caret you will get patches and minor versions, but you will not get major (breaking changes) versions.

    Tilde Version is considered a "safer" approach, but if you are using reliable dependencies (well-maintained libraries) you should not have any problems with Caret Version (because minor changes should not be breaking changes.

    Remove a specific string from an array of string

    Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.

    vue.js 'document.getElementById' shorthand

    Try not to do DOM manipulation by referring the DOM directly, it will have lot of performance issue, also event handling becomes more tricky when we try to access DOM directly, instead use data and directives to manipulate the DOM.

    This will give you more control over the manipulation, also you will be able to manage functionalities in the modular format.

    Device not detected in Eclipse when connected with USB cable

    One possible reason is to check Android SDK Manager and install Google USB Driver in Extras folder if you have not installed it.

    Following the steps here: http://developer.android.com/sdk/oem-usb.html#InstallingDriver allowed Eclipse to display the device.

    Why do Twitter Bootstrap tables always have 100% width?

    Bootstrap 3:

    Why fight it? Why not simply control your table width using the bootstrap grid?

    <div class="row">
        <div class="col-sm-6">
            <table></table>
        </div>
    </div>
    

    This will create a table that is half (6 out of 12) of the width of the containing element.

    I sometimes use inline styles as per the other answers, but it is discouraged.

    Bootstrap 4:

    Bootstrap 4 has some nice helper classes for width like w-25, w-50, w-75, w-100, and w-auto. This will make the table 50% width:

    <table class="w-50"></table>
    

    Here's the doc: https://getbootstrap.com/docs/4.0/utilities/sizing/

    How to add the text "ON" and "OFF" to toggle button

    You could do it like this:

    _x000D_
    _x000D_
    .switch {
      position: relative;
      display: inline-block;
      width: 90px;
      height: 34px;
    }
    
    .switch input {display:none;}
    
    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #ca2222;
      -webkit-transition: .4s;
      transition: .4s;
    }
    
    .slider:before {
      position: absolute;
      content: "";
      height: 26px;
      width: 26px;
      left: 4px;
      bottom: 4px;
      background-color: white;
      -webkit-transition: .4s;
      transition: .4s;
    }
    
    input:checked + .slider {
      background-color: #2ab934;
    }
    
    input:focus + .slider {
      box-shadow: 0 0 1px #2196F3;
    }
    
    input:checked + .slider:before {
      -webkit-transform: translateX(55px);
      -ms-transform: translateX(55px);
      transform: translateX(55px);
    }
    
    /*------ ADDED CSS ---------*/
    .on
    {
      display: none;
    }
    
    .on, .off
    {
      color: white;
      position: absolute;
      transform: translate(-50%,-50%);
      top: 50%;
      left: 50%;
      font-size: 10px;
      font-family: Verdana, sans-serif;
    }
    
    input:checked+ .slider .on
    {display: block;}
    
    input:checked + .slider .off
    {display: none;}
    
    /*--------- END --------*/
    
    /* Rounded sliders */
    .slider.round {
      border-radius: 34px;
    }
    
    .slider.round:before {
      border-radius: 50%;}
    _x000D_
    <label class="switch">
     <input type="checkbox" id="togBtn">
     <div class="slider round">
      <!--ADDED HTML -->
      <span class="on">ON</span>
      <span class="off">OFF</span>
      <!--END-->
     </div>
    </label>
    _x000D_
    _x000D_
    _x000D_

    Or pure CSS:

    _x000D_
    _x000D_
    .switch {
      position: relative;
      display: inline-block;
      width: 90px;
      height: 34px;
    }
    
    .switch input {display:none;}
    
    .slider {
      position: absolute;
      cursor: pointer;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      background-color: #ca2222;
      -webkit-transition: .4s;
      transition: .4s;
       border-radius: 34px;
    }
    
    .slider:before {
      position: absolute;
      content: "";
      height: 26px;
      width: 26px;
      left: 4px;
      bottom: 4px;
      background-color: white;
      -webkit-transition: .4s;
      transition: .4s;
      border-radius: 50%;
    }
    
    input:checked + .slider {
      background-color: #2ab934;
    }
    
    input:focus + .slider {
      box-shadow: 0 0 1px #2196F3;
    }
    
    input:checked + .slider:before {
      -webkit-transform: translateX(26px);
      -ms-transform: translateX(26px);
      transform: translateX(55px);
    }
    
    /*------ ADDED CSS ---------*/
    .slider:after
    {
     content:'OFF';
     color: white;
     display: block;
     position: absolute;
     transform: translate(-50%,-50%);
     top: 50%;
     left: 50%;
     font-size: 10px;
     font-family: Verdana, sans-serif;
    }
    
    input:checked + .slider:after
    {  
      content:'ON';
    }
    
    /*--------- END --------*/
    _x000D_
    <label class="switch">
    <input type="checkbox" id="togBtn">
    <div class="slider round"></div>
    </label>
    _x000D_
    _x000D_
    _x000D_

    Java word count program

    public static void main (String[] args) {
    
         System.out.println("Simple Java Word Count Program");
    
         String str1 = "Today is Holdiay Day";
    
         String[] wordArray = str1.trim().split("\\s+");
         int wordCount = wordArray.length;
    
         System.out.println("Word count is = " + wordCount);
    }
    

    The ideas is to split the string into words on any whitespace character occurring any number of times. The split function of the String class returns an array containing the words as its elements. Printing the length of the array would yield the number of words in the string.

    How to install the Raspberry Pi cross compiler on my Linux host machine?

    I couldn't get the compiler (x64 version) to use the sysroot until I added SET(CMAKE_SYSROOT $ENV{HOME}/raspberrypi/rootfs) to pi.cmake.

    How to chain scope queries with OR instead of AND?

    Update for Rails4

    requires no 3rd party gems

    a = Person.where(name: "John") # or any scope 
    b = Person.where(lastname: "Smith") # or any scope 
    Person.where([a, b].map{|s| s.arel.constraints.reduce(:and) }.reduce(:or))\
      .tap {|sc| sc.bind_values = [a, b].map(&:bind_values) }
    

    Old answer

    requires no 3rd party gems

    Person.where(
        Person.where(:name => "John").where(:lastname => "Smith")
          .where_values.reduce(:or)
    )
    

    What are native methods in Java and where should they be used?

    The method is implemented in "native" code. That is, code that does not run in the JVM. It's typically written in C or C++.

    Native methods are usually used to interface with system calls or libraries written in other programming languages.

    Java: recommended solution for deep cloning/copying an instance

    For deep cloning (clones the entire object hierarchy):

    • commons-lang SerializationUtils - using serialization - if all classes are in your control and you can force implementing Serializable.

    • Java Deep Cloning Library - using reflection - in cases when the classes or the objects you want to clone are out of your control (a 3rd party library) and you can't make them implement Serializable, or in cases you don't want to implement Serializable.

    For shallow cloning (clones only the first level properties):

    I deliberately omitted the "do-it-yourself" option - the API's above provide a good control over what to and what not to clone (for example using transient, or String[] ignoreProperties), so reinventing the wheel isn't preferred.

    Can't find bundle for base name /Bundle, locale en_US

    I use Eclipse (without Maven) so I place the .properties file in src folder that also contains the java source code, in order to have the .properties file in the classes folder after building the project. It works fine. Take a look at this post: https://www.mkyong.com/jsf2/cant-find-bundle-for-base-name-xxx-locale-en_us/

    Hope this help you.

    How to bring back "Browser mode" in IE11?

    Microsoft has a tool just for this purpose: Microsoft Expression Web. There's a free version with a bunch of FrontPage/Dreamweaver-like garbage that nobody wants. What's important is that it has a great browser testing feature. I'm running Windows 8.1 Pro (final release, not preview) with Internet Explorer 11. I get these local browsers:

    • Internet Explorer 6
    • Internet Explorer 7
    • Internet Explorer 11 /!\ Unsupported Version (can't use it; big whoop, I have the browser)

    Then I get a Remote Browsers (Beta) option. I'm supposed to sign up with a valid e-mail, but there's an error communicating with the server. Oh well.

    Firefox used to be supported, but I don't see it now. Might be hiding.

    I can compare side-by-side between browser versions. I can also compare with an image, or apparently, a PSD file (no idea how well that works). InDesign would be nice, but that's probably asking for too much.

    I have the full version of Expression partially installed as well due to Visual Studio Ultimate being on the same computer, so I'd appreciate someone confirming in a comment that my free installation isn't automatically upgrading.

    Update: Looks like the online service was discontinued, but local browsers are still supported. You can also download just SuperPreview, without the editor garbage. If you want the full IDE, the latest version is Microsoft Expression Web 4 (Free Version). Here's the official list of supported browsers. IE6 seems to give an error on Windows 8.1, but IE7 works.

    Update 2014-12-09: Microsoft has pretty much given up on this. Don't expect it to work well.

    Conversion failed when converting date and/or time from character string in SQL SERVER 2008

    If you're trying to insert in to last_accessed_on, which is a DateTime2, then your issue is with the fact that you are converting it to a varchar in a format that SQL doesn't understand.

    If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:

    UPDATE  student_queues 
    SET  Deleted=0, 
         last_accessed_by='raja', 
         last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
    WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
    

    Or if you want to use CAST, replace with:

    CAST('2014-07-23 09:37:00.000' AS datetime2)
    

    This is using the SQL ISO Date Format.

    Want to move a particular div to right

    You can use float on that particular div, e.g.

    <div style="float:right;">
    

    Float the div you want more space to have to the left as well:

    <div style="float:left;">
    

    If all else fails give the div on the right position:absolute and then move it as right as you want it to be.

    <div style="position:absolute; left:-500px; top:30px;"> 
    

    etc. Obviously put the style in a seperate stylesheet but this is just a quicker example.

    Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

    Steps to find the UDID from IPhone and IPad Without Using itunes

    1. Open below link in your iPhone or iPad : - http://get.udid.io/

    2. Click on the Button Green color - Tap to find UDID

    3. Get your UDID will Appear, Click on the right side top INSTALL button

    4 . UDID will appear Copy the UDID.

    pip or pip3 to install packages for Python 3?

    If you had python 2.x and then installed python3, your pip will be pointing to pip3. you can verify that by typing pip --version which would be the same as pip3 --version.

    On your system you have now pip, pip2 and pip3.

    If you want you can change pip to point to pip2 instead of pip3.

    Is there a macro to conditionally copy rows to another worksheet?

    Here's another solution that uses some of VBA's built in date functions and stores all the date data in an array for comparison, which may give better performance if you get a lot of data:

    Public Sub MoveData(MonthNum As Integer, FromSheet As Worksheet, ToSheet As Worksheet)
        Const DateCol = "A" 'column where dates are store
        Const DestCol = "A" 'destination column where dates are stored. We use this column to find the last populated row in ToSheet
        Const FirstRow = 2 'first row where date data is stored
        'Copy range of values to Dates array
        Dates = FromSheet.Range(DateCol & CStr(FirstRow) & ":" & DateCol & CStr(FromSheet.Range(DateCol & CStr(FromSheet.Rows.Count)).End(xlUp).Row)).Value
        Dim i As Integer
        For i = LBound(Dates) To UBound(Dates)
            If IsDate(Dates(i, 1)) Then
                If Month(CDate(Dates(i, 1))) = MonthNum Then
                    Dim CurrRow As Long
                    'get the current row number in the worksheet
                    CurrRow = FirstRow + i - 1
                    Dim DestRow As Long
                    'get the destination row
                    DestRow = ToSheet.Range(DestCol & CStr(ToSheet.Rows.Count)).End(xlUp).Row + 1
                    'copy row CurrRow in FromSheet to row DestRow in ToSheet
                    FromSheet.Range(CStr(CurrRow) & ":" & CStr(CurrRow)).Copy ToSheet.Range(DestCol & CStr(DestRow))
                End If
            End If
        Next i
    End Sub
    

    setSupportActionBar toolbar cannot be applied to (android.widget.Toolbar) error

    ToolBar's name can easily be changed using

    android:label="My Activity"
    

    in your Manifest File. I just going through Manifest & found

    android:label 
    

    Helps to change according to the specific activity, Hope you'll give it a try

    Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

    this is probably about you don't entered correct dependency version. you can select correct dependency from this:

    file>menu>project structure>app>dependencies>+>Library Dependency>select any thing you need > OK
    

    if cannot find your needs you should update your sdk from below way:

    tools>android>sdk manager>sdk update>select any thing you need>ok

    How do I upgrade to Python 3.6 with conda?

    Best method I found:

    source activate old_env
    conda env export > old_env.yml
    

    Then process it with something like this:

    with open('old_env.yml', 'r') as fin, open('new_env.yml', 'w') as fout:
        for line in fin:
            if 'py35' in line:  # replace by the version you want to supersede
                line = line[:line.rfind('=')] + '\n'
            fout.write(line)
    

    then edit manually the first (name: ...) and last line (prefix: ...) to reflect your new environment name and run:

    conda env create -f new_env.yml
    

    you might need to remove or change manually the version pin of a few packages for which which the pinned version from old_env is found incompatible or missing for the new python version.

    I wish there was a built-in, easier way...

    scp from Linux to Windows

    I know this is old but I was struggling with the same. I haven't found a way to change directories, but if you just want to work with the C drive, scp defaults to C. To scp from Ubuntu to Windows, I ended up having to use (notice the double back-slashes):

    scp /local/file/path [email protected]:Users\\Anshul\\Desktop

    Hope this helps someone.

    maxlength ignored for input type="number" in Chrome

    You can use the min and max attributes.

    The following code do the same:

    <input type="number" min="-999" max="9999"/>
    

    How to open a txt file and read numbers in Java

    Good news in Java 8 we can do it in one line:

    List<Integer> ints = Files.lines(Paths.get(fileName))
                              .map(Integer::parseInt)
                              .collect(Collectors.toList());
    

    how to include glyphicons in bootstrap 3

    I think your particular problem isn't how to use Glyphicons but understanding how Bootstrap files work together.

    Bootstrap requires a specific file structure to work. I see from your code you have this:

    <link href="bootstrap.css" rel="stylesheet" media="screen">
    

    Your Bootstrap.css is being loaded from the same location as your page, this would create a problem if you didn't adjust your file structure.

    But first, let me recommend you setup your folder structure like so:

    /css      <-- Bootstrap.css here
    /fonts    <-- Bootstrap fonts here
    /img
    /js       <-- Bootstrap JavaScript here
    index.html
    

    If you notice, this is also how Bootstrap structures its files in its download ZIP.

    You then include your Bootstrap file like so:

    <link href="css/bootstrap.css" rel="stylesheet" media="screen">
    or
    <link href="./css/bootstrap.css" rel="stylesheet" media="screen">
    or
    <link href="/css/bootstrap.css" rel="stylesheet" media="screen">
    

    Depending on your server structure or what you're going for.

    The first and second are relative to your file's current directory. The second one is just more explicit by saying "here" (./) first then css folder (/css).

    The third is good if you're running a web server, and you can just use relative to root notation as the leading "/" will be always start at the root folder.

    So, why do this?

    Bootstrap.css has this specific line for Glyphfonts:

    @font-face {
        font-family: 'Glyphicons Halflings';
        src: url('../fonts/glyphicons-halflings-regular.eot');
        src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
    }
    

    What you can see is that that Glyphfonts are loaded by going up one directory ../ and then looking for a folder called /fonts and THEN loading the font file.

    The URL address is relative to the location of the CSS file. So, if your CSS file is at the same location like this:

    /fonts
    Bootstrap.css
    index.html
    

    The CSS file is going one level deeper than looking for a /fonts folder.

    So, let's say the actual location of these files are:

    C:\www\fonts
    C:\www\Boostrap.css
    C:\www\index.html
    

    The CSS file would technically be looking for a folder at:

    C:\fonts
    

    but your folder is actually in:

    C:\www\fonts
    

    So see if that helps. You don't have to do anything 'special' to load Bootstrap Glyphicons, except make sure your folder structure is set up appropriately.

    When you get that fixed, your HTML should simply be:

    <span class="glyphicon glyphicon-comment"></span>
    

    Note, you need both classes. The first class glyphicon sets up the basic styles while glyphicon-comment sets the specific image.

    Serialize JavaScript object into JSON string

    This might be useful. http://nanodeath.github.com/HydrateJS/ https://github.com/nanodeath/HydrateJS

    Use hydrate.stringify to serialize the object and hydrate.parse to deserialize.

    Should Gemfile.lock be included in .gitignore?

    Assuming you're not writing a rubygem, Gemfile.lock should be in your repository. It's used as a snapshot of all your required gems and their dependencies. This way bundler doesn't have to recalculate all the gem dependencies each time you deploy, etc.

    From cowboycoded's comment below:

    If you are working on a gem, then DO NOT check in your Gemfile.lock. If you are working on a Rails app, then DO check in your Gemfile.lock.

    Here's a nice article explaining what the lock file is.

    Java: how to initialize String[]?

    String[] string=new String[60];
    System.out.println(string.length);
    

    it is initialization and getting the STRING LENGTH code in very simple way for beginners

    Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

    When an array is passed to a method or function in PHP, it is passed by value unless you explicitly pass it by reference, like so:

    function test(&$array) {
        $array['new'] = 'hey';
    }
    
    $a = $array(1,2,3);
    // prints [0=>1,1=>2,2=>3]
    var_dump($a);
    test($a);
    // prints [0=>1,1=>2,2=>3,'new'=>'hey']
    var_dump($a);
    

    In your second question, $b is not a reference to $a, but a copy of $a.

    Much like the first example, you can reference $a by doing the following:

    $a = array(1,2,3);
    $b = &$a;
    // prints [0=>1,1=>2,2=>3]
    var_dump($b);
    $b['new'] = 'hey';
    // prints [0=>1,1=>2,2=>3,'new'=>'hey']
    var_dump($a);
    

    Set textbox to readonly and background color to grey in jquery

    there are 2 solutions:

    visit this jsfiddle

    in your css you can add this:
         .input-disabled{background-color:#EBEBE4;border:1px solid #ABADB3;padding:2px 1px;}
    
    in your js do something like this:
         $('#test').attr('readonly', true);
         $('#test').addClass('input-disabled');
    

    Hope this help.

    Another way is using hidden input field as mentioned by some of the comments. However bear in mind that, in the backend code, you need to make sure you validate this newly hidden input at correct scenario. Hence I'm not recommend this way as it will create more bugs if its not handle properly.

    How can I get a character in a string by index?

    string s = "hello";
    char c = s[1];
    // now c == 'e'
    

    See also Substring, to return more than one character.

    Count number of vector values in range with R

    There are also the %<% and %<=% comparison operators in the TeachingDemos package which allow you to do this like:

    sum( 2 %<% x %<% 5 )
    sum( 2 %<=% x %<=% 5 )
    

    which gives the same results as:

    sum( 2 < x & x < 5 )
    sum( 2 <= x & x <= 5 )
    

    Which is better is probably more a matter of personal preference.

    How do I make my string comparison case insensitive?

    In the default Java API you have:

    String.CASE_INSENSITIVE_ORDER
    

    So you do not need to rewrite a comparator if you were to use strings with Sorted data structures.

    String s = "some text here";
    s.equalsIgnoreCase("Some text here");
    

    Is what you want for pure equality checks in your own code.

    Just to further informations about anything pertaining to equality of Strings in Java. The hashCode() function of the java.lang.String class "is case sensitive":

    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;
    
            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }
    

    So if you want to use an Hashtable/HashMap with Strings as keys, and have keys like "SomeKey", "SOMEKEY" and "somekey" be seen as equal, then you will have to wrap your string in another class (you cannot extend String since it is a final class). For example :

    private static class HashWrap {
        private final String value;
        private final int hash;
    
        public String get() {
            return value;
        }
    
        private HashWrap(String value) {
            this.value = value;
            String lc = value.toLowerCase();
            this.hash = lc.hashCode();
        }
    
        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o instanceof HashWrap) {
                HashWrap that = (HashWrap) o;
                return value.equalsIgnoreCase(that.value);
            } else {
                return false;
            }
        }
    
        @Override
        public int hashCode() {
            return this.hash;
        }
    }
    

    and then use it as such:

    HashMap<HashWrap, Object> map = new HashMap<HashWrap, Object>();
    

    Twitter - share button, but with image

    Look into twitter cards.

    The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook sharing.

    Example:

    <meta name="twitter:card" content="summary_large_image">
    <meta name="twitter:site" content="@site_username">
    <meta name="twitter:title" content="Top 10 Things Ever">
    <meta name="twitter:description" content="Up than 200 characters.">
    <meta name="twitter:creator" content="@creator_username">
    <meta name="twitter:image" content="http://placekitten.com/250/250">
    <meta name="twitter:domain" content="YourDomain.com">
    

    PowerShell equivalent to grep -f

    I had the same issue trying to find text in files with powershell. I used the following - to stay as close to the Linux environment as possible.

    Hopefully this helps somebody:

    PowerShell:

    PS) new-alias grep findstr
    PS) ls -r *.txt | cat | grep "some random string"
    

    Explanation:

    ls       - lists all files
    -r       - recursively (in all files and folders and subfolders)
    *.txt    - only .txt files
    |        - pipe the (ls) results to next command (cat)
    cat      - show contents of files comming from (ls)
    |        - pipe the (cat) results to next command (grep)
    grep     - search contents from (cat) for "some random string" (alias to findstr)
    

    Yes, this works as well:

    PS) ls -r *.txt | cat | findstr "some random string"
    

    Run task only if host does not belong to a group

    Here's another way to do this:

    - name: my command
      command: echo stuff
      when: "'groupname' not in group_names"
    

    group_names is a magic variable as documented here: https://docs.ansible.com/ansible/latest/user_guide/playbooks_variables.html#accessing-information-about-other-hosts-with-magic-variables :

    group_names is a list (array) of all the groups the current host is in.

    Changing the child element's CSS when the parent is hovered

    .parent:hover > .child {
        /*do anything with this child*/
    }
    

    How to set image width to be 100% and height to be auto in react native?

    "resizeMode" isn't style property. Should move to Image component's Props like below code.

    const win = Dimensions.get('window');
    
    const styles = StyleSheet.create({
        image: {
            flex: 1,
            alignSelf: 'stretch',
            width: win.width,
            height: win.height,
        }
    });
    
    ...
        <Image 
           style={styles.image}
           resizeMode={'contain'}   /* <= changed  */
           source={require('../../../images/collection-imag2.png')} /> 
    ...
    

    Image's height won't become automatically because Image component is required both width and height in style props. So you can calculate by using getSize() method for remote images like this answer and you can also calculate image ratio for static images like this answer.

    There are a lot of useful open source libraries -

    How to add image in Flutter

    How to include images in your app

    1. Create an assets/images folder

    • This should be located in the root of your project, in the same folder as your pubspec.yaml file.
    • In Android Studio you can right click in the Project view
    • You don't have to call it assets or images. You don't even need to make images a subfolder. Whatever name you use, though, is what you will regester in the pubspec.yaml file.

    2. Add your image to the new folder

    • You can just copy your image into assets/images. The relative path of lake.jpg, for example, would be assets/images/lake.jpg.

    3. Register the assets folder in pubspec.yaml

    • Open the pubspec.yaml file that is in the root of your project.

    • Add an assets subsection to the flutter section like this:

        flutter:
          assets:
            - assets/images/lake.jpg
      
    • If you have multiple images that you want to include then you can leave off the file name and just use the directory name (include the final /):

        flutter:
          assets:
            - assets/images/
      

    4. Use the image in code

    • Get the asset in an Image widget with Image.asset('assets/images/lake.jpg').

    • The entire main.dart file is here:

        import 'package:flutter/material.dart';
      
        void main() => runApp(MyApp());
      
        class MyApp extends StatelessWidget {
          @override
          Widget build(BuildContext context) {
            return MaterialApp(
              home: Scaffold(
                appBar: AppBar(
                  title: Text("Image from assets"),
                ),
                body: Image.asset('assets/images/lake.jpg'), //   <--- image
              ),
            );
          }
        }
      

    5. Restart your app

    When making changes to pubspec.yaml I find that I often need to completely stop my app and restart it again, especially when adding assets. Otherwise I get a crash.

    Running the app now you should have something like this:

    enter image description here

    Further reading

    • See the documentation for how to do things like provide alternate images for different densities.

    Videos

    The first video here goes into a lot of detail about how to include images in your app. The second video covers more about how to adjust how they look.

    How do I add multiple "NOT LIKE '%?%' in the WHERE clause of sqlite3?

    You missed the second statement: 1) NOT LIKE A, AND 2) NOT LIKE B

    SELECT word FROM table WHERE word NOT LIKE '%a%' AND word NOT LIKE '%b%'
    

    How to undo last commit

    Warning: Don't do this if you've already pushed

    You want to do:

    git reset HEAD~
    

    If you don't want the changes and blow everything away:

    git reset --hard HEAD~
    

    range() for floats

    This can be done with numpy.arange(start, stop, stepsize)

    import numpy as np
    
    np.arange(0.5,5,1.5)
    >> [0.5, 2.0, 3.5, 5.0]
    
    # OBS you will sometimes see stuff like this happening, 
    # so you need to decide whether that's not an issue for you, or how you are going to catch it.
    >> [0.50000001, 2.0, 3.5, 5.0]
    

    Note 1: From the discussion in the comment section here, "never use numpy.arange() (the numpy documentation itself recommends against it). Use numpy.linspace as recommended by wim, or one of the other suggestions in this answer"

    Note 2: I have read the discussion in a few comments here, but after coming back to this question for the third time now, I feel this information should be placed in a more readable position.

    How to get the stream key for twitch.tv

    This may be an old thread but I came across it and figured that I would give a final answer.

    The twitch api is json based and to recieve your stream key you need to authorize your app for use with the api. You do so under the connections tab within your profile on twitch.tv itself.. Down the bottom of said tab there is "register your app" or something similar. Register it and you'll get a client-id header for your get requests.

    Now you need to attach your Oauthv2 key to your headers or as a param during the query to the following get request.

    curl -H 'Accept: application/vnd.twitchtv.v3+json' -H 'Authorization: OAuth ' \ -X GET https://api.twitch.tv/kraken/channel

    documentataion here

    As you can see in the documentation above, if you've done these two things, your stream key will be made available to you.

    As I said - Sorry for the bump but some people do find it hard to read the twitch* api.

    Hope that helps somebody in the future.

    makefile execute another target

    Actually you are right: it runs another instance of make. A possible solution would be:

    .PHONY : clearscr fresh clean all
    
    all :
        compile executable
    
    clean :
        rm -f *.o $(EXEC)
    
    fresh : clean clearscr all
    
    clearscr:
        clear
    

    By calling make fresh you get first the clean target, then the clearscreen which runs clear and finally all which does the job.

    EDIT Aug 4

    What happens in the case of parallel builds with make’s -j option? There's a way of fixing the order. From the make manual, section 4.2:

    Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites

    The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).

    Hence the makefile becomes

    .PHONY : clearscr fresh clean all
    
    all :
        compile executable
    
    clean :
        rm -f *.o $(EXEC)
    
    fresh : | clean clearscr all
    
    clearscr:
        clear
    

    EDIT Dec 5

    It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.

    log_success = (echo "\x1B[32m>> $1\x1B[39m")
    log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)
    
    install:
      @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
      command1  # this line will be a subshell
      command2  # this line will be another subshell
      @command3  # Use `@` to hide the command line
      $(call log_error, "It works, yey!")
    
    uninstall:
      @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
      ....
      $(call log_error, "Nuked!")
    

    Navigation drawer: How do I set the selected item at startup?

    you can do this, nav_view.getMenu().findItem(R.id.menutem).setChecked(true)