Programs & Examples On #Random sample

Random sampling is the algorithmic generation of random sequences with specified properties.

Select a random sample of results from a query result

The SAMPLE clause will give you a random sample percentage of all rows in a table.

For example, here we obtain 25% of the rows:

SELECT * FROM emp SAMPLE(25)

The following SQL (using one of the analytical functions) will give you a random sample of a specific number of each occurrence of a particular value (similar to a GROUP BY) in a table.

Here we sample 10 of each:

SELECT * FROM (
SELECT job, sal, ROW_NUMBER()
OVER (
PARTITION BY job ORDER BY job
) SampleCount FROM emp
)
WHERE SampleCount <= 10

Test if executable exists in Python?

Just remember to specify the file extension on windows. Otherwise, you have to write a much complicated is_exe for windows using PATHEXT environment variable. You may just want to use FindPath.

OTOH, why are you even bothering to search for the executable? The operating system will do it for you as part of popen call & will raise an exception if the executable is not found. All you need to do is catch the correct exception for given OS. Note that on Windows, subprocess.Popen(exe, shell=True) will fail silently if exe is not found.


Incorporating PATHEXT into the above implementation of which (in Jay's answer):

def which(program):
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK) and os.path.isfile(fpath)

    def ext_candidates(fpath):
        yield fpath
        for ext in os.environ.get("PATHEXT", "").split(os.pathsep):
            yield fpath + ext

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            for candidate in ext_candidates(exe_file):
                if is_exe(candidate):
                    return candidate

    return None

Exporting PDF with jspdf not rendering CSS

As I know jsPDF is not working with CSS and the same issue I was facing.

To solve this issue, I used Html2Canvas. Just Add HTML2Canvas JS and then use pdf.addHTML() instead of pdf.fromHTML().

Here's my code (no other code):

 var pdf = new jsPDF('p', 'pt', 'letter');
 pdf.addHTML($('#ElementYouWantToConvertToPdf')[0], function () {
     pdf.save('Test.pdf');
 });

Best of Luck!

Edit: Refer to this line in case you didn't find .addHTML()

How do I install g++ for Fedora?

Just make a sample 'Hello World' Program and try to compile it using "g++ sam.cpp" in terminal, and it will ask you if you wish to download the g++ package. Press y to install.

How to pass an array into a SQL Server stored procedure

It took me a long time to figure this out, so in case anyone needs it...

This is based on the SQL 2005 method in Aaron's answer, and using his SplitInts function (I just removed the delim param since I'll always use commas). I'm using SQL 2008 but I wanted something that works with typed datasets (XSD, TableAdapters) and I know string params work with those.

I was trying to get his function to work in a "where in (1,2,3)" type clause, and having no luck the straight-forward way. So I created a temp table first, and then did an inner join instead of the "where in". Here is my example usage, in my case I wanted to get a list of recipes that don't contain certain ingredients:

CREATE PROCEDURE dbo.SOExample1
    (
    @excludeIngredientsString varchar(MAX) = ''
    )
AS
    /* Convert string to table of ints */
    DECLARE @excludeIngredients TABLE (ID int)
    insert into @excludeIngredients
    select ID = Item from dbo.SplitInts(@excludeIngredientsString)

    /* Select recipies that don't contain any ingredients in our excluded table */
   SELECT        r.Name, r.Slug
FROM            Recipes AS r LEFT OUTER JOIN
                         RecipeIngredients as ri inner join
                         @excludeIngredients as ei on ri.IngredientID = ei.ID
                         ON r.ID = ri.RecipeID
WHERE        (ri.RecipeID IS NULL)

C++ wait for user input

There is no "standard" library function to do this. The standard (perhaps surprisingly) does not actually recognise the concept of a "keyboard", albeit it does have a standard for "console input".

There are various ways to achieve it on different operating systems (see herohuyongtao's solution) but it is not portable across all platforms that support keyboard input.

Remember that C++ (and C) are devised to be languages that can run on embedded systems that do not have keyboards. (Having said that, an embedded system might not have various other devices that the standard library supports).

This matter has been debated for a long time.

In PHP how can you clear a WSDL cache?

if you already deployed the code or can't change any configuration, you could remove all temp files from wsdl:

rm /tmp/wsdl-*

align images side by side in html

Not really sure what you meant by "the caption in the middle", but here's one solution to get your images appear side by side, using the excellent display:inline-block :

<!DOCTYPE html>
<html>
<head>
  <meta charset=utf-8 />
  <title></title>
  <style>
    div.container {
      display:inline-block;
    }

    p {
      text-align:center;
    }
  </style>
</head>
<body>
  <div class="container">
    <img src="http://placehold.it/350x150" height="200" width="200" />
    <p>This is image 1</p>
  </div>
  <div class="container">
    <img class="middle-img" src="http://placehold.it/350x150"/ height="200" width="200" />
    <p>This is image 2</p>
  </div>
  <div class="container">
    <img src="http://placehold.it/350x150" height="200" width="200" />
    <p>This is image 3</p>
  </div>
</div>
</body>
</html>

Java Generics With a Class & an Interface - Together

Actually, you can do what you want. If you want to provide multiple interfaces or a class plus interfaces, you have to have your wildcard look something like this:

<T extends ClassA & InterfaceB>

See the Generics Tutorial at sun.com, specifically the Bounded Type Parameters section, at the bottom of the page. You can actually list more than one interface if you wish, using & InterfaceName for each one that you need.

This can get arbitrarily complicated. To demonstrate, see the JavaDoc declaration of Collections#max, which (wrapped onto two lines) is:

public static <T extends Object & Comparable<? super T>> T
                                           max(Collection<? extends T> coll)

why so complicated? As said in the Java Generics FAQ: To preserve binary compatibility.

It looks like this doesn't work for variable declaration, but it does work when putting a generic boundary on a class. Thus, to do what you want, you may have to jump through a few hoops. But you can do it. You can do something like this, putting a generic boundary on your class and then:

class classB { }
interface interfaceC { }

public class MyClass<T extends classB & interfaceC> {
    Class<T> variable;
}

to get variable that has the restriction that you want. For more information and examples, check out page 3 of Generics in Java 5.0. Note, in <T extends B & C>, the class name must come first, and interfaces follow. And of course you can only list a single class.

CSS3 Transform Skew One Side

Try this:

To unskew the image use a nested div for the image and give it the opposite skew value. So if you had 20deg on the parent then you can give the nested (image) div a skew value of -20deg.

_x000D_
_x000D_
.container {_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#parallelogram {_x000D_
  width: 150px;_x000D_
  height: 100px;_x000D_
  margin: 0 0 0 -20px;_x000D_
  -webkit-transform: skew(20deg);_x000D_
  -moz-transform: skew(20deg);_x000D_
  -o-transform: skew(20deg);_x000D_
  background: red;_x000D_
  overflow: hidden;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.image {_x000D_
  background: url(http://placekitten.com/301/301);_x000D_
  position: absolute;_x000D_
  top: -30px;_x000D_
  left: -30px;_x000D_
  right: -30px;_x000D_
  bottom: -30px;_x000D_
  -webkit-transform: skew(-20deg);_x000D_
  -moz-transform: skew(-20deg);_x000D_
  -o-transform: skew(-20deg);_x000D_
}
_x000D_
<div class="container">_x000D_
  <div id="parallelogram">_x000D_
    <div class="image"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

The example:

http://jsfiddle.net/diegoh/mXLgF/1154/

SSL error SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

If you are using macOS sierra there is a update in PHP version. you need to have Entrust.net Certificate Authority (2048) file added to the PHP code. more info check accepted answer here Push Notification in PHP using PEM file

Trying to mock datetime.date.today(), but not working

The easiest way for me is doing this:

import datetime
from unittest.mock import Mock, patch

def test():
    datetime_mock = Mock(wraps=datetime.datetime)
    datetime_mock.now.return_value = datetime.datetime(1999, 1, 1)
    with patch('datetime.datetime', new=datetime_mock):
        assert datetime.datetime.now() == datetime.datetime(1999, 1, 1)

CAUTION for this solution: all functionality from datetime module from the target_module will stop working.

firestore: PERMISSION_DENIED: Missing or insufficient permissions

the problem is that you tried to read or write data to realtime database or firestore before the user has be authenticated. please try to check the scope of your code. hope it helped!

How to write a cron that will run a script every day at midnight?

Sometimes you'll need to specify PATH and GEM_PATH using crontab with rvm.

Like this:

# top of crontab file
PATH=/home/user_name/.rvm/gems/ruby-2.2.0/bin:/home/user_name/.rvm/gems/ruby-2.2.0@global/bin:/home/user_name/.rvm/rubies/ruby-2.2.$
GEM_PATH=/home/user_name/.rvm/gems/ruby-2.2.0:/home/user_name/.rvm/gems/ruby-2.2.0@global

# jobs
00 00 * * * ruby path/to/your/script.rb
00 */4 * * * ruby path/to/your/script2.rb
00 8,12,22 * * * ruby path/to/your/script3.rb

PHP: convert spaces in string into %20?

I believe that, if you need to use the %20 variant, you could perhaps use rawurlencode().

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

I just felt like I'll add my $0.2 to those 2 good answers. I had a case when I had to move the last column all the way to the top in a 3-column situation.

[A][B][C]

to

[C]

[A]

[B]

Boostrap's class .col-xx-push-Xdoes nothing else but pushes a column to the right with left: XX%; so all you have to do to push a column right is to add the number of pseudo columns going left.

In this case:

  • two columns (col-md-5 and col-md-3) are going left, each with the value of the one that is going right;

  • one(col-md-4) is going right by the sum of the first two going left (5+3=8);


<div class="row">
    <div class="col-md-4 col-md-push-8 ">
        C
    </div>
    <div class="col-md-5 col-md-pull-4">
        A
    </div>
    <div class="col-md-3 col-md-pull-4">
        B
    </div>
</div>

enter image description here

adding classpath in linux

Paths under linux are separated by colons (:), not semi-colons (;), as theatrus correctly used it in his example. I believe Java respects this convention.

Edit

Alternatively to what andy suggested, you may use the following form (which sets CLASSPATH for the duration of the command):

CLASSPATH=".:../somejar.jar:../mysql-connector-java-5.1.6-bin.jar" java -Xmx500m ...

whichever is more convenient to you.

How to Delete Session Cookie?

Deleting a jQuery cookie:

$(function() {
    var COOKIE_NAME = 'test_cookie';
    var options = { path: '/', expires: 10 };
    $.cookie(COOKIE_NAME, 'test', options); // sets the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns test
    $.cookie(COOKIE_NAME, null, options);   // deletes the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns null
});

calculate the mean for each column of a matrix in R

You can use 'apply' to run a function or the rows or columns of a matrix or numerical data frame:

cluster1 <- data.frame(a=1:5, b=11:15, c=21:25, d=31:35)

apply(cluster1,2,mean)  # applies function 'mean' to 2nd dimension (columns)

apply(cluster1,1,mean)  # applies function to 1st dimension (rows)

sapply(cluster1, mean)  # also takes mean of columns, treating data frame like list of vectors

Can I use an HTML input type "date" to collect only a year?

Add this code structure to your page code

<?php
echo '<label>Admission Year:</label><br><select name="admission_year" data-component="date">';
for($year=1900; $year<=date('Y'); $year++){
echo '<option value="'.$year.'">'.$year.'</option>';
}
?>

It works perfectly and can be reverse engineered

<?php
echo '<label>Admission Year:</label><br><select name="admission_year" data-component="date">';
for($year=date('Y'); $year>=1900; $year++){
echo '<option value="'.$year.'">'.$year.'</option>';
}
?>

With this you are good to go.

how to create a logfile in php?

You could use built-in function trigger_error() to trigger user errors/warnings/notices and set_error_handler() to handle them. Inside your error handler you might want to use error_log() or file_put_contents() to store all records on files. To have a single file for every day just use something like sprintf('%s.log', date('Y-m-d')) as filename. And now you should know where to start... :)

angular.min.js.map not found, what is it exactly?

As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.

You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the

/*
//@ sourceMappingURL=angular.min.js.map
*/

at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.

remote: repository not found fatal: not found

This answer is a bit late but I hope it helps someone out there all the same.

In my case, it was because the repository had been moved. I recloned the project and everything became alright afterwards. A better alternative would have been to re-initialize git.

I hope this helps.. Merry coding!

Using Laravel Homestead: 'no input file specified'

This happens because you need to configure your nginx server properly in order to serve you application. You can do this following this guide, starting in the topic Configure Nginx and the Web Root.

After properly configuring your symbolic link between your /etc/nginx/sites-available and /etc/nginx/sites-enabled you need to make sure your root variable is set to your application's folder path. Set your nginx root from

root /usr/share/nginx/html;

to

/home/vagrant/Projects/ProjectOne/public

Also, you have to place index.php before your html files so php is served before html. Change this

index index.html index.htm;

to this

index index.php index.html index.htm;

After finish your configuration restart your nginx server with

sudo service nginx restart

Your application should be served now.

How to append multiple items in one line in Python

You could also:

newlist += mylist[i:i+22]

Different class for the last element in ng-repeat

To elaborate on Paul's answer, this is the controller logic that coincides with the template code.

// HTML
<div class="row" ng-repeat="thing in things">
  <div class="well" ng-class="isLast($last)">
      <p>Data-driven {{thing.name}}</p>
  </div>
</div>

// CSS
.last { /* Desired Styles */}

// Controller
$scope.isLast = function(check) {
    var cssClass = check ? 'last' : null;
    return cssClass;
};

Its also worth noting that you really should avoid this solution if possible. By nature CSS can handle this, making a JS-based solution is unnecessary and non-performant. Unfortunately if you need to support IE8> this solution won't work for you (see MDN support docs).

CSS-Only Solution

// Using the above example syntax
.row:last-of-type { /* Desired Style */ }

ES6 Map in Typescript

Add "target": "ESNEXT" property to the tsconfig.json file.

{
    "compilerOptions": {
        "target": "ESNEXT" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
    }
}

How to get a dependency tree for an artifact?

I know this post is quite old, but still, if anyone using IntelliJ any want to see dependency tree directly in IDE then they can install Maven Helper Plugin plugin.

Once installed open pom.xml and you would able to see Dependency Analyze tab like below. It also provides option to see dependency that is conflicted only and also as a tree structure.

enter image description here

Storing and retrieving datatable from session

Add a datatable into session:

DataTable Tissues = new DataTable();

Tissues = dal.returnTissues("TestID", "TestValue");// returnTissues("","") sample     function for adding values


Session.Add("Tissues", Tissues);

Retrive that datatable from session:

DataTable Tissues = Session["Tissues"] as DataTable

or

DataTable Tissues = (DataTable)Session["Tissues"];

Disable/enable an input with jQuery?

2018, without JQuery (ES6)

Disable all input:

[...document.querySelectorAll('input')].map(e => e.disabled = true);

Disable input with id="my-input"

document.getElementById('my-input').disabled = true;

The question is with JQuery, it's just FYI.

Single line if statement with 2 actions

userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";

should do the trick.

Changing default encoding of Python?

A) To control sys.getdefaultencoding() output:

python -c 'import sys; print(sys.getdefaultencoding())'

ascii

Then

echo "import sys; sys.setdefaultencoding('utf-16-be')" > sitecustomize.py

and

PYTHONPATH=".:$PYTHONPATH" python -c 'import sys; print(sys.getdefaultencoding())'

utf-16-be

You could put your sitecustomize.py higher in your PYTHONPATH.

Also you might like to try reload(sys).setdefaultencoding by @EOL

B) To control stdin.encoding and stdout.encoding you want to set PYTHONIOENCODING:

python -c 'import sys; print(sys.stdin.encoding, sys.stdout.encoding)'

ascii ascii

Then

PYTHONIOENCODING="utf-16-be" python -c 'import sys; 
print(sys.stdin.encoding, sys.stdout.encoding)'

utf-16-be utf-16-be

Finally: you can use A) or B) or both!

Pandas: Creating DataFrame from Series

Here is how to create a DataFrame where each series is a row.

For a single Series (resulting in a single-row DataFrame):

series = pd.Series([1,2], index=['a','b'])
df = pd.DataFrame([series])

For multiple series with identical indices:

cols = ['a','b']
list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)]
df = pd.DataFrame(list_of_series, columns=cols)

For multiple series with possibly different indices:

list_of_series = [pd.Series([1,2],index=['a','b']), pd.Series([3,4],index=['a','c'])]
df = pd.concat(list_of_series, axis=1).transpose()

To create a DataFrame where each series is a column, see the answers by others. Alternatively, one can create a DataFrame where each series is a row, as above, and then use df.transpose(). However, the latter approach is inefficient if the columns have different data types.

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

NOTE: This is an incorrect solution as @benlemasurier proved

Here is a way to copy a slice. I'm a bit late, but there is a simpler, and faster answer than @Dave's. This are the instructions generated from a code like @Dave's. These is the instructions generated by mine. As you can see there are far fewer instructions. What is does is it just does append(slice), which copies the slice. This code:

package main

import "fmt"

func main() {
    var foo = []int{1, 2, 3, 4, 5}
    fmt.Println("foo:", foo)
    var bar = append(foo)
    fmt.Println("bar:", bar)
    bar = append(bar, 6)
    fmt.Println("foo after:", foo)
    fmt.Println("bar after:", bar)
}

Outputs this:

foo: [1 2 3 4 5]
bar: [1 2 3 4 5]
foo after: [1 2 3 4 5]
bar after: [1 2 3 4 5 6]

How to check if an element exists in the xml using xpath?

take look at my example

<tocheading language="EN"> 
     <subj-group> 
         <subject>Editors Choice</subject> 
         <subject>creative common</subject> 
     </subj-group> 
</tocheading> 

now how to check if creative common is exist

tocheading/subj-group/subject/text() = 'creative common'

hope this help you

Getting the application's directory from a WPF application

You can also use the first argument of the command line arguments:

String exePath = System.Environment.GetCommandLineArgs()[0]

How to add multiple font files for the same font?

The solution seems to be to add multiple @font-face rules, for example:

@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans.ttf");
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Bold.ttf");
    font-weight: bold;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Oblique.ttf");
    font-style: italic, oblique;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic, oblique;
}

By the way, it would seem Google Chrome doesn't know about the format("ttf") argument, so you might want to skip that.

(This answer was correct for the CSS 2 specification. CSS3 only allows for one font-style rather than a comma-separated list.)

How to use conditional breakpoint in Eclipse?

Make a normal breakpoint on the doIt(tablist[i]); line

Right-click -> Properties

Check 'Conditional'

Enter tablist[i].equalsIgnoreCase("LEADDELEGATES")

UUID max character length

This is the perfect kind of field to define as CHAR 36, by the way, not VARCHAR 36, since each value will have the exact same length. And you'll use less storage space, since you don't need to store the data length for each value, just the value.

jQuery selector for inputs with square brackets in the name attribute

Just separate it with different quotes:

<input name="myName[1][data]" value="myValue">

JQuery:

var value = $('input[name="myName[1][data]"]').val();

Can't install any package with node npm

npm install <packagename> --registry http://registry.npmjs.org/

Try specifying the registry with the install command. Solved my problem.

R: Break for loop

Well, your code is not reproducible so we will never know for sure, but this is what help('break')says:

break breaks out of a for, while or repeat loop; control is transferred to the first statement outside the inner-most loop.

So yes, break only breaks the current loop. You can also see it in action with e.g.:

for (i in 1:10)
{
    for (j in 1:10)
    {
        for (k in 1:10)
        {
            cat(i," ",j," ",k,"\n")
            if (k ==5) break
        }   
    }
}

How to delete last item in list?

you should use this

del record[-1]

The problem with

record = record[:-1]

Is that it makes a copy of the list every time you remove an item, so isn't very efficient

How to open .dll files to see what is written inside?

Open .dll file with visual studio. Or resource editor.

How do I delete an exported environment variable?

As mentioned in the above answers, unset GNUPLOT_DRIVER_DIR should work if you have used export to set the variable. If you have set it permanently in ~/.bashrc or ~/.zshrc then simply removing it from there will work.

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

I found that in my code when I used a ration or percentage for line-height line-height;1.5;

My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px; so that I could predict exactly how many pixels each page would take with a given number of lines.

LISTAGG in Oracle to return distinct values

I think this could help - CASE the columns value to NULL if it's duplicate - then it's not appended to LISTAGG string:

with test_data as 
(
      select 1 as col1, 2 as col2, 'Smith' as created_by from dual
union select 1, 2, 'John' from dual
union select 1, 3, 'Ajay' from dual
union select 1, 4, 'Ram' from dual
union select 1, 5, 'Jack' from dual
union select 2, 5, 'Smith' from dual
union select 2, 6, 'John' from dual
union select 2, 6, 'Ajay' from dual
union select 2, 6, 'Ram' from dual
union select 2, 7, 'Jack' from dual
)
SELECT col1  ,
      listagg(col2 , ',') within group (order by col2 ASC) AS orig_value,
      listagg(CASE WHEN rwn=1 THEN col2 END , ',') within group (order by col2 ASC) AS distinct_value
from 
    (
    select row_number() over (partition by col1,col2 order by 1) as rwn, 
           a.*
    from test_data a
    ) a
GROUP BY col1   

Results in:

COL1  ORIG         DISTINCT
1   2,2,3,4,5   2,3,4,5
2   5,6,6,6,7   5,6,7

What is the functionality of setSoTimeout and how it works?

Does it mean that I'm blocking reading any input from the Server/Client for this socket for 2000 millisecond and after this time the socket is ready to read data?

No, it means that if no data arrives within 2000ms a SocketTimeoutException will be thrown.

What does it mean timeout expire?

It means the 2000ms (in your case) elapses without any data arriving.

What is the option which must be enabled prior to blocking operation?

There isn't one that 'must be' enabled. If you mean 'may be enabled', this is one of them.

Infinite Timeout menas that the socket does't read anymore?

What a strange suggestion. It means that if no data ever arrives you will block in the read forever.

How to parse dates in multiple formats using SimpleDateFormat

Matt's approach above is fine, but please be aware that you will run into problems if you use it to differentiate between dates of the format y/M/d and d/M/y. For instance, a formatter initialised with y/M/d will accept a date like 01/01/2009 and give you back a date which is clearly not what you wanted. I fixed the issue as follows, but I have limited time and I'm not happy with the solution for 2 main reasons:

  1. It violates one of Josh Bloch's quidelines, specifically 'don't use exceptions to handle program flow'.
  2. I can see the getDateFormat() method becoming a bit of a nightmare if you needed it to handle lots of other date formats.

If I had to make something that could handle lots and lots of different date formats and needed to be highly performant, then I think I would use the approach of creating an enum which linked each different date regex to its format. Then use MyEnum.values() to loop through the enum and test with if(myEnum.getPattern().matches(date)) rather than catching a dateformatexception.

Anway, that being said, the following can handle dates of the formats 'y/M/d' 'y-M-d' 'y M d' 'd/M/y' 'd-M-y' 'd M y' and all other variations of those which include time formats as well:

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class DateUtil {
    private static final String[] timeFormats = {"HH:mm:ss","HH:mm"};
    private static final String[] dateSeparators = {"/","-"," "};

    private static final String DMY_FORMAT = "dd{sep}MM{sep}yyyy";
    private static final String YMD_FORMAT = "yyyy{sep}MM{sep}dd";

    private static final String ymd_template = "\\d{4}{sep}\\d{2}{sep}\\d{2}.*";
    private static final String dmy_template = "\\d{2}{sep}\\d{2}{sep}\\d{4}.*";

    public static Date stringToDate(String input){
    Date date = null;
    String dateFormat = getDateFormat(input);
    if(dateFormat == null){
        throw new IllegalArgumentException("Date is not in an accepted format " + input);
    }

    for(String sep : dateSeparators){
        String actualDateFormat = patternForSeparator(dateFormat, sep);
        //try first with the time
        for(String time : timeFormats){
        date = tryParse(input,actualDateFormat + " " + time);
        if(date != null){
            return date;
        }
        }
        //didn't work, try without the time formats
        date = tryParse(input,actualDateFormat);
        if(date != null){
        return date;
        }
    }

    return date;
    }

    private static String getDateFormat(String date){
    for(String sep : dateSeparators){
        String ymdPattern = patternForSeparator(ymd_template, sep);
        String dmyPattern = patternForSeparator(dmy_template, sep);
        if(date.matches(ymdPattern)){
        return YMD_FORMAT;
        }
        if(date.matches(dmyPattern)){
        return DMY_FORMAT;
        }
    }
    return null;
    }

    private static String patternForSeparator(String template, String sep){
    return template.replace("{sep}", sep);
    }

    private static Date tryParse(String input, String pattern){
    try{
        return new SimpleDateFormat(pattern).parse(input);
    }
    catch (ParseException e) {}
    return null;
    }


}

Update Item to Revision vs Revert to Revision

The files in your working copy might look exactly the same after, but they are still very different actions -- the repository is in a completely different state, and you will have different options available to you after reverting than "updating" to an old revision.

Briefly, "update to" only affects your working copy, but "reverse merge and commit" will affect the repository.

If you "update" to an old revision, then the repository has not changed: in your example, the HEAD revision is still 100. You don't have to commit anything, since you are just messing around with your working copy. If you make modifications to your working copy and try to commit, you will be told that your working copy is out-of-date, and you will need to update before you can commit. If someone else working on the same repository performs an "update", or if you check out a second working copy, it will be r100.

However, if you "reverse merge" to an old revision, then your working copy is still based on the HEAD (assuming you are up-to-date) -- but you are creating a new revision to supersede the unwanted changes. You have to commit these changes, since you are changing the repository. Once done, any updates or new working copies based on the HEAD will show r101, with the contents you just committed.

Using iText to convert HTML to PDF

I have ended up using ABCPdf from webSupergoo. It works really well and for about $350 it has saved me hours and hours based on your comments above. Thanks again Daniel and Bratch for your comments.

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

Consider following code

<ul id="myTask">
  <li>Coding</li>
  <li>Answering</li>
  <li>Getting Paid</li>
</ul>

Now, here goes the difference

// Remove the myTask item when clicked.
$('#myTask').children().click(function () {
  $(this).remove()
});

Now, what if we add a myTask again?

$('#myTask').append('<li>Answer this question on SO</li>');

Clicking this myTask item will not remove it from the list, since it doesn't have any event handlers bound. If instead we'd used .on, the new item would work without any extra effort on our part. Here's how the .on version would look:

$('#myTask').on('click', 'li', function (event) {
  $(event.target).remove()
});

Summary:

The difference between .on() and .click() would be that .click() may not work when the DOM elements associated with the .click() event are added dynamically at a later point while .on() can be used in situations where the DOM elements associated with the .on() call may be generated dynamically at a later point.

FIFO class in Java

Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E> with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.

Access Database opens as read only

Create an empty folder and move the .mdb file to that folder. And try opening it from there. I tried it this way and it worked for me.

What's the fastest way in Python to calculate cosine similarity given sparse matrix data?

You can compute pairwise cosine similarity on the rows of a sparse matrix directly using sklearn. As of version 0.17 it also supports sparse output:

from sklearn.metrics.pairwise import cosine_similarity
from scipy import sparse

A =  np.array([[0, 1, 0, 0, 1], [0, 0, 1, 1, 1],[1, 1, 0, 1, 0]])
A_sparse = sparse.csr_matrix(A)

similarities = cosine_similarity(A_sparse)
print('pairwise dense output:\n {}\n'.format(similarities))

#also can output sparse matrices
similarities_sparse = cosine_similarity(A_sparse,dense_output=False)
print('pairwise sparse output:\n {}\n'.format(similarities_sparse))

Results:

pairwise dense output:
[[ 1.          0.40824829  0.40824829]
[ 0.40824829  1.          0.33333333]
[ 0.40824829  0.33333333  1.        ]]

pairwise sparse output:
(0, 1)  0.408248290464
(0, 2)  0.408248290464
(0, 0)  1.0
(1, 0)  0.408248290464
(1, 2)  0.333333333333
(1, 1)  1.0
(2, 1)  0.333333333333
(2, 0)  0.408248290464
(2, 2)  1.0

If you want column-wise cosine similarities simply transpose your input matrix beforehand:

A_sparse.transpose()

How do you loop through each line in a text file using a windows batch file?

From the Windows command line reference:

To parse a file, ignoring commented lines, type:

for /F "eol=; tokens=2,3* delims=," %i in (myfile.txt) do @echo %i %j %k

This command parses each line in Myfile.txt, ignoring lines that begin with a semicolon and passing the second and third token from each line to the FOR body (tokens are delimited by commas or spaces). The body of the FOR statement references %i to get the second token, %j to get the third token, and %k to get all of the remaining tokens.

If the file names that you supply contain spaces, use quotation marks around the text (for example, "File Name"). To use quotation marks, you must use usebackq. Otherwise, the quotation marks are interpreted as defining a literal string to parse.

By the way, you can find the command-line help file on most Windows systems at:

 "C:\WINDOWS\Help\ntcmds.chm"

Extract text from a string

Just to add a non-regex solution:

'(' + $myString.Split('()')[1] + ')'

This splits the string at the parentheses and takes the string from the array with the program name in it.

If you don't need the parentheses, just use:

$myString.Split('()')[1]

jQuery + client-side template = "Syntax error, unrecognized expression"

As the official document: As of 1.9, a string is only considered to be HTML if it starts with a less-than ("<") character. The Migrate plugin can be used to restore the pre-1.9 behavior.

If a string is known to be HTML but may start with arbitrary text that is not an HTML tag, pass it to jQuery.parseHTML() which will return an array of DOM nodes representing the markup. A jQuery collection can be created from this, for example: $($.parseHTML(htmlString)). This would be considered best practice when processing HTML templates for example. Simple uses of literal strings such as $("<p>Testing</p>").appendTo("body") are unaffected by this change.

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

Try to add the path to tnsnames.ora to the config file:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <oracle.manageddataaccess.client>
    <version number="4.112.3.60">
      <settings>
        <setting name="TNS_ADMIN" value="C:\oracle\product\10.2.0\client_1\NETWORK\ADMIN\" />
      </settings>
    </version>
  </oracle.manageddataaccess.client>
</configuration>

Hive query output to file

To directly save the file in HDFS, use the below command:

hive> insert overwrite  directory '/user/cloudera/Sample' row format delimited fields terminated by '\t' stored as textfile select * from table where id >100;

This will put the contents in the folder /user/cloudera/Sample in HDFS.

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

Open a URL in a new tab (and not a new window)

If you use window.open(url, '_blank'), it will be blocked (popup blocker) on Chrome.

Try this:

//With JQuery

$('#myButton').click(function () {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
});

With pure JavaScript,

document.querySelector('#myButton').onclick = function() {
    var redirectWindow = window.open('http://google.com', '_blank');
    redirectWindow.location;
};

Error message "Linter pylint is not installed"

If you are using MacPorts, you may need to activate package pylint and autopep8 after you've installed them, i.e.:

sudo port select pylint pylint36
sudo port select autopep8 autopep8-36

Rails 4 - Strong Parameters - Nested Objects

If it is Rails 5, because of new hash notation: params.permit(:name, groundtruth: [:type, coordinates:[]]) will work fine.

Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP

Maximum number of threads per process in Linux?

For anyone looking at this now, on systemd systems (in my case, specifically Ubuntu 16.04) there is another limit enforced by the cgroup pids.max parameter.

This is set to 12,288 by default, and can be overriden in /etc/systemd/logind.conf

Other advice still applies including pids_max, threads-max, max_maps_count, ulimits, etc.

Using Predicate in Swift

You can use filters available in swift to filter content from an array instead of using a predicate like in Objective-C.

An example in Swift 4.0 is as follows:

var stringArray = ["foundation","coredata","coregraphics"]
stringArray = stringArray.filter { $0.contains("core") }

In the above example, since each element in the array is a string you can use the contains method to filter the array.

If the array contains custom objects, then the properties of that object can be used to filter the elements similarly.

centos: Another MySQL daemon already running with the same unix socket

To prevent the problem from occurring, you must perform a graceful shutdown of the server from the command line rather than powering off the server.

# shutdown -h now

This will stop the running services before powering down the machine.

Based on Centos, an additional method for getting it back up again when you run into this problem is to move mysql.sock:

# mv /var/lib/mysql/mysql.sock /var/lib/mysql/mysql.sock.bak

# service mysqld start

Restarting the service creates a new entry called mqsql.sock

What is the most efficient way to check if a value exists in a NumPy array?

Fascinating. I needed to improve the speed of a series of loops that must perform matching index determination in this same way. So I decided to time all the solutions here, along with some riff's.

Here are my speed tests for Python 2.7.10:

import timeit
timeit.timeit('N.any(N.in1d(sids, val))', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

18.86137104034424

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = [20010401010101+x for x in range(1000)]')

15.061666011810303

timeit.timeit('N.in1d(sids, val)', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

11.613027095794678

timeit.timeit('N.any(val == sids)', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

7.670552015304565

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

5.610057830810547

timeit.timeit('val == sids', setup = 'import numpy as N; val = 20010401020091; sids = N.array([20010401010101+x for x in range(1000)])')

1.6632978916168213

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = set([20010401010101+x for x in range(1000)])')

0.0548710823059082

timeit.timeit('val in sids', setup = 'import numpy as N; val = 20010401020091; sids = dict(zip([20010401010101+x for x in range(1000)],[True,]*1000))')

0.054754018783569336

Very surprising! Orders of magnitude difference!

To summarize, if you just want to know whether something's in a 1D list or not:

  • 19s N.any(N.in1d(numpy array))
  • 15s x in (list)
  • 8s N.any(x == numpy array)
  • 6s x in (numpy array)
  • .1s x in (set or a dictionary)

If you want to know where something is in the list as well (order is important):

  • 12s N.in1d(x, numpy array)
  • 2s x == (numpy array)

Printing the value of a variable in SQL Developer

There are 2 options:

set serveroutput on format wrapped;

or

Open the 'view' menu and click on 'dbms output'. You should get a dbms output window at the bottom of the worksheet. You then need to add the connection (for some reason this is not done automatically).

postgresql port confusion 5433 or 5432?

/etc/services is only advisory, it's a listing of well-known ports. It doesn't mean that anything is actually running on that port or that the named service will run on that port.

In PostgreSQL's case it's typical to use port 5432 if it is available. If it isn't, most installers will choose the next free port, usually 5433.

You can see what is actually running using the netstat tool (available on OS X, Windows, and Linux, with command line syntax varying across all three).

This is further complicated on Mac OS X systems by the horrible mess of different PostgreSQL packages - Apple's ancient version of PostgreSQL built in to the OS, Postgres.app, Homebrew, Macports, the EnterpriseDB installer, etc etc.

What ends up happening is that the user installs Pg and starts a server from one packaging, but uses the psql and libpq client from a different packaging. Typically this occurs when they're running Postgres.app or homebrew Pg and connecting with the psql that shipped with the OS. Not only do these sometimes have different default ports, but the Pg that shipped with Mac OS X has a different default unix socket path, so even if the server is running on the same port it won't be listening to the same unix socket.

Most Mac users work around this by just using tcp/ip with psql -h localhost. You can also specify a port if required, eg psql -h localhost -p 5433. You might have multiple PostgreSQL instances running so make sure you're connecting to the right one by using select version() and SHOW data_directory;.

You can also specify a unix socket directory; check the unix_socket_directories setting of the PostgreSQL instance you wish to connect to and specify that with psql -h, e.g.psql -h /tmp.

A cleaner solution is to correct your system PATH so that the psql and libpq associated with the PostgreSQL you are actually running is what's found first on the PATH. The details of that depend on your Mac OS X version and which Pg packages you have installed. I don't use Mac and can't offer much more detail on that side without spending more time than is currently available.

Authentication failed to bitbucket

None of the above worked for me - the problem lay in my Sourcetree Preferences. In the Network tab, I had a setting there for 'Default usernames for URLs which do not include one:'. The username was incorrect where I had entered it incorrectly previously - I had set it to my email rather than username. I highlighted the entries and clicked Remove for both. Then I returned to my repository page and clicked Push again. On pushing, it asked me for full username and password, which I was able to enter correctly - the push then finally worked.

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

Before the launch of Java SE 7 we were habitual of writing code with multiple catch statements associated with a try block. A very basic Example:

 try {
  // some instructions
} catch(ATypeException e) {
} catch(BTypeException e) {
} catch(CTypeException e) {
}

But now with the latest update on Java, instead of writing multiple catch statements we can handle multiple exceptions within a single catch clause. Here is an example showing how this feature can be achieved.

try {
// some instructions
} catch(ATypeException|BTypeException|CTypeException ex) {
   throw e;
}

So multiple Exceptions in a single catch clause not only simplifies the code but also reduce the redundancy of code. I found this article which explains this feature very well along with its implementation. Improved and Better Exception Handling from Java 7 This may help you too.

PHPMailer character encoding issues

$mail -> CharSet = "UTF-8";
$mail = new PHPMailer();

line $mail -> CharSet = "UTF-8"; must be after $mail = new PHPMailer(); and with no spaces!

try this

$mail = new PHPMailer();
$mail->CharSet = "UTF-8";

How do I download a file using VBA (without Internet Explorer)

This solution is based from this website: http://social.msdn.microsoft.com/Forums/en-US/bd0ee306-7bb5-4ce4-8341-edd9475f84ad/excel-2007-use-vba-to-download-save-csv-from-url

It is slightly modified to overwrite existing file and to pass along login credentials.

Sub DownloadFile()

Dim myURL As String
myURL = "https://YourWebSite.com/?your_query_parameters"

Dim WinHttpReq As Object
Set WinHttpReq = CreateObject("Microsoft.XMLHTTP")
WinHttpReq.Open "GET", myURL, False, "username", "password"
WinHttpReq.send

If WinHttpReq.Status = 200 Then
    Set oStream = CreateObject("ADODB.Stream")
    oStream.Open
    oStream.Type = 1
    oStream.Write WinHttpReq.responseBody
    oStream.SaveToFile "C:\file.csv", 2 ' 1 = no overwrite, 2 = overwrite
    oStream.Close
End If

End Sub

Iterating Through a Dictionary in Swift

If you want to iterate over all the values:

dict.values.forEach { value in
    // print(value)
}

How can I make an entire HTML form "readonly"?

This is an ideal solution for disabling all inputs, textareas, selects and buttons in a specified element.

For jQuery 1.6 and above:

// To fully disable elements
$('#myForm :input').prop('disabled', true); 

Or

// To make elements readonly
$('#myForm :input').prop('readonly', true); 

jQuery 1.5 and below:

$('#myForm :input').prop('disabled', 'disabled');

And

$('#myForm :input').prop('readonly', 'readonly');

How to dynamically create generic C# object using reflection?

I know this question is resolved but, for the benefit of anyone else reading it; if you have all of the types involved as strings, you could do this as a one liner:

IYourInterface o = (Activator.CreateInstance(Type.GetType("Namespace.TaskA`1[OtherNamespace.TypeParam]") as IYourInterface);

Whenever I've done this kind of thing, I've had an interface which I wanted subsequent code to utilise, so I've casted the created instance to an interface.

How do I find if a string starts with another string in Ruby?

Since there are several methods presented here, I wanted to figure out which one was fastest. Using Ruby 1.9.3p362:

irb(main):001:0> require 'benchmark'
=> true
irb(main):002:0> Benchmark.realtime { 1.upto(10000000) { "foobar"[/\Afoo/] }}
=> 12.477248
irb(main):003:0> Benchmark.realtime { 1.upto(10000000) { "foobar" =~ /\Afoo/ }}
=> 9.593959
irb(main):004:0> Benchmark.realtime { 1.upto(10000000) { "foobar"["foo"] }}
=> 9.086909
irb(main):005:0> Benchmark.realtime { 1.upto(10000000) { "foobar".start_with?("foo") }}
=> 6.973697

So it looks like start_with? ist the fastest of the bunch.

Updated results with Ruby 2.2.2p95 and a newer machine:

require 'benchmark'
Benchmark.bm do |x|
  x.report('regex[]')    { 10000000.times { "foobar"[/\Afoo/] }}
  x.report('regex')      { 10000000.times { "foobar" =~ /\Afoo/ }}
  x.report('[]')         { 10000000.times { "foobar"["foo"] }}
  x.report('start_with') { 10000000.times { "foobar".start_with?("foo") }}
end

            user       system     total       real
regex[]     4.020000   0.000000   4.020000 (  4.024469)
regex       3.160000   0.000000   3.160000 (  3.159543)
[]          2.930000   0.000000   2.930000 (  2.931889)
start_with  2.010000   0.000000   2.010000 (  2.008162)

biggest integer that can be stored in a double

The biggest/largest integer that can be stored in a double without losing precision is the same as the largest possible value of a double. That is, DBL_MAX or approximately 1.8 × 10308 (if your double is an IEEE 754 64-bit double). It's an integer. It's represented exactly. What more do you want?

Go on, ask me what the largest integer is, such that it and all smaller integers can be stored in IEEE 64-bit doubles without losing precision. An IEEE 64-bit double has 52 bits of mantissa, so I think it's 253:

  • 253 + 1 cannot be stored, because the 1 at the start and the 1 at the end have too many zeros in between.
  • Anything less than 253 can be stored, with 52 bits explicitly stored in the mantissa, and then the exponent in effect giving you another one.
  • 253 obviously can be stored, since it's a small power of 2.

Or another way of looking at it: once the bias has been taken off the exponent, and ignoring the sign bit as irrelevant to the question, the value stored by a double is a power of 2, plus a 52-bit integer multiplied by 2exponent - 52. So with exponent 52 you can store all values from 252 through to 253 - 1. Then with exponent 53, the next number you can store after 253 is 253 + 1 × 253 - 52. So loss of precision first occurs with 253 + 1.

How can I see if a Perl hash already has a certain key?

I believe to check if a key exists in a hash you just do

if (exists $strings{$string}) {
    ...
} else {
    ...
}

Undo git pull, how to bring repos to old state

git pull do below operation.

i. git fetch

ii. git merge

To undo pull do any operation:

i. git reset --hard --- its revert all local change also

or

ii. git reset --hard master@{5.days.ago} (like 10.minutes.ago, 1.hours.ago, 1.days.ago ..) to get local changes.

or

iii. git reset --hard commitid

Improvement:

Next time use git pull --rebase instead of git pull.. its sync server change by doing ( fetch & merge).

Incrementing in C++ - When to use x++ or ++x?

I just want to notice that the geneated code is offen the same if you use pre/post incrementation where the semantic (of pre/post) doesn't matter.

example:

pre.cpp:

#include <iostream>

int main()
{
  int i = 13;
  i++;
  for (; i < 42; i++)
    {
      std::cout << i << std::endl;
    }
}

post.cpp:

#include <iostream>

int main()
{

  int i = 13;
  ++i;
  for (; i < 42; ++i)
    {
      std::cout << i << std::endl;
    }
}

_

$> g++ -S pre.cpp
$> g++ -S post.cpp
$> diff pre.s post.s   
1c1
<   .file   "pre.cpp"
---
>   .file   "post.cpp"

jQuery find() method not working in AngularJS directive

Before the days of jQuery you would use:

   document.getElementById('findmebyid');

If this one line will save you an entire jQuery library, it might be worth while using it instead.

For those concerned about performance: Beginning your selector with an ID is always best as it uses native function document.getElementById.

// Fast:
$( "#container div.robotarm" );

// Super-fast:
$( "#container" ).find( "div.robotarm" );

http://learn.jquery.com/performance/optimize-selectors/

jsPerf http://jsperf.com/jquery-selector-benchmark/32

Javascript/jQuery detect if input is focused

If you can use JQuery, then using the JQuery :focus selector will do the needful

$(this).is(':focus');

Replace an element into a specific position of a vector

You can do that using at. You can try out the following simple example:

const size_t N = 20;
std::vector<int> vec(N);
try {
    vec.at(N - 1) = 7;
} catch (std::out_of_range ex) {
    std::cout << ex.what() << std::endl;
}
assert(vec.at(N - 1) == 7);

Notice that method at returns an allocator_type::reference, which is that case is a int&. Using at is equivalent to assigning values like vec[i]=....


There is a difference between at and insert as it can be understood with the following example:

const size_t N = 8;
std::vector<int> vec(N);
for (size_t i = 0; i<5; i++){
    vec[i] = i + 1;
}

vec.insert(vec.begin()+2, 10);

If we now print out vec we will get:

1 2 10 3 4 5 0 0 0

If, instead, we did vec.at(2) = 10, or vec[2]=10, we would get

1 2 10 4 5 0 0 0

Attempt to write a readonly database - Django w/ SELinux error

In short, it happens when the application which writes to the sqlite database does not have write permission.

This can be solved in three ways:

  1. Granting ownership of db.sqlite3 file and its parent directory (thereby write access also) to the user using chown (Eg: chown username db.sqlite3 )
  2. Running the webserver (often gunicorn) as root user (run the command sudo -i before you run gunicorn or django runserver)
  3. Allowing read and write access to all users by running command chmod 777 db.sqlite3 (Dangerous option)

Never go for the third option unless you are running the webserver in a local machine or the data in the database is not at all important for you.

Second option is also not recommended. But you can go for it, if you are sure that your application is not vulnerable for code injection attack.

How to echo in PHP, HTML tags

<?php

echo '<div>
 <h3><a href="#">First</a></h3>
 <div>Lorem ipsum dolor sit amet.</div>
</div>
<div>';

?>

Just put it in single quotes.

How to save a base64 image to user's disk using JavaScript?

In JavaScript you cannot have the direct access to the filesystem. However, you can make browser to pop up a dialog window allowing the user to pick the save location. In order to do this, use the replace method with your Base64String and replace "image/png" with "image/octet-stream":

"data:image/png;base64,iVBORw0KG...".replace("image/png", "image/octet-stream");

Also, W3C-compliant browsers provide 2 methods to work with base64-encoded and binary data:

Probably, you will find them useful in a way...


Here is a refactored version of what I understand you need:

_x000D_
_x000D_
window.addEventListener('DOMContentLoaded', () => {_x000D_
  const img = document.getElementById('embedImage');_x000D_
  img.src = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA' +_x000D_
    'AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO' +_x000D_
    '9TXL0Y4OHwAAAABJRU5ErkJggg==';_x000D_
_x000D_
  img.addEventListener('load', () => button.removeAttribute('disabled'));_x000D_
  _x000D_
  const button = document.getElementById('saveImage');_x000D_
  button.addEventListener('click', () => {_x000D_
    window.location.href = img.src.replace('image/png', 'image/octet-stream');_x000D_
  });_x000D_
});
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <img id="embedImage" alt="Red dot" />_x000D_
  <button id="saveImage" disabled="disabled">save image</button>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

GCC fatal error: stdio.h: No such file or directory

Mac OS Mojave

The accepted answer no longer works. When running the command xcode-select --install it tells you to use "Software Update" to install updates.

In this link is the updated method:

Open a Terminal and then:

cd /Library/Developer/CommandLineTools/Packages/
open macOS_SDK_headers_for_macOS_10.14.pkg

This will open an installation Wizard.

Update 12/2019

After updating to Mojave 10.15.1 it seems that using xcode-select --install works as intended.

Program "make" not found in PATH

If you are using MinGw, rename the mingw32-make.exe to make.exe in the folder " C:\MinGW\bin " or wherever minGw is installed in your system.

Regex to match string containing two names in any order

You can do checks using lookarounds:

^(?=.*\bjack\b)(?=.*\bjames\b).*$

Test it.

This approach has the advantage that you can easily specify multiple conditions.

^(?=.*\bjack\b)(?=.*\bjames\b)(?=.*\bjason\b)(?=.*\bjules\b).*$

Getting an option text/value with JavaScript

You can use:

var option_user_selection = element.options[ element.selectedIndex ].text

Does reading an entire file leave the file handle open?

Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:

with open('Path/to/file', 'r') as content_file:
    content_list = content_file.read().strip().split("\n")

As can be seen, one needs to add the concatenated methods .strip().split("\n") to the main answer in this thread.

Here, .strip() just removes whitespace and newline characters at the endings of the entire file string, and .split("\n") produces the actual list via splitting the entire file string at every newline character \n.

Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.

IIS URL Rewrite and Web.config

Just wanted to point out one thing missing in LazyOne's answer (I would have just commented under the answer but don't have enough rep)

In rule #2 for permanent redirect there is thing missing:

redirectType="Permanent"

So rule #2 should look like this:

<system.webServer>
    <rewrite>
        <rules>
            <rule name="SpecificRedirect" stopProcessing="true">
                <match url="^page$" />
                <action type="Redirect" url="/page.html" redirectType="Permanent" />
            </rule>
        </rules>
    </rewrite>
</system.webServer>

Edit

For more information on how to use the URL Rewrite Module see this excellent documentation: URL Rewrite Module Configuration Reference

In response to @kneidels question from the comments; To match the url: topic.php?id=39 something like the following could be used:

<system.webServer>
  <rewrite>
    <rules>
      <rule name="SpecificRedirect" stopProcessing="true">
        <match url="^topic.php$" />
        <conditions logicalGrouping="MatchAll">
          <add input="{QUERY_STRING}" pattern="(?:id)=(\d{2})" />
        </conditions>
        <action type="Redirect" url="/newpage/{C:1}" appendQueryString="false" redirectType="Permanent" />
      </rule>
    </rules>
  </rewrite>
</system.webServer>

This will match topic.php?id=ab where a is any number between 0-9 and b is also any number between 0-9. It will then redirect to /newpage/xy where xy comes from the original url. I have not tested this but it should work.

Replacing Pandas or Numpy Nan with a None to use with MysqlDB

@bogatron has it right, you can use where, it's worth noting that you can do this natively in pandas:

df1 = df.where(pd.notnull(df), None)

Note: this changes the dtype of all columns to object.

Example:

In [1]: df = pd.DataFrame([1, np.nan])

In [2]: df
Out[2]: 
    0
0   1
1 NaN

In [3]: df1 = df.where(pd.notnull(df), None)

In [4]: df1
Out[4]: 
      0
0     1
1  None

Note: what you cannot do recast the DataFrames dtype to allow all datatypes types, using astype, and then the DataFrame fillna method:

df1 = df.astype(object).replace(np.nan, 'None')

Unfortunately neither this, nor using replace, works with None see this (closed) issue.


As an aside, it's worth noting that for most use cases you don't need to replace NaN with None, see this question about the difference between NaN and None in pandas.

However, in this specific case it seems you do (at least at the time of this answer).

npm ERR! code UNABLE_TO_GET_ISSUER_CERT_LOCALLY

A quick solution from the internet search was npm config set strict-ssl false, luckily it worked. But as a part of my work environment, I am restricted to set the strict-ssl flag to false.

Later I found a safe and working solution,

npm config set registry http://registry.npmjs.org/  

this worked perfectly and I got a success message Happy Hacking! by not setting the strict-ssl flag to false.

How to manually force a commit in a @Transactional method?

Why don't you use spring's TransactionTemplate to programmatically control transactions? You could also restructure your code so that each "transaction block" has it's own @Transactional method, but given that it's a test I would opt for programmatic control of your transactions.

Also note that the @Transactional annotation on your runnable won't work (unless you are using aspectj) as the runnables aren't managed by spring!

@RunWith(SpringJUnit4ClassRunner.class)
//other spring-test annotations; as your database context is dirty due to the committed transaction you might want to consider using @DirtiesContext
public class TransactionTemplateTest {

@Autowired
PlatformTransactionManager platformTransactionManager;

TransactionTemplate transactionTemplate;

@Before
public void setUp() throws Exception {
    transactionTemplate = new TransactionTemplate(platformTransactionManager);
}

@Test //note that there is no @Transactional configured for the method
public void test() throws InterruptedException {

    final Contract c1 = transactionTemplate.execute(new TransactionCallback<Contract>() {
        @Override
        public Contract doInTransaction(TransactionStatus status) {
            Contract c = contractDOD.getNewTransientContract(15);
            contractRepository.save(c);
            return c;
        }
    });

    ExecutorService executorService = Executors.newFixedThreadPool(5);

    for (int i = 0; i < 5; ++i) {
        executorService.execute(new Runnable() {
            @Override  //note that there is no @Transactional configured for the method
            public void run() {
                transactionTemplate.execute(new TransactionCallback<Object>() {
                    @Override
                    public Object doInTransaction(TransactionStatus status) {
                        // do whatever you want to do with c1
                        return null;
                    }
                });
            }
        });
    }

    executorService.shutdown();
    executorService.awaitTermination(10, TimeUnit.SECONDS);

    transactionTemplate.execute(new TransactionCallback<Object>() {
        @Override
        public Object doInTransaction(TransactionStatus status) {
            // validate test results in transaction
            return null;
        }
    });
}

}

How to get html to print return value of javascript function?

Most likely you're looking for something like

var targetElement = document.getElementById('idOfTargetElement');
targetElement.innerHTML = produceMessage();

provided that this is not something which happens on page load, in which case it should already be there from the start.

Which MIME type to use for a binary file that's specific to my program?

I'd recommend application/octet-stream as RFC2046 says "The "octet-stream" subtype is used to indicate that a body contains arbitrary binary data" and "The recommended action for an implementation that receives an "application/octet-stream" entity is to simply offer to put the data in a file[...]".

I think that way you will get better handling from arbitrary programs, that might barf when encountering your unknown mime type.

What are ODEX files in Android?

This Blog article explains the internals of ODEX files:

WHAT IS AN ODEX FILE?

In Android file system, applications come in packages with the extension .apk. These application packages, or APKs contain certain .odex files whose supposed function is to save space. These ‘odex’ files are actually collections of parts of an application that are optimized before booting. Doing so speeds up the boot process, as it preloads part of an application. On the other hand, it also makes hacking those applications difficult because a part of the coding has already been extracted to another location before execution.

how do I initialize a float to its max/min value?

You can either use -FLT_MAX (or -DBL_MAX) for the maximum magnitude negative number and FLT_MAX (or DBL_MAX) for positive. This gives you the range of possible float (or double) values.

You probably don't want to use FLT_MIN; it corresponds to the smallest magnitude positive number that can be represented with a float, not the most negative value representable with a float.

FLT_MIN and FLT_MAX correspond to std::numeric_limits<float>::min() and std::numeric_limits<float>::max().

Node Sass couldn't find a binding for your current environment

Worked for me:

Just delete the node-sass folder and run npm install.

Partly cherry-picking a commit with Git

I know I'm answering an old question, but it looks like there's a new way to do this with interactively checking out:

git checkout -p bc66559

Credit to Can I interactively pick hunks from another git commit?

Javascript to Select Multiple options

<script language="JavaScript" type="text/javascript">
<!--
function loopSelected()
{
  var txtSelectedValuesObj = document.getElementById('txtSelectedValues');
  var selectedArray = new Array();
  var selObj = document.getElementById('selSeaShells');
  var i;
  var count = 0;
  for (i=0; i<selObj.options.length; i++) {
    if (selObj.options[i].selected) {
      selectedArray[count] = selObj.options[i].value;
      count++;
    }
  }
  txtSelectedValuesObj.value = selectedArray;
}
function openInNewWindow(frm)
{
  // open a blank window
  var aWindow = window.open('', 'Tutorial004NewWindow',
   'scrollbars=yes,menubar=yes,resizable=yes,toolbar=no,width=400,height=400');

  // set the target to the blank window
  frm.target = 'Tutorial004NewWindow';

  // submit
  frm.submit();
}
//-->
</script>
The HTML
<form action="tutorial004_nw.html" method="get">
  <table border="1" cellpadding="10" cellspacing="0">
  <tr>
    <td valign="top">
      <input type="button" value="Submit" onclick="openInNewWindow(this.form);" />
      <input type="button" value="Loop Selected" onclick="loopSelected();" />
      <br />
      <select name="selSea" id="selSeaShells" size="5" multiple="multiple">
        <option value="val0" selected>sea zero</option>
        <option value="val1">sea one</option>
        <option value="val2">sea two</option>
        <option value="val3">sea three</option>
        <option value="val4">sea four</option>
      </select>
    </td>
    <td valign="top">
      <input type="text" id="txtSelectedValues" />
      selected array
    </td>
  </tr>
  </table>
</form>

Using getResources() in non-activity class

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 XmlPullParser xpp = ctx.getResources().getXml(R.xml.samplexml);
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

Partial Dependency (Databases)

Partial Dependency is one kind of functional dependency that occur when primary key must be candidate key and non prime attribute are depends on the subset/part of candidates key (more than one primary key).

Try to understand partial dependency relate through example :

Seller(Id, Product, Price)

Candidate Key : Id, Product
Non prime attribute : Price

Price attribute only depends on only Product attribute which is a subset of candidate key, Not the whole candidate key(Id, Product) key . It is called partial dependency.

So we can say that Product->Price is partial dependency.

How to get disk capacity and free space of remote computer

There are two issues I encountered with the other suggestions

    1) Drive mappings are not supported if you run the powershell under task scheduler
    2) You may get Access is denied errors errors trying to used "get-WmiObject" on remote computers (depending on your infrastructure setup, of course)

The alternative that doesn't suffer from these issues is to use GetDiskFreeSpaceEx with a UNC path:

function getDiskSpaceInfoUNC($p_UNCpath, $p_unit = 1tb, $p_format = '{0:N1}')
{
    # unit, one of --> 1kb, 1mb, 1gb, 1tb, 1pb
    $l_typeDefinition = @' 
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] 
        [return: MarshalAs(UnmanagedType.Bool)] 
        public static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, 
            out ulong lpFreeBytesAvailable, 
            out ulong lpTotalNumberOfBytes, 
            out ulong lpTotalNumberOfFreeBytes); 
'@
    $l_type = Add-Type -MemberDefinition $l_typeDefinition -Name Win32Utils -Namespace GetDiskFreeSpaceEx -PassThru

    $freeBytesAvailable     = New-Object System.UInt64 # differs from totalNumberOfFreeBytes when per-user disk quotas are in place
    $totalNumberOfBytes     = New-Object System.UInt64
    $totalNumberOfFreeBytes = New-Object System.UInt64

    $l_result = $l_type::GetDiskFreeSpaceEx($p_UNCpath,([ref]$freeBytesAvailable),([ref]$totalNumberOfBytes),([ref]$totalNumberOfFreeBytes)) 

    $totalBytes     = if($l_result) { $totalNumberOfBytes    /$p_unit } else { '' }
    $totalFreeBytes = if($l_result) { $totalNumberOfFreeBytes/$p_unit } else { '' }

    New-Object PSObject -Property @{
        Success   = $l_result
        Path      = $p_UNCpath
        Total     = $p_format -f $totalBytes
        Free      = $p_format -f $totalFreeBytes
    } 
}

How to do IF NOT EXISTS in SQLite

If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:

CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));

And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:

INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');

It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not.

Static variable inside of a function in C

In C++11 at least, when the expression used to initialize a local static variable is not a 'constexpr' (cannot be evaluated by the compiler), then initialization must happen during the first call to the function. The simplest example is to directly use a parameter to intialize the local static variable. Thus the compiler must emit code to guess whether the call is the first one or not, which in turn requires a local boolean variable. I've compiled such example and checked this is true by seeing the assembly code. The example can be like this:

void f( int p )
{
  static const int first_p = p ;
  cout << "first p == " << p << endl ;
}

void main()
{
   f(1); f(2); f(3);
}

of course, when the expresion is 'constexpr', then this is not required and the variable can be initialized on program load by using a value stored by the compiler in the output assembly code.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

First, get your tombstone stack trace, it will be printed every time your app crashes. Something like this:

*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'XXXXXXXXX'
pid: 1658, tid: 13086  >>> system_server <<<
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr 64696f7e
 r0 00000000  r1 00000001  r2 ad12d1e8  r3 7373654d
 r4 64696f72  r5 00000406  r6 00974130  r7 40d14008
 r8 4b857b88  r9 4685adb4  10 00974130  fp 4b857ed8
 ip 00000000  sp 4b857b50  lr afd11108  pc ad115ebc  cpsr 20000030
 d0  4040000040000000  d1  0000004200000003
 d2  4e72cd924285e370  d3  00e81fe04b1b64d8
 d4  3fbc71c7009b64d8  d5  3fe999999999999a
 d6  4010000000000000  d7  4000000000000000
 d8  4000000000000000  d9  0000000000000000
 d10 0000000000000000  d11 0000000000000000
 d12 0000000000000000  d13 0000000000000000
 d14 0000000000000000  d15 0000000000000000
 scr 80000012

         #00  pc 000108d8  /system/lib/libc.so
         #01  pc 0003724c  /system/lib/libxvi020.so
         #02  pc 0000ce02  /system/lib/libxvi020.so
         #03  pc 0000d672  /system/lib/libxvi020.so
         #04  pc 00010cce  /system/lib/libxvi020.so
         #05  pc 00004432  /system/lib/libwimax_jni.so
         #06  pc 00011e74  /system/lib/libdvm.so
         #07  pc 0004354a  /system/lib/libdvm.so
         #08  pc 00017088  /system/lib/libdvm.so
         #09  pc 0001c210  /system/lib/libdvm.so
         #10  pc 0001b0f8  /system/lib/libdvm.so
         #11  pc 00059c24  /system/lib/libdvm.so
         #12  pc 00059e3c  /system/lib/libdvm.so
         #13  pc 0004e19e  /system/lib/libdvm.so
         #14  pc 00011b94  /system/lib/libc.so
         #15  pc 0001173c  /system/lib/libc.so

code around pc:
ad115e9c 4620eddc bf00bd70 0001736e 0001734e 
ad115eac 4605b570 447c4c0a f7f44620 e006edc8 
ad115ebc 42ab68e3 68a0d103 f7f42122 6864edd2 
ad115ecc d1f52c00 44784803 edbef7f4 bf00bd70 
ad115edc 00017332 00017312 2100b51f 46682210 

code around lr:
afd110e8 e2166903 1a000018 e5945000 e1a02004 
afd110f8 e2055a02 e1a00005 e3851001 ebffed92 
afd11108 e3500000 13856002 1a000001 ea000009 
afd11118 ebfffe50 e1a01004 e1a00006 ebffed92 
afd11128 e1a01005 e1550000 e1a02006 e3a03000 

stack:
    4b857b10  40e43be8  
    4b857b14  00857280  
    4b857b18  00000000  
    4b857b1c  034e8968  
    4b857b20  ad118ce9  /system/lib/libnativehelper.so
    4b857b24  00000002  
    4b857b28  00000406

Then, use the addr2line utility (find it in your NDK tool-chain) to find the function that crashes. In this sample, you do

addr2line -e -f libc.so 0001173c

And you will see where you got the problem. Of course this wont help you since it is in libc.

So you might combine the utilities of arm-eabi-objdump to find the final target.

Believe me, it is a tough task.




Just for an update. I think I was doing Android native build from the whole-source-tree for quite a long time, until today I have myself carefully read the NDK documents. Ever since the release NDK-r6, it has provided a utility called ndk-stack.

Following is the content from official NDK documents with the NDK-r9 tar ball.

Overview:

ndk-stack is a simple tool that allows you to filter stack traces as they appear in the output of 'adb logcat' and replace any address inside a shared library with the corresponding : values.

In a nutshell, it will translate something like:

  I/DEBUG   (   31): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
  I/DEBUG   (   31): Build fingerprint: 'generic/google_sdk/generic/:2.2/FRF91/43546:eng/test-keys'
  I/DEBUG   (   31): pid: 351, tid: 351  %gt;%gt;%gt; /data/local/ndk-tests/crasher <<<
  I/DEBUG   (   31): signal 11 (SIGSEGV), fault addr 0d9f00d8
  I/DEBUG   (   31):  r0 0000af88  r1 0000a008  r2 baadf00d  r3 0d9f00d8
  I/DEBUG   (   31):  r4 00000004  r5 0000a008  r6 0000af88  r7 00013c44
  I/DEBUG   (   31):  r8 00000000  r9 00000000  10 00000000  fp 00000000
  I/DEBUG   (   31):  ip 0000959c  sp be956cc8  lr 00008403  pc 0000841e  cpsr 60000030
  I/DEBUG   (   31):          #00  pc 0000841e  /data/local/ndk-tests/crasher
  I/DEBUG   (   31):          #01  pc 000083fe  /data/local/ndk-tests/crasher
  I/DEBUG   (   31):          #02  pc 000083f6  /data/local/ndk-tests/crasher
  I/DEBUG   (   31):          #03  pc 000191ac  /system/lib/libc.so
  I/DEBUG   (   31):          #04  pc 000083ea  /data/local/ndk-tests/crasher
  I/DEBUG   (   31):          #05  pc 00008458  /data/local/ndk-tests/crasher
  I/DEBUG   (   31):          #06  pc 0000d362  /system/lib/libc.so
  I/DEBUG   (   31):

Into the more readable output:

  ********** Crash dump: **********
  Build fingerprint: 'generic/google_sdk/generic/:2.2/FRF91/43546:eng/test-keys'
  pid: 351, tid: 351  >>> /data/local/ndk-tests/crasher <<<
  signal 11 (SIGSEGV), fault addr 0d9f00d8
  Stack frame #00  pc 0000841e  /data/local/ndk-tests/crasher : Routine zoo in /tmp/foo/crasher/jni/zoo.c:13
  Stack frame #01  pc 000083fe  /data/local/ndk-tests/crasher : Routine bar in /tmp/foo/crasher/jni/bar.c:5
  Stack frame #02  pc 000083f6  /data/local/ndk-tests/crasher : Routine my_comparison in /tmp/foo/crasher/jni/foo.c:9
  Stack frame #03  pc 000191ac  /system/lib/libc.so
  Stack frame #04  pc 000083ea  /data/local/ndk-tests/crasher : Routine foo in /tmp/foo/crasher/jni/foo.c:14
  Stack frame #05  pc 00008458  /data/local/ndk-tests/crasher : Routine main in /tmp/foo/crasher/jni/main.c:19
  Stack frame #06  pc 0000d362  /system/lib/libc.so

Usage:

To do this, you will first need a directory containing symbolic versions of your application's shared libraries. If you use the NDK build system (i.e. ndk-build), then these are always located under $PROJECT_PATH/obj/local/, where stands for your device's ABI (i.e. armeabi by default).

You can feed the logcat text either as direct input to the program, e.g.:

adb logcat | $NDK/ndk-stack -sym $PROJECT_PATH/obj/local/armeabi

Or you can use the -dump option to specify the logcat as an input file, e.g.:

adb logcat > /tmp/foo.txt
$NDK/ndk-stack -sym $PROJECT_PATH/obj/local/armeabi -dump foo.txt

IMPORTANT :

The tool looks for the initial line containing starts in the logcat output, i.e. something that looks like:

 *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

When copy/pasting traces, don't forget this line from the traces, or ndk-stack won't work correctly.

TODO:

A future version of ndk-stack will try to launch adb logcat and select the library path automatically. For now, you'll have to do these steps manually.

As of now, ndk-stack doesn't handle libraries that don't have debug information in them. It may be useful to try to detect the nearest function entry point to a given PC address (e.g. as in the libc.so example above).

Draw a curve with css

You could use an asymmetrical border to make curves with CSS.

border-radius: 50%/100px 100px 0 0;

VIEW DEMO

_x000D_
_x000D_
.box {_x000D_
  width: 500px; _x000D_
  height: 100px;  _x000D_
  border: solid 5px #000;_x000D_
  border-color: #000 transparent transparent transparent;_x000D_
  border-radius: 50%/100px 100px 0 0;_x000D_
}
_x000D_
<div class="box"></div>
_x000D_
_x000D_
_x000D_

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

Select first occurring element after another element

For your literal example you'd want to use the adjacent selector (+).

h4 + p {color:red}//any <p> that is immediately preceded by an <h4>

<h4>Some text</h4>
<p>I'm red</p>
<p>I'm not</p>

However, if you wanted to select all successive paragraphs, you'd need to use the general sibling selector (~).

h4 ~ p {color:red}//any <p> that has the same parent as, and comes after an <h4>

<h4>Some text</h4>
<p>I'm red</p>
<p>I am too</p>

It's known to be buggy in IE 7+ unfortunately.

How to NodeJS require inside TypeScript file?

The best solution is to get a copy of Node's type definitions. This will solve all kinds of dependency issues, not only require(). This was previously done using packages like typings, but as Mike Chamberlain mentioned, Typings are deprecated. The modern way is doing it like this:

npm install --save-dev @types/node

Not only will it fix the compiler error, it will also add the definitions of the Node API to your IDE.

What's the difference between next() and nextLine() methods from Scanner class?

From the documentation for Scanner:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

From the documentation for next():

A complete token is preceded and followed by input that matches the delimiter pattern.

How to get file_get_contents() to work with HTTPS?

Try the following.

function getSslPage($url) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_REFERER, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

Note: This disables SSL verification, meaning the security offered by HTTPS is lost. Only use this code for testing / local development, never on the internet or other public-facing networks. If this code works, it means the SSL certificate isn't trusted or can't be verified, which you should look into fixing as a separate issue.

Get the last 4 characters of a string

Like this:

>>>mystr = "abcdefghijkl"
>>>mystr[-4:]
'ijkl'

This slices the string's last 4 characters. The -4 starts the range from the string's end. A modified expression with [:-4] removes the same 4 characters from the end of the string:

>>>mystr[:-4]
'abcdefgh'

For more information on slicing see this Stack Overflow answer.

Memory errors and list limits?

If you want to circumvent this problem you could also use the shelve. Then you would create files that would be the size of your machines capacity to handle, and only put them on the RAM when necessary, basically writing to the HD and pulling the information back in pieces so you can process it.

Create binary file and check if information is already in it if yes make a local variable to hold it else write some data you deem necessary.

Data = shelve.open('File01')
   for i in range(0,100):
     Matrix_Shelve = 'Matrix' + str(i)
     if Matrix_Shelve in Data:
        Matrix_local = Data[Matrix_Shelve]
     else:
        Data[Matrix_Selve] = 'somenthingforlater'

Hope it doesn't sound too arcaic.

How to Use Sockets in JavaScript\HTML?

I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.

How to get client's IP address using JavaScript?

<script type="application/javascript">
  function getip(json)
  {
     alert(json.ip); 
  }

 <script type="application/javascript" src="http://jsonip.appspot.com/?callback=getip"></script>

Run above script Clik here

Changing the page title with Jquery

$(document).prop('title', 'test');

This is simply a JQuery wrapper for:

document.title = 'test';

To add a > periodically you can do:

function changeTitle() {
    var title = $(document).prop('title'); 
    if (title.indexOf('>>>') == -1) {
        setTimeout(changeTitle, 3000);  
        $(document).prop('title', '>'+title);
    }
}

changeTitle();

How can I transform string to UTF-8 in C#?

string utf8String = "Acción";
string propEncodeString = string.Empty;

byte[] utf8_Bytes = new byte[utf8String.Length];
for (int i = 0; i < utf8String.Length; ++i)
{
   utf8_Bytes[i] = (byte)utf8String[i];
}

propEncodeString = Encoding.UTF8.GetString(utf8_Bytes, 0, utf8_Bytes.Length);

Output should look like

Acción

day’s displays day's

call DecodeFromUtf8();

private static void DecodeFromUtf8()
{
    string utf8_String = "day’s";
    byte[] bytes = Encoding.Default.GetBytes(utf8_String);
    utf8_String = Encoding.UTF8.GetString(bytes);
}

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

Wildcards in a Windows hosts file

Acrylic DNS Proxy (free, open source) does the job. It creates a proxy DNS server (on your own computer) with its own hosts file. The hosts file accepts wildcards.

Download from the offical website

http://mayakron.altervista.org/support/browse.php?path=Acrylic&name=Home

Configuring Acrylic DNS Proxy

To configure Acrylic DNS Proxy, install it from the above link then go to:

  1. Start
  2. Programs
  3. Acrylic DNS Proxy
  4. Config
  5. Edit Custom Hosts File (AcrylicHosts.txt)

Add the folowing lines on the end of the file:

127.0.0.1   *.localhost
127.0.0.1   *.local
127.0.0.1   *.lc

Restart the Acrylic DNS Proxy service:

  1. Start
  2. Programs
  3. Acrilic DNS Proxy
  4. Config
  5. Restart Acrylic Service

You will also need to adjust your DNS setting in you network interface settings:

  1. Start
  2. Control Panel
  3. Network and Internet
  4. Network Connections
  5. Local Area Connection Properties
  6. TCP/IPv4

Set "Use the following DNS server address":

Preferred DNS Server: 127.0.0.1

If you then combine this answer with jeremyasnyder's answer (using VirtualDocumentRoot) you can then automatically setup domains/virtual hosts by simply creating a directory.

Can (domain name) subdomains have an underscore "_" in it?

Just created local project (with vagrant) and it was working perfectly when accessed over ip address. Then I added some_name.test to hosts file and tried accessing it that way, but I was getting "bad request - 400" all the time. Wasted hours until I figured out that just changing domain name to some-name.test solves the problem. So at least locally on Mac OS it's not working.

Open a selected file (image, pdf, ...) programmatically from my Android Application?

Try the below code. I am using this code for opening a PDF file. You can use it for other files also.

File file = new File(Environment.getExternalStorageDirectory(),
                     "Report.pdf");
Uri path = Uri.fromFile(file);
Intent pdfOpenintent = new Intent(Intent.ACTION_VIEW);
pdfOpenintent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
pdfOpenintent.setDataAndType(path, "application/pdf");
try {
    startActivity(pdfOpenintent);
}
catch (ActivityNotFoundException e) {

}

If you want to open files, you can change the setDataAndType(path, "application/pdf"). If you want to open different files with the same intent, you can use Intent.createChooser(intent, "Open in...");. For more information, look at How to make an intent with multiple actions.

wp_nav_menu change sub-menu class name?

replace class:

echo str_replace('sub-menu', 'menu menu_sub', wp_nav_menu( array(
    'echo' => false,
    'theme_location' => 'sidebar-menu',
    'items_wrap' => '<ul class="menu menu_sidebar">%3$s</ul>' 
  ) )
);

Save bitmap to location

I would also like to save a picture. But my problem(?) is that I want to save it from a bitmap that ive drawed.

I made it like this:

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
            case R.id.save_sign:      

                myView.save();
                break;

            }
            return false;    

    }

public void save() {
            String filename;
            Date date = new Date(0);
            SimpleDateFormat sdf = new SimpleDateFormat ("yyyyMMddHHmmss");
            filename =  sdf.format(date);

            try{
                 String path = Environment.getExternalStorageDirectory().toString();
                 OutputStream fOut = null;
                 File file = new File(path, "/DCIM/Signatures/"+filename+".jpg");
                 fOut = new FileOutputStream(file);

                 mBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
                 fOut.flush();
                 fOut.close();

                 MediaStore.Images.Media.insertImage(getContentResolver()
                 ,file.getAbsolutePath(),file.getName(),file.getName());

            }catch (Exception e) {
                e.printStackTrace();
            }

 }

What does enumerate() mean?

As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.

So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].

Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).

for index, value in enumerate(joint_values):
   if index == 3:
       continue

   # Do something with the other `value`

So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).

Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:

def enumerate(l, start=0):
    return zip(range(start, len(l) + start), l)

Example:

l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)

Output:

[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]

As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.

Telling Python to save a .txt file to a certain directory on Windows and Mac

If you want to save a file to a particular DIRECTORY and FILENAME here is some simple example. It also checks to see if the directory has or has not been created.

import os.path
directory = './html/'
filename = "file.html"
file_path = os.path.join(directory, filename)
if not os.path.isdir(directory):
    os.mkdir(directory)
file = open(file_path, "w")
file.write(html)
file.close()

Hope this helps you!

Remove commas from the string using JavaScript

To remove the commas, you'll need to use replace on the string. To convert to a float so you can do the maths, you'll need parseFloat:

var total = parseFloat('100,000.00'.replace(/,/g, '')) +
            parseFloat('500,000.00'.replace(/,/g, ''));

SQL Server: Cannot insert an explicit value into a timestamp column

If you have a need to copy the exact same timestamp data, change the data type in the destination table from timestamp to binary(8) -- i used varbinary(8) and it worked fine.

This obviously breaks any timestamp functionality in the destination table, so make sure you're ok with that first.

How do I make a MySQL database run completely in memory?

It is also possible to place the MySQL data directory in a tmpfs in thus speeding up the database write and read calls. It might not be the most efficient way to do this but sometimes you can't just change the storage engine.

Here is my fstab entry for my MySQL data directory

none            /opt/mysql/server-5.6/data  tmpfs   defaults,size=1000M,uid=999,gid=1000,mode=0700          0       0

You may also want to take a look at the innodb_flush_log_at_trx_commit=2 setting. Maybe this will speedup your MySQL sufficently.

innodb_flush_log_at_trx_commit changes the mysql disk flush behaviour. When set to 2 it will only flush the buffer every second. By default each insert will cause a flush and thus cause more IO load.

Best practices for Storyboard login screen, handling clearing of data upon logout

Doing this from the app delegate is NOT recommended. AppDelegate manages the app life cycle that relate to launching, suspending, terminating and so on. I suggest doing this from your initial view controller in the viewDidAppear. You can self.presentViewController and self.dismissViewController from the login view controller. Store a bool key in NSUserDefaults to see if it's launching for the first time.

Copy table without copying data

SHOW CREATE TABLE bar;

you will get a create statement for that table, edit the table name, or anything else you like, and then execute it.

This will allow you to copy the indexes and also manually tweak the table creation.

You can also run the query within a program.

XAMPP Apache Webserver localhost not working on MAC OS

This is what helped me:

sudo apachectl stop

This command killed Apache server that was pre-installed on MAC OS X.

How to fetch the dropdown values from database and display in jsp

how to fetch the dropdown values from database and display in jsp:

Dynamically Fetch data from Mysql to (drop down) select option in Jsp. This post illustrates, to fetch the data from the mysql database and display in select option element in Jsp. You should know the following post before going through this post i.e :

How to Connect Mysql database to jsp.

How to create database in MySql and insert data into database. Following database is used, to illustrate ‘Dynamically Fetch data from Mysql to (drop down)

select option in Jsp’ :

id  City
1   London
2   Bangalore
3   Mumbai
4   Paris

Following codes are used to insert the data in the MySql database. Database used is “City” and username = “root” and password is also set as “root”.

Create Database city;
Use city;

Create table new(id int(4), city varchar(30));

insert into new values(1, 'LONDON');
insert into new values(2, 'MUMBAI');
insert into new values(3, 'PARIS');
insert into new values(4, 'BANGLORE');

Here is the code to Dynamically Fetch data from Mysql to (drop down) select option in Jsp:

<%@ page import="java.sql.*" %>
<%ResultSet resultset =null;%>

<HTML>
<HEAD>
    <TITLE>Select element drop down box</TITLE>
</HEAD>

<BODY BGCOLOR=##f89ggh>

<%
    try{
//Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = 
         DriverManager.getConnection
            ("jdbc:mysql://localhost/city?user=root&password=root");

       Statement statement = connection.createStatement() ;

       resultset =statement.executeQuery("select * from new") ;
%>

<center>
    <h1> Drop down box or select element</h1>
        <select>
        <%  while(resultset.next()){ %>
            <option><%= resultset.getString(2)%></option>
        <% } %>
        </select>
</center>

<%
//**Should I input the codes here?**
        }
        catch(Exception e)
        {
             out.println("wrong entry"+e);
        }
%>

</BODY>
</HTML>

enter image description here

error: This is probably not a problem with npm. There is likely additional logging output above

Delete your package-lock.json file and node_modules folder. Then do npm cache clean

npm cache clean --force

do npm install

again and run

How to set conditional breakpoints in Visual Studio?

Set a breakpoint as usual. Right click it. Click Condition.

Perl: function to trim string leading and trailing whitespace

I also use a positive lookahead to trim repeating spaces inside the text:

s/^\s+|\s(?=\s)|\s+$//g

org.hibernate.MappingException: Could not determine type for: java.util.List, at table: College, for columns: [org.hibernate.mapping.Column(students)]

Adding the @ElementCollection to the List field solved this issue:

    @Column
    @ElementCollection(targetClass=Integer.class)
    private List<Integer> countries;

Stock ticker symbol lookup API

The NASDAQ site hosts separate CSV lists for ticker symbols in each stock exchange (NYSE, AMEX and NASDAQ). You need to complete the captcha and get the CSV dump.

http://www.nasdaq.com/screening/company-list.aspx

Regex any ASCII character

. stands for any char, so you write your regex like this:

xxx.+xxx

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

Lambda function in list comprehensions

The big difference is that the first example actually invokes the lambda f(x), while the second example doesn't.

Your first example is equivalent to [(lambda x: x*x)(x) for x in range(10)] while your second example is equivalent to [f for x in range(10)].

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

How do I wait until Task is finished in C#?

async Task<int> AccessTheWebAsync()  
{   
    // You need to add a reference to System.Net.Http to declare client.  
    HttpClient client = new HttpClient();  

    // GetStringAsync returns a Task<string>. That means that when you await the  
    // task you'll get a string (urlContents).  
    Task<string> getStringTask = 

    client.GetStringAsync("http://msdn.microsoft.com");  

    // You can do work here that doesn't rely on the string from GetStringAsync.  
    DoIndependentWork();  

    // The await operator suspends AccessTheWebAsync.  
    //  - AccessTheWebAsync can't continue until getStringTask is complete.  
    //  - Meanwhile, control returns to the caller of AccessTheWebAsync.  
    //  - Control resumes here when getStringTask is complete.   
    //  - The await operator then retrieves the string result from 
    getStringTask.  
    string urlContents = await getStringTask;  

    // The return statement specifies an integer result.  
    // Any methods that are awaiting AccessTheWebenter code hereAsync retrieve the length 
    value.  
    return urlContents.Length;  
}  

Closing Bootstrap modal onclick

You can hide the modal and popup the window to review the carts in validateShipping() function itself.

function validateShipping(){
...
...
$('#product-options').modal('hide');
//pop the window to select items
}

What is the difference between a symbolic link and a hard link?

Simply , Hard link : is just add new name to a file, that's mean , a file can have many name in the same time, all name are equal to each other, no one preferred, Hard link is not mean to copy the all contents of file and make new file is not that, it just create an alternative name to be known..

Symbolic link (symlink) : is a file pointer to another file, if the symbolic link points to an existing file which is later deleted, the symbolic link continues to point to the same file name even though the name no longer names any file.

How to show SVG file on React Native?

I used the following solution:

  1. Convert .svg image to JSX with https://svg2jsx.herokuapp.com/
  2. Convert the JSX to react-native-svg component with https://svgr.now.sh/ (check the "React Native checkbox)

Responsive font size in CSS

I've been playing around with ways to overcome this issue, and believe I have found a solution:

If you can write your application for Internet Explorer 9 (and later) and all other modern browsers that support CSS calc(), rem units, and vmin units. You can use this to achieve scalable text without media queries:

body {
  font-size: calc(0.75em + 1vmin);
}

Here it is in action: http://codepen.io/csuwldcat/pen/qOqVNO

Laravel Migration table already exists, but I want to add new not the older

  1. Drop all table database
  2. Update two file in folder database/migrations/: 2014_10_12_000000_create_users_table.php, 2014_10_12_100000_create_password_resets_table.php

2014_10_12_100000_create_password_resets_table.php

Schema::create('password_resets', function (Blueprint $table) {
     $table->string('email');
     $table->string('token');
     $table->timestamp('created_at')->nullable();
});

2014_10_12_000000_create_users_table.php

Schema::create('users', function (Blueprint $table) {
     $table->increments('id');
     $table->string('name');
     $table->string('email');
     $table->string('password');
     $table->rememberToken();
     $table->timestamps();
});

Java 6 Unsupported major.minor version 51.0

I face the same problem and solved by adding the JAVA_HOME variable with updated version of java in my Ubuntu Machine(16.04). if you are using "Apache Maven 3.3.9" You need to upgrade your JAVA_HOME with java7 or more

Step to Do this

1-sudo vim /etc/environment

2-JAVA_HOME=JAVA Installation Directory (MyCase-/opt/dev/jdk1.7.0_45/)

3-Run echo $JAVA_HOME will give the JAVA_HOME set value

4-Now mvn -version will give the desired output

Apache Maven 3.3.9

Maven home: /usr/share/maven

Java version: 1.7.0_45, vendor: Oracle Corporation

Java home: /opt/dev/jdk1.7.0_45/jre

Default locale: en_US, platform encoding: UTF-8

OS name: "linux", version: "4.4.0-36-generic", arch: "amd64", family: "unix"

git: diff between file in local repo and origin

If [remote-path] and [local-path] are the same, you can do

$ git fetch origin master
$ git diff origin/master -- [local-path]

Note 1: The second command above will compare against the locally stored remote tracking branch. The fetch command is required to update the remote tracking branch to be in sync with the contents of the remote server. Alternatively, you can just do

$ git diff master:<path-or-file-name>

Note 2: master can be replaced in the above examples with any branch name

SQLAlchemy equivalent to SQL "LIKE" statement

Adding to the above answer, whoever looks for a solution, you can also try 'match' operator instead of 'like'. Do not want to be biased but it perfectly worked for me in Postgresql.

Note.query.filter(Note.message.match("%somestr%")).all()

It inherits database functions such as CONTAINS and MATCH. However, it is not available in SQLite.

For more info go Common Filter Operators

JList add/remove Item

The problem is

listModel.addElement(listaRosa.getSelectedValue());
listModel.removeElement(listaRosa.getSelectedValue());

you may be adding an element and immediatly removing it since both add and remove operations are on the same listModel.

Try

private void aggiungiTitolareButtonActionPerformed(java.awt.event.ActionEvent evt) {                                                       

    DefaultListModel lm2 = (DefaultListModel) listaTitolari.getModel();
    DefaultListModel lm1  = (DefaultListModel) listaRosa.getModel();
    if(lm2 == null)
    {
        lm2 = new DefaultListModel();
        listaTitolari.setModel(lm2);
    }
    lm2.addElement(listaTitolari.getSelectedValue());
    lm1.removeElement(listaTitolari.getSelectedValue());        
} 

Constructor overloading in Java - best practice

Well, here's an example for overloaded constructors.

public class Employee
{
   private String name;
   private int age;

   public Employee()
   {
      System.out.println("We are inside Employee() constructor");
   }

   public Employee(String name)
   {
      System.out.println("We are inside Employee(String name) constructor");
      this.name = name;
   }

   public Employee(String name, int age)
   {
      System.out.println("We are inside Employee(String name, int age) constructor");
      this.name = name;
      this.age = age;
   }

   public Employee(int age)
   {
      System.out.println("We are inside Employee(int age) constructor");
      this.age = age; 
   }

   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   public int getAge()
   {
      return age;
   }

   public void setAge(int age)
   {
      this.age = age;
   }
}

In the above example you can see overloaded constructors. Name of the constructors is same but each constructors has different parameters.

Here are some resources which throw more light on constructor overloading in java,

Constructors.

Constructor explanation.

How do I disable the resizable property of a textarea?

You can simply disable the textarea property like this:

textarea {
    resize: none;
}

To disable vertical or horizontal resizing, use

resize: vertical;

or

resize: horizontal;

How to redirect page after click on Ok button on sweet alert?

_x000D_
_x000D_
setTimeout(function () { _x000D_
swal({_x000D_
  title: "Wow!",_x000D_
  text: "Message!",_x000D_
  type: "success",_x000D_
  confirmButtonText: "OK"_x000D_
},_x000D_
function(isConfirm){_x000D_
  if (isConfirm) {_x000D_
    window.location.href = "//stackoverflow.com";_x000D_
  }_x000D_
}); }, 1000);
_x000D_
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
_x000D_
_x000D_
_x000D_


Or you can use the build-in function timer, i.e.:

_x000D_
_x000D_
swal({_x000D_
  title: "Success!",_x000D_
  text: "Redirecting in 2 seconds.",_x000D_
  type: "success",_x000D_
  timer: 2000,_x000D_
  showConfirmButton: false_x000D_
}, function(){_x000D_
      window.location.href = "//stackoverflow.com";_x000D_
});
_x000D_
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>_x000D_
  <script src="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert-dev.js"></script>_x000D_
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.css">
_x000D_
_x000D_
_x000D_

Lambda expression to convert array/List of String to array/List of Integers

In addition - control when string array doesn't have elements:

Arrays.stream(from).filter(t -> (t != null)&&!("".equals(t))).map(func).toArray(generator) 

Best way to convert IList or IEnumerable to Array

I feel like reinventing the wheel...

public static T[] ConvertToArray<T>(this IEnumerable<T> enumerable)
{
    if (enumerable == null)
        throw new ArgumentNullException("enumerable");

    return enumerable as T[] ?? enumerable.ToArray();
}

How to convert An NSInteger to an int?

I'm not sure about the circumstances where you need to convert an NSInteger to an int.

NSInteger is just a typedef:

NSInteger Used to describe an integer independently of whether you are building for a 32-bit or a 64-bit system.

#if __LP64__ || TARGET_OS_EMBEDDED || TARGET_OS_IPHONE || TARGET_OS_WIN32 || NS_BUILD_32_LIKE_64 
typedef long NSInteger;
#else
typedef int NSInteger;
#endif

You can use NSInteger any place you use an int without converting it.

text-align:center won't work with form <label> tag (?)

label is an inline element so its width is equal to the width of the text it contains. The browser is actually displaying the label with text-align:center but since the label is only as wide as the text you don't notice.

The best thing to do is to apply a specific width to the label that is greater than the width of the content - this will give you the results you want.

How do I select an element that has a certain class?

The CSS :first-child selector allows you to target an element that is the first child element within its parent.

element:first-child { style_properties }
table:first-child { style_properties }

Get a resource using getResource()

One thing to keep in mind is that the relevant path here is the path relative to the file system location of your class... in your case TestGameTable.class. It is not related to the location of the TestGameTable.java file.
I left a more detailed answer here... where is resource actually located

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

I know this already has a great answer by BalusC but here is a little trick I use to get the container to tell me the correct clientId.

  1. Remove the update on your component that is not working
  2. Put a temporary component with a bogus update within the component you were trying to update
  3. hit the page, the servlet exception error will tell you the correct client Id you need to reference.
  4. Remove bogus component and put correct clientId in the original update

Here is code example as my words may not describe it best.

<p:tabView id="tabs">
    <p:tab id="search" title="Search">                        
        <h:form id="insTable">
            <p:dataTable id="table" var="lndInstrument" value="#{instrumentBean.instruments}">
                <p:column>
                    <p:commandLink id="select"

Remove the failing update within this component

 oncomplete="dlg.show()">
                        <f:setPropertyActionListener value="#{lndInstrument}" 
                                        target="#{instrumentBean.selectedInstrument}" />
                        <h:outputText value="#{lndInstrument.name}" />
                    </p:commandLink>                                    
                </p:column>
            </p:dataTable>
            <p:dialog id="dlg" modal="true" widgetVar="dlg">
                <h:panelGrid id="display">

Add a component within the component of the id you are trying to update using an update that will fail

   <p:commandButton id="BogusButton" update="BogusUpdate"></p:commandButton>

                    <h:outputText value="Name:" />
                    <h:outputText value="#{instrumentBean.selectedInstrument.name}" />
                </h:panelGrid>
            </p:dialog>                            
        </h:form>
    </p:tab>
</p:tabView>

Hit this page and view the error. The error is: javax.servlet.ServletException: Cannot find component for expression "BogusUpdate" referenced from tabs:insTable: BogusButton

So the correct clientId to use would then be the bold plus the id of the target container (display in this case)

tabs:insTable:display

Why does AngularJS include an empty option in select?

i had the same problem, i (removed "ng-model") changed this :

<select ng-model="mapayear" id="mapayear" name="mapayear" style="  display:inline-block !important;  max-width: 20%;" class="form-control">
  <option id="removable" hidden> Selecione u </option>
    <option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}
</option>
</select>

to this:

<select id="mapayear" name="mapayear" style="  display:inline-block !important;  max-width: 20%;" class="form-control">
  <option id="removable" hidden> Selecione u </option>
    <option selected ng-repeat="x in anos" value="{{ x.ano }}">{{ x.ano }}
</option>
</select>

now its working, but in my case it was cause ive deleted that scope from ng.controller, check if u didn't do the same.

Bower: ENOGIT Git is not installed or not in the PATH

I also got the same problem from cmd and resolved using the following steps.

First install the https://msysgit.github.io/ (if not alredy installed). Then set the Git path as suggested by skinneejoe:

set PATH=%PATH%;C:\Program Files\Git\bin;

Or this (notice the (x86)):

set PATH=%PATH%;C:\Program Files (x86)\Git\bin;

Show datalist labels but submit the actual value

Using PHP i've found a quite simple way to do this. Guys, Just Use something like this

<input list="customers" name="customer_id" required class="form-control" placeholder="Customer Name">
            <datalist id="customers">
                <?php 
    $querySnamex = "SELECT * FROM `customer` WHERE fname!='' AND lname!='' order by customer_id ASC";
    $resultSnamex = mysqli_query($con,$querySnamex) or die(mysql_error());

                while ($row_this = mysqli_fetch_array($resultSnamex)) {
                    echo '<option data-value="'.$row_this['customer_id'].'">'.$row_this['fname'].' '.$row_this['lname'].'</option>
                    <input type="hidden" name="customer_id_real" value="'.$row_this['customer_id'].'" id="answerInput-hidden">';
                }

                 ?>
            </datalist>

The Code Above lets the form carry the id of the option also selected.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Linq to SQL how to do "where [column] in (list of values)"

Here is how I do it by using HashSet

        HashSet<String> hs = new HashSet<string>(new String[] { "Pluto", "Earth", "Neptune" });
        String[] arr =
        {
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            "Pluto",
            "Earth",
            "Neptune",
            "Jupiter",
            "Saturn",
            "Mercury",
            // etc.
        };
        ICollection<String> coll = arr;

        String[] arrStrFiltered = coll.Where(str => hs.Contains(str)).ToArray();

HashSet is basically almost to O(1) so your complexity remains O(n).

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

Continue For loop

you can do that by simple way, simply change the variable value that used in for loop to the end value as shown in example

_x000D_
_x000D_
Sub TEST_ONLY()
        For i = 1 To 10
            ActiveSheet.Cells(i, 1).Value = i
            If i = 5 Then
                i = 10
            End If
        Next i
End Sub
_x000D_
_x000D_
_x000D_

How to define Gradle's home in IDEA?

Installed on a Mac via Homebrew, the path

/usr/local/opt/gradle/libexec

is preferable to

/usr/local/Cellar/gradle/X.X/libexec

since the former will survive version upgrades.

Proper MIME type for .woff2 fonts

Apache

In Apache, you can add the woff2 mime type via your .htaccess file as stated by this link.

AddType  application/font-woff2  .woff2

IIS

In IIS, simply add the following mimeMap tag into your web.config file inside the staticContent tag.

<configuration>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />

How do I scroll to an element within an overflowed Div?

This is my own plugin (will position the element in top of the the list. Specially for overflow-y : auto. May not work with overflow-x!):

NOTE: elem is the HTML selector of an element which the page will be scrolled to. Anything supported by jQuery, like: #myid, div.myclass, $(jquery object), [dom object], etc.

jQuery.fn.scrollTo = function(elem, speed) { 
    $(this).animate({
        scrollTop:  $(this).scrollTop() - $(this).offset().top + $(elem).offset().top 
    }, speed == undefined ? 1000 : speed); 
    return this; 
};

If you don't need it to be animated, then use:

jQuery.fn.scrollTo = function(elem) { 
    $(this).scrollTop($(this).scrollTop() - $(this).offset().top + $(elem).offset().top); 
    return this; 
};

How to use:

$("#overflow_div").scrollTo("#innerItem");
$("#overflow_div").scrollTo("#innerItem", 2000); //custom animation speed 

Note: #innerItem can be anywhere inside #overflow_div. It doesn't really have to be a direct child.

Tested in Firefox (23) and Chrome (28).

If you want to scroll the whole page, check this question.

Rails: How to run `rails generate scaffold` when the model already exists?

Great answer by Lee Jarvis, this is just the command e.g; we already have an existing model called User:

rails g scaffold_controller User

If input value is blank, assign a value of "empty" with Javascript

You can do this:

var getValue  = function (input, defaultValue) {
    return input.value || defaultValue;
};

How to read a specific line using the specific line number from a file in Java?

You can also take a look at LineNumberReader, subclass of BufferedReader. Along with the readline method, it also has setter/getter methods to access line number. Very useful to keep track of the number of lines read, while reading data from file.

Auto-refreshing div with jQuery - setTimeout or another method?

Another modification:

function update() {
  $.get("response.php", function(data) {
    $("#some_div").html(data);
    window.setTimeout(update, 10000);
  });
}

The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.

Also, if the server fails to respond, it won't keep trying.

I've used a similar method in the past using .ajax to handle even more complex behaviour:

function update() {
  $("#notice_div").html('Loading..'); 
  $.ajax({
    type: 'GET',
    url: 'response.php',
    timeout: 2000,
    success: function(data) {
      $("#some_div").html(data);
      $("#notice_div").html(''); 
      window.setTimeout(update, 10000);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#notice_div").html('Timeout contacting server..');
      window.setTimeout(update, 60000);
    }
}

This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.

This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.

Get Context in a Service

Service extends ContextWrapper which extends Context. Hence the Service is a Context. Use 'this' keyword in the service.

Sum values from an array of key-value pairs in JavaScript

You can use the native map method for Arrays. map Method (Array) (JavaScript)

var myData = new Array(['2013-01-22', 0], ['2013-01-29', 0], ['2013-02-05', 0],
             ['2013-02-12', 0], ['2013-02-19', 0], ['2013-02-26', 0], 
             ['2013-03-05', 0], ['2013-03-12', 0], ['2013-03-19', 0], 
             ['2013-03-26', 0], ['2013-04-02', 21], ['2013-04-09', 2]);
var a = 0;
myData.map( function(aa){ a += aa[1];  return a; });

a is your result

Chart creating dynamically. in .net, c#

Try to include these lines on your code, after mych.Visible = true;:

ChartArea chA = new ChartArea();
mych.ChartAreas.Add(chA);

A message body writer for Java type, class myPackage.B, and MIME media type, application/octet-stream, was not found

You need to specify the @Provider that @Produces(MediaType.APPLICATION_XML) from B.class
An add the package of your MessageBodyWriter<B.class> to your /WEB_INF/web.xml as:

<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>
your.providers.package
</param-value>
</init-param>

Jquery date picker z-index issue

Based in marksyzm answer, this worked for me:

$('input').datepicker({
    beforeShow:function(input) {
        $(input).css({
            "position": "relative",
            "z-index": 999999
        });
    }
});

How to connect to LocalDb

I am totally unable to connect to localdb with any tool including MSSMA, sqlcmd, etc. You would think Microsoft would document this, but I find nothing on MSDN. I have v12 and tried (localdb)\v12.0 and that didn't work. Issuing the command sqllocaldb i MSSQLLocalDB shows that the local instance is running, but there is no way to connect to it.

c:\> sqllocaldb i MSSQLLocalDB
Name:               MSSQLLocalDB
Version:            12.0.2000.8
Shared name:
Owner:              CWOLF-PC\cwolf
Auto-create:        Yes
State:              Running
Last start time:    6/12/2014 8:34:11 AM
Instance pipe name: np:\\.\pipe\LOCALDB#C86052DD\tsql\query
c:\>
c:\> sqlcmd -L

Servers:
    ;UID:Login ID=?;PWD:Password=?;Trusted_Connection:Use Integrated Security=?;
*APP:AppName=?;*WSID:WorkStation ID=?;

I finally figured it out!! the connect string is (localdb)\MSSQLLocalDB, e.g.:

$ sqlcmd -S \(localdb\)\\MSSQLLocalDB
1> select 'hello!'
2> go

------
hello!

(1 rows affected)    

Redraw datatables after using ajax to refresh the table content?

Use this:

var table = $(selector).dataTables();
table.api().draw(false);

or

var table = $(selector).DataTables();
table.draw(false);

PRINT statement in T-SQL

Query Analyzer buffers messages. The PRINT and RAISERROR statements both use this buffer, but the RAISERROR statement has a WITH NOWAIT option. To print a message immediately use the following:

RAISERROR ('Your message', 0, 1) WITH NOWAIT

RAISERROR will only display 400 characters of your message and uses a syntax similar to the C printf function for formatting text.

Please note that the use of RAISERROR with the WITH NOWAIT option will flush the message buffer, so all previously buffered information will be output also.

How to have multiple conditions for one if statement in python

Might be a bit odd or bad practice but this is one way of going about it.

(arg1, arg2, arg3) = (1, 2, 3)

if (arg1 == 1)*(arg2 == 2)*(arg3 == 3):
    print('Example.')

Anything multiplied by 0 == 0. If any of these conditions fail then it evaluates to false.

Codeigniter displays a blank page instead of error messages

In system/core/Common.php there is an exception handler, with a block of code that looks like this:

 // We don't bother with "strict" notices since they tend to fill up
 // the log file with excess information that isn't normally very helpful.
if ($severity == E_STRICT)
{
    return;
}

By removing the if and the return and the incorrect comment, I was able to get an error message, instead of just a blank page. This project isn't using the most recent version of CodeIgniter, hopefully they've fixed this bug by now.

Python List vs. Array - when to use?

Basically, Python lists are very flexible and can hold completely heterogeneous, arbitrary data, and they can be appended to very efficiently, in amortized constant time. If you need to shrink and grow your list time-efficiently and without hassle, they are the way to go. But they use a lot more space than C arrays, in part because each item in the list requires the construction of an individual Python object, even for data that could be represented with simple C types (e.g. float or uint64_t).

The array.array type, on the other hand, is just a thin wrapper on C arrays. It can hold only homogeneous data (that is to say, all of the same type) and so it uses only sizeof(one object) * length bytes of memory. Mostly, you should use it when you need to expose a C array to an extension or a system call (for example, ioctl or fctnl).

array.array is also a reasonable way to represent a mutable string in Python 2.x (array('B', bytes)). However, Python 2.6+ and 3.x offer a mutable byte string as bytearray.

However, if you want to do math on a homogeneous array of numeric data, then you're much better off using NumPy, which can automatically vectorize operations on complex multi-dimensional arrays.

To make a long story short: array.array is useful when you need a homogeneous C array of data for reasons other than doing math.

Getting "project" nuget configuration is invalid error

Simply restarting Visual Studio worked for me.

How to clear all <div>s’ contents inside a parent <div>?

$("#masterdiv div[id^='childdiv']").each(function(el){$(el).empty();});

or

$("#masterdiv").find("div[id^='childdiv']").each(function(el){$(el).empty();});