Programs & Examples On #Theorem proving

Theorem proving, currently the most well-developed subfield of automated reasoning, is the proving of mathematical theorems by a computer program.

How to change Java version used by TOMCAT?

When you open catalina.sh / catalina.bat, you can see :

Environment Variable Prequisites

JAVA_HOME Must point at your Java Development Kit installation.

So, set your environment variable JAVA_HOME to point to Java 6. Also make sure JRE_HOME is pointing to the same target, if it is set.

Update: since you are on Windows, see here for how to manage your environment variables

How to store images in mysql database using php

<!-- 
//THIS PROGRAM WILL UPLOAD IMAGE AND WILL RETRIVE FROM DATABASE. UNSING BLOB
(IF YOU HAVE ANY QUERY CONTACT:[email protected])


CREATE TABLE  `images` (
  `id` int(100) NOT NULL AUTO_INCREMENT,
  `name` varchar(100) NOT NULL,
  `image` longblob NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB ;

-->
<!-- this form is user to store images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Enter the Image Name:<input type="text" name="image_name" id="" /><br />

<input name="image" id="image" accept="image/JPEG" type="file"><br /><br />
<input type="submit" value="submit" name="submit" />
</form>
<br /><br />
<!-- this form is user to display all the images-->
<form action="index.php" method="post"  enctype="multipart/form-data">
Retrive all the images:
<input type="submit" value="submit" name="retrive" />
</form>



<?php
//THIS IS INDEX.PHP PAGE
//connect to database.db name is images
        mysql_connect("", "", "") OR DIE (mysql_error());
        mysql_select_db ("") OR DIE ("Unable to select db".mysql_error());
//to retrive send the page to another page
if(isset($_POST['retrive']))
{
    header("location:search.php");

}

//to upload
if(isset($_POST['submit']))
{
if(isset($_FILES['image'])) {
        $name=$_POST['image_name'];
        $email=$_POST['mail'];
        $fp=addslashes(file_get_contents($_FILES['image']['tmp_name'])); //will store the image to fp
        }
                // our sql query
                $sql = "INSERT INTO images VALUES('null', '{$name}','{$fp}');";
                            mysql_query($sql) or die("Error in Query insert: " . mysql_error());
} 
?>



<?php
//SEARCH.PHP PAGE
    //connect to database.db name = images
         mysql_connect("localhost", "root", "") OR DIE (mysql_error());
        mysql_select_db ("image") OR DIE ("Unable to select db".mysql_error());
//display all the image present in the database

        $msg="";
        $sql="select * from images";
        if(mysql_query($sql))
        {
            $res=mysql_query($sql);
            while($row=mysql_fetch_array($res))
            {
                    $id=$row['id'];
                    $name=$row['name'];
                    $image=$row['image'];

                  $msg.= '<a href="search.php?id='.$id.'"><img src="data:image/jpeg;base64,'.base64_encode($row['image']). ' " />   </a>';

            }
        }
        else
            $msg.="Query failed";
?>
<div>
<?php
echo $msg;
?>

Traverse a list in reverse order in Python

Also, you could use either "range" or "count" functions. As follows:

a = ["foo", "bar", "baz"]
for i in range(len(a)-1, -1, -1):
    print(i, a[i])

3 baz
2 bar
1 foo

You could also use "count" from itertools as following:

a = ["foo", "bar", "baz"]
from itertools import count, takewhile

def larger_than_0(x):
    return x > 0

for x in takewhile(larger_than_0, count(3, -1)):
    print(x, a[x-1])

3 baz
2 bar
1 foo

Visual Studio Code Tab Key does not insert a tab

As of December 2018 on macOS Mojave 10.14.2 using VSCode 1.29.1 the default keybinding for 'Toggle Tab Key Moves Focus' is set to Command+Shift+M. If you got stuck with this, using that key combo should fix the issue.

Do Command+K Command+S to pull up the Hotkeys Settings and then search for Toggle Tab Key Moves Focus or editor.action.toggleTabFocusMode if you want to change the key combo.

AttributeError: Module Pip has no attribute 'main'

Edit file: C:\Users\kpate\hw6\python-zulip-api\zulip_bots\setup.py in line 108

to

rcode = pip.main(['install', '-r', req_path, '--quiet'])

do

rcode = getattr(pip, '_main', pip.main)(['install', '-r', req_path, '--quiet'])´

Notification bar icon turns white in Android 5 Lollipop

android:targetSdkVersion="20" it should be < 21.

JavaScript pattern for multiple constructors

Sometimes, default values for parameters is enough for multiple constructors. And when that doesn't suffice, I try to wrap most of the constructor functionality into an init(other-params) function that is called afterwards. Also consider using the factory concept to make an object that can effectively create the other objects you want.

http://en.wikipedia.org/w/index.php?title=Factory_method_pattern&oldid=363482142#Javascript

Html.HiddenFor value property not getting set

A simple answer is to use @Html.TextboxFor but place it in a div that is hidden with style. Example: In View:

<div style="display:none"> @Html.TextboxFor(x=>x.CRN) </div>

Can't bind to 'ngModel' since it isn't a known property of 'input'

Simple solution: In file app.module.ts -

Example 1

import {FormsModule} from "@angular/forms";
// Add in imports

imports: [
 BrowserModule,
 FormsModule
 ],

Example 2

If you want to use [(ngModel)] then you have to import FormsModule in app.module.ts:

import { FormsModule  } from "@angular/forms";
@NgModule({
  declarations: [
    AppComponent, videoComponent, tagDirective,
  ],
  imports: [
    BrowserModule,  FormsModule

  ],
  providers: [ApiServices],
  bootstrap: [AppComponent]
})
export class AppModule { }

How do I convert an enum to a list in C#?

/// <summary>
/// Method return a read-only collection of the names of the constants in specified enum
/// </summary>
/// <returns></returns>
public static ReadOnlyCollection<string> GetNames()
{
    return Enum.GetNames(typeof(T)).Cast<string>().ToList().AsReadOnly();   
}

where T is a type of Enumeration; Add this:

using System.Collections.ObjectModel; 

Windows command to get service status?

Using Windows Script:

Set ComputerObj = GetObject("WinNT://MYCOMPUTER")    
ComputerObj.Filter = Array("Service")    
For Each Service in ComputerObj    
    WScript.Echo "Service display name = " & Service.DisplayName    
    WScript.Echo "Service account name = " & Service.ServiceAccountName    
    WScript.Echo "Service executable   = " & Service.Path    
    WScript.Echo "Current status       = " & Service.Status    
Next

You can easily filter the above for the specific service you want.

What is the difference between exit(0) and exit(1) in C?

exit() should always be called with an integer value and non-zero values are used as error codes.

See also: Use of exit() function

Start and stop a timer PHP

As alternative, php has a built-in timer controller: new EvTimer().

It can be used to make a task scheduler, with proper handling of special cases.

This is not only the Time, but a time transport layer, a chronometer, a lap counter, just as a stopwatch but with php callbacks ;)

EvTimer watchers are simple relative timers that generate an event after a given time, and optionally repeating in regular intervals after that.

The timers are based on real time, that is, if one registers an event that times out after an hour and resets the system clock to January last year, it will still time out after(roughly) one hour.

The callback is guaranteed to be invoked only after its timeout has passed (...). If multiple timers become ready during the same loop iteration then the ones with earlier time-out values are invoked before ones of the same priority with later time-out values.

The timer itself will do a best-effort at avoiding drift, that is, if a timer is configured to trigger every 10 seconds, then it will normally trigger at exactly 10 second intervals. If, however, the script cannot keep up with the timer because it takes longer than those 10 seconds to do) the timer will not fire more than once per event loop iteration.

The first two parameters allows to controls the time delay before execution, and the number of iterations.

The third parameter is a callback function, called at each iteration.

after

    Configures the timer to trigger after after seconds.

repeat

    If repeat is 0.0 , then it will automatically be stopped once the timeout is reached.
    If it is positive, then the timer will automatically be configured to trigger again every repeat seconds later, until stopped manually.

https://www.php.net/manual/en/class.evtimer.php

https://www.php.net/manual/en/evtimer.construct.php

$w2 = new EvTimer(2, 1, function ($w) {
    echo "is called every second, is launched after 2 seconds\n";
    echo "iteration = ", Ev::iteration(), PHP_EOL;

    // Stop the watcher after 5 iterations
    Ev::iteration() == 5 and $w->stop();
    // Stop the watcher if further calls cause more than 10 iterations
    Ev::iteration() >= 10 and $w->stop();
});

We can of course easily create this with basic looping and some tempo with sleep(), usleep(), or hrtime(), but new EvTimer() allows cleans and organized multiples calls, while handling special cases like overlapping.

"No resource identifier found for attribute 'showAsAction' in package 'android'"

Add "android-support-v7-appcompat.jar" to Android Private Libraries

File content into unix variable with newlines

The envdir utility provides an easy way to do this. envdir uses files to represent environment variables, with file names mapping to env var names, and file contents mapping to env var values. If the file contents contain newlines, so will the env var.

See https://pypi.python.org/pypi/envdir

Groovy method with optional parameters

Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:

def someMethod(def args) {
    println "MANDATORY1=${args.mandatory1}"
    println "MANDATORY2=${args.mandatory2}"
    println "OPTIONAL1=${args?.optional1}"
    println "OPTIONAL2=${args?.optional2}"
}

someMethod mandatory1:1, mandatory2:2, optional1:3

with the output:

MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null

This looks nicer and the advantage of this is that you can change the order of the parameters as you like.

How to check if IsNumeric

You could write an extension method:

public static class Extension
{
    public static bool IsNumeric(this string s)
    {
        float output;
        return float.TryParse(s, out output);
    }
}

Summing elements in a list

Python iterable can be summed like so - [sum(range(10)[1:])] . This sums all elements from the list except the first element.

>>> atuple = (1,2,3,4,5)
>>> sum(atuple)
15
>>> alist = [1,2,3,4,5]
>>> sum(alist)
15

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

How to convert Integer to int?

Another simple way would be:

Integer i = new Integer("10");

if (i != null)
    int ip = Integer.parseInt(i.toString());

Drawable image on a canvas

also you can use this way. it will change your big drawble fit to your canvas:

Resources res = getResources();
Bitmap bitmap = BitmapFactory.decodeResource(res, yourDrawable);
yourCanvas.drawBitmap(bitmap, 0, 0, yourPaint);

How do I shrink my SQL Server Database?

Not sure how practical this would be, and depending on the size of the database, number of tables and other complexities, but I:

  1. defrag the physical drive
  2. create a new database according to my requirements, space, percentage growth, etc
  3. use the simple ssms task to import all tables from the old db to the new db
  4. script out the indexes for all tables on the old database, and then recreate the indexes on the new database. expand as needed for foreign keys etc.
  5. rename databases as needed, confirm successful, delete old

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

Try closing all the FileOutputStream/FileInputStream you've opened earlier in other methods ,then try deleting ,worked like a charm.

What is simplest way to read a file into String?

From Java 7 (API Description) onwards you can do:

new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

Where filePath is a String representing the file you want to load.

laravel Unable to prepare route ... for serialization. Uses Closure

the solustion when we use routes like this:

Route::get('/', function () {
    return view('welcome');
});

laravel call them Closure so you cant optimize routes uses as Closures you must route to controller to use php artisan optimize

Pass a datetime from javascript to c# (Controller)

try this

var date = new Date();    
$.ajax(
   {
       type: "POST",
       url: "/Group/Refresh",
       contentType: "application/json; charset=utf-8",
       data: "{ 'MyDate': " + date.getTimezoneOffset() + " }",
       success: function (result) {
           //do something
       },
       error: function (req, status, error) {
           //error                        
       }
   });

In C#

DateTime.Now.ToUniversalTime().AddMinutes(double.Parse(MyDate)).ToString();

Python mysqldb: Library not loaded: libmysqlclient.18.dylib

go to http://dev.mysql.com/downloads/connector/c/ and download MySQL Connector/C. after getting the package, make a new directory 'mysql', uncompress the Mysql Connector file under directory mysql, then under mysql, make another empty directory 'build'.we will use 'build' to build MySQL Connector/C. cd build && cmake ../your-MySQL-Connector-source-dir make && make install after make install, you will get a directory named mysql under /usr/local. it contains all the headers and libs you need.go to this dirctory, and copy the headers and libs to corresponding locations.

How can I shutdown Spring task executor/scheduler pools before all other beans in the web app are destroyed?

If it is going to be a web based application, you can also use the ServletContextListener interface.

public class SLF4JBridgeListener implements ServletContextListener {

   @Autowired 
   ThreadPoolTaskExecutor executor;

   @Autowired 
   ThreadPoolTaskScheduler scheduler;

    @Override
    public void contextInitialized(ServletContextEvent sce) {

    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
         scheduler.shutdown();
         executor.shutdown();     

    }

}

How to get anchor text/href on click using jQuery?

Without jQuery:

You don't need jQuery when it is so simple to do this using pure JavaScript. Here are two options:

  • Method 1 - Retrieve the exact value of the href attribute:

    Select the element and then use the .getAttribute() method.

    This method does not return the full URL, instead it retrieves the exact value of the href attribute.

    _x000D_
    _x000D_
    var anchor = document.querySelector('a'),_x000D_
        url = anchor.getAttribute('href');_x000D_
    _x000D_
    alert(url);
    _x000D_
    <a href="/relative/path.html"></a>
    _x000D_
    _x000D_
    _x000D_


  • Method 2 - Retrieve the full URL path:

    Select the element and then simply access the href property.

    This method returns the full URL path.

    In this case: http://stacksnippets.net/relative/path.html.

    _x000D_
    _x000D_
    var anchor = document.querySelector('a'),_x000D_
        url = anchor.href;_x000D_
    _x000D_
    alert(url);
    _x000D_
    <a href="/relative/path.html"></a>
    _x000D_
    _x000D_
    _x000D_


As your title implies, you want to get the href value on click. Simply select an element, add a click event listener and then return the href value using either of the aforementioned methods.

_x000D_
_x000D_
var anchor = document.querySelector('a'),_x000D_
    button = document.getElementById('getURL'),_x000D_
    url = anchor.href;_x000D_
_x000D_
button.addEventListener('click', function (e) {_x000D_
  alert(url);_x000D_
});
_x000D_
<button id="getURL">Click me!</button>_x000D_
<a href="/relative/path.html"></a>
_x000D_
_x000D_
_x000D_

Echo tab characters in bash script

From the bash man page:

Words of the form $'string' are treated specially. The word expands to string, with backslash-escaped characters replaced as specified by the ANSI C standard.

So you can do this:

echo $'hello\tworld'

What do 3 dots next to a parameter type mean in Java?

Also to shed some light, it is important to know that var-arg parameters are limited to one and you can't have several var-art params. For example this is illigal:

public void myMethod(String... strings, int ... ints){
// method body
}

How to test the `Mosquitto` server?

Start the Mosquitto Broker
Open the terminal and type

mosquitto_sub -h 127.0.0.1 -t topic

Open another terminal and type
mosquitto_pub -h 127.0.0.1 -t topic -m "Hello"

Now you can switch to the previous terminal and there you can able to see the "Hello" Message.One terminal acts as publisher and another one subscriber.

What is a good Hash Function?

There are two major purposes of hashing functions:

  • to disperse data points uniformly into n bits.
  • to securely identify the input data.

It's impossible to recommend a hash without knowing what you're using it for.

If you're just making a hash table in a program, then you don't need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you'd be better off using a variation of FNV. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it's more adaptable to varying input sizes.

If you're using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. The Hash Function Lounge is a good place to start.

Combination of async function + await + setTimeout

Update 2020

You can await setTimeout with Node.js 15 or above:

const timersPromises = require('timers/promises');

(async () => {
  const result = await timersPromises.setTimeout(2000, 'resolved')
  // Executed after 2 seconds
  console.log(result); // "resolved"
})()

Timers Promises API: https://nodejs.org/api/timers.html#timers_timers_promises_api (library already built in Node)


Note: Stability: 1 - Use of the feature is not recommended in production environments.

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How do I create a pause/wait function using Qt?

Small +1 to kshark27's answer to make it dynamic:

#include <QTime>

void delay( int millisecondsToWait )
{
    QTime dieTime = QTime::currentTime().addMSecs( millisecondsToWait );
    while( QTime::currentTime() < dieTime )
    {
        QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );
    }
}

What does yield mean in PHP?

This function is using yield:

function a($items) {
    foreach ($items as $item) {
        yield $item + 1;
    }
}

It is almost the same as this one without:

function b($items) {
    $result = [];
    foreach ($items as $item) {
        $result[] = $item + 1;
    }
    return $result;
}

The only one difference is that a() returns a generator and b() just a simple array. You can iterate on both.

Also, the first one does not allocate a full array and is therefore less memory-demanding.

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

How to group by week in MySQL?

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

Not overly elegant, but functional...

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

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

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


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

Mutex lock threads

A process consists of at least one thread (think of the main function). Multi threaded code will just spawn more threads. Mutexes are used to create locks around shared resources to avoid data corruption / unexpected / unwanted behaviour. Basically it provides for sequential execution in an asynchronous setup - the requirement for which stems from non-const non-atomic operations on shared data structures.

A vivid description of what mutexes would be the case of people (threads) queueing up to visit the restroom (shared resource). While one person (thread) is using the bathroom easing him/herself (non-const non-atomic operation), he/she should ensure the door is locked (mutex), otherwise it could lead to being caught in full monty (unwanted behaviour)

How to enable C# 6.0 feature in Visual Studio 2013?

Under VS2013 you can install the new compilers into the project as a nuget package. That way you don't need VS2015 or an updated build server.

https://www.nuget.org/packages/Microsoft.Net.Compilers/

Install-Package Microsoft.Net.Compilers

The package allows you to use/build C# 6.0 code/syntax. Because VS2013 doesn't natively recognize the new C# 6.0 syntax, it will show errors in the code editor window although it will build fine.

Using Resharper, you'll get squiggly lines on C# 6 features, but the bulb gives you the option to 'Enable C# 6.0 support for this project' (setting saved to .DotSettings).

As mentioned by @stimpy77: for support in MVC Razor views you'll need an extra package (for those that don't read the comments)

Install-Package Microsoft.CodeDom.Providers.DotNetCompilerPlatform

If you want full C# 6.0 support, you'll need to install VS2015.

Is it possible to force row level locking in SQL Server?

You can use the ROWLOCK hint, but AFAIK SQL may decide to escalate it if it runs low on resources

From the doco:

ROWLOCK Specifies that row locks are taken when page or table locks are ordinarily taken. When specified in transactions operating at the SNAPSHOT isolation level, row locks are not taken unless ROWLOCK is combined with other table hints that require locks, such as UPDLOCK and HOLDLOCK.

and

Lock hints ROWLOCK, UPDLOCK, AND XLOCK that acquire row-level locks may place locks on index keys rather than the actual data rows. For example, if a table has a nonclustered index, and a SELECT statement using a lock hint is handled by a covering index, a lock is acquired on the index key in the covering index rather than on the data row in the base table.

And finally this gives a pretty in-depth explanation about lock escalation in SQL Server 2005 which was changed in SQL Server 2008.

There is also, the very in depth: Locking in The Database Engine (in books online)

So, in general

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

Should be ok, but depending on the indexes and load on the server it may end up escalating to a page lock.

Change background color of selected item on a ListView

Method 1:

Update ListView in the your xml layout activity/fragment:

<ListView
   ...
   android:choiceMode="singleChoice"
   android:listSelector="@android:color/darker_gray"
/>

That's it, you're done!

If you want a programmatic way to handle this then use method 2...

Method 2:

If you're using a ListFragment you can override onListItemClick(), using the view to set the colour. Save the current View selected to reset the colour of the last selection.

Please note, this only works on listviews that fit on one screen, as the view is recycled.

public class MyListFragment extends ListFragment {
    View previousSelectedItem;
...
    @Override
    public void onListItemClick(ListView parent, View v, int position, long id) {
        super.onListItemClick(parent, v, position, id);
        if (previousSelectedItem!=null) {
            previousSelectedItem.setBackgroundColor(Color.WHITE);
        }
        previousSelectedItem=v;
        v.setBackgroundColor(Color.BLUE);
    }
}

How line ending conversions work with git core.autocrlf between different operating systems

The best explanation of how core.autocrlf works is found on the gitattributes man page, in the text attribute section.

This is how core.autocrlf appears to work currently (or at least since v1.7.2 from what I am aware):

  • core.autocrlf = true
  1. Text files checked-out from the repository that have only LF characters are normalized to CRLF in your working tree; files that contain CRLF in the repository will not be touched
  2. Text files that have only LF characters in the repository, are normalized from CRLF to LF when committed back to the repository. Files that contain CRLF in the repository will be committed untouched.
  • core.autocrlf = input
  1. Text files checked-out from the repository will keep original EOL characters in your working tree.
  2. Text files in your working tree with CRLF characters are normalized to LF when committed back to the repository.
  • core.autocrlf = false
  1. core.eol dictates EOL characters in the text files of your working tree.
  2. core.eol = native by default, which means Windows EOLs are CRLF and *nix EOLs are LF in working trees.
  3. Repository gitattributes settings determines EOL character normalization for commits to the repository (default is normalization to LF characters).

I've only just recently researched this issue and I also find the situation to be very convoluted. The core.eol setting definitely helped clarify how EOL characters are handled by git.

Sum the digits of a number

n = str(input("Enter the number\n"))

list1 = []

for each_number in n:

        list1.append(int(each_number))

print(sum(list1))

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:

@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })

The above format can of course be changed to whatever.

sql try/catch rollback/commit - preventing erroneous commit after rollback

Below might be useful.

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

BEGIN TRANSACTION;

BEGIN TRY
    -- your code --
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

Android/Eclipse: how can I add an image in the res/drawable folder?

Open folder path of Android application, open src folder then Add your image in /res/drawable folder

No connection string named 'MyEntities' could be found in the application config file

I had this problem when running MSTest. I could not get it to work without the "noisolation" flag.

Hopefully this helps someone. Cost me a lot of time to figure that out. Everything ran fine from the IDE. Something weird about the Entity Framework in this context.

git: patch does not apply

git apply --reverse --reject example.patch

When you created a patch file with the branch names reversed:

ie. git diff feature_branch..master instead of git diff master..feature_branch

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

How to share data between different threads In C# using AOP?

You can't beat the simplicity of a locked message queue. I say don't waste your time with anything more complex.

Read up on the lock statement.

lock

EDIT

Here is an example of the Microsoft Queue object wrapped so all actions against it are thread safe.

public class Queue<T>
{
    /// <summary>Used as a lock target to ensure thread safety.</summary>
    private readonly Locker _Locker = new Locker();

    private readonly System.Collections.Generic.Queue<T> _Queue = new System.Collections.Generic.Queue<T>();

    /// <summary></summary>
    public void Enqueue(T item)
    {
        lock (_Locker)
        {
            _Queue.Enqueue(item);
        }
    }

    /// <summary>Enqueues a collection of items into this queue.</summary>
    public virtual void EnqueueRange(IEnumerable<T> items)
    {
        lock (_Locker)
        {
            if (items == null)
            {
                return;
            }

            foreach (T item in items)
            {
                _Queue.Enqueue(item);
            }
        }
    }

    /// <summary></summary>
    public T Dequeue()
    {
        lock (_Locker)
        {
            return _Queue.Dequeue();
        }
    }

    /// <summary></summary>
    public void Clear()
    {
        lock (_Locker)
        {
            _Queue.Clear();
        }
    }

    /// <summary></summary>
    public Int32 Count
    {
        get
        {
            lock (_Locker)
            {
                return _Queue.Count;
            }
        }
    }

    /// <summary></summary>
    public Boolean TryDequeue(out T item)
    {
        lock (_Locker)
        {
            if (_Queue.Count > 0)
            {
                item = _Queue.Dequeue();
                return true;
            }
            else
            {
                item = default(T);
                return false;
            }
        }
    }
}

EDIT 2

I hope this example helps. Remember this is bare bones. Using these basic ideas you can safely harness the power of threads.

public class WorkState
{
    private readonly Object _Lock = new Object();
    private Int32 _State;

    public Int32 GetState()
    {
        lock (_Lock)
        {
            return _State;
        }
    }

    public void UpdateState()
    {
        lock (_Lock)
        {
            _State++;   
        }   
    }
}

public class Worker
{
    private readonly WorkState _State;
    private readonly Thread _Thread;
    private volatile Boolean _KeepWorking;

    public Worker(WorkState state)
    {
        _State = state;
        _Thread = new Thread(DoWork);
        _KeepWorking = true;                
    }

    public void DoWork()
    {
        while (_KeepWorking)
        {
            _State.UpdateState();                   
        }
    }

    public void StartWorking()
    {
        _Thread.Start();
    }

    public void StopWorking()
    {
        _KeepWorking = false;
    }
}



private void Execute()
{
    WorkState state = new WorkState();
    Worker worker = new Worker(state);

    worker.StartWorking();

    while (true)
    {
        if (state.GetState() > 100)
        {
            worker.StopWorking();
            break;
        }
    }                   
}

How to specify the default error page in web.xml?

You can also specify <error-page> for exceptions using <exception-type>, eg below:

<error-page>
    <exception-type>java.lang.Exception</exception-type>
    <location>/errorpages/exception.html</location>
</error-page>

Or map a error code using <error-code>:

<error-page>
    <error-code>404</error-code>
    <location>/errorpages/404error.html</location>
</error-page>

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

I like the style of Mike Woodhouse's answer on the other page you mentioned. It's especially concise when the thing being maximised over is just a single column, in which case the subquery can just use MAX(some_col) and GROUP BY the other columns, but in your case you have a 2-part quantity to be maximised, you can still do so by using ORDER BY plus LIMIT 1 instead (as done by Quassnoi):

SELECT * 
FROM lives outer
WHERE (usr_id, time_stamp, trans_id) IN (
    SELECT usr_id, time_stamp, trans_id
    FROM lives sq
    WHERE sq.usr_id = outer.usr_id
    ORDER BY trans_id, time_stamp
    LIMIT 1
)

I find using the row-constructor syntax WHERE (a, b, c) IN (subquery) nice because it cuts down on the amount of verbiage needed.

Generating random whole numbers in JavaScript in a specific range?

function randomRange(min, max) {
  return ~~(Math.random() * (max - min + 1)) + min
}

Alternative if you are using Underscore.js you can use

_.random(min, max)

Casting objects in Java

Superclass variable = new subclass object();
This just creates an object of type subclass, but assigns it to the type superclass. All the subclasses' data is created etc, but the variable cannot access the subclasses data/functions. In other words, you cannot call any methods or access data specific to the subclass, you can only access the superclasses stuff.

However, you can cast Superclassvariable to the Subclass and use its methods/data.

Git Bash won't run my python files?

Here is the SOLUTION

If you get Response:

  1. bash: python: command not found OR
  2. bash: conda: command not found

To the following Commands: when you execute python or python -V conda or conda --version in your Git/Terminal window

Background: This is because you either

  1. Installed Python in a location on your C Drive (C:) which is not directly in your program files folder.
  2. Installed Python maybe on the D Drive (D:) and your computer by default searches for it on your C:
  3. You have been told to go to your environment variables (located if you do a search for environment variables on your machines start menu) and change the "Path" variable on your computer and this still does not fix the problem.

Solution:

  1. At the command prompt, paste this command export PATH="$PATH:/c/Python36". That will tell Windows where to find Python. (This assumes that you installed it in C:\Python36)

  2. If you installed python on your D drive, paste this command export PATH="$PATH:/d/Python36".

  3. Then at the command prompt, paste python or python -V and you will see the version of Python installed and now you should not get Python 3.6.5

  4. Assuming that it worked correctly you will want to set up git bash so that it always knows where to find python. To do that, enter the following command: echo 'export PATH="$PATH:/d/Python36"' > .bashrc

Permanent Solution

  1. Go to BASH RC Source File (located on C: / C Drive in “C:\Users\myname”)

  2. Make sure your BASH RC Source File is receiving direction from your Bash Profile Source File, you can do this by making sure that your BASH RC Source File contains this line of code: source ~/.bash_profile

  3. Go to BASH Profile Source File (located on C: / C Drive in “C:\Users\myname”)

  4. Enter line: export PATH="$PATH:/D/PROGRAMMING/Applications/PYTHON/Python365" (assuming this is the location where Python version 3.6.5 is installed)

  5. This should take care of the problem permanently. Now whenever you open your Git Bash Terminal Prompt and enter “python” or “python -V” it should return the python version

Host binding and Host listening

@HostListener is a decorator for the callback/event handler method, so remove the ; at the end of this line:

@HostListener('click', ['$event.target']);

Here's a working plunker that I generated by copying the code from the API docs, but I put the onClick() method on the same line for clarity:

import {Component, HostListener, Directive} from 'angular2/core';

@Directive({selector: 'button[counting]'})
class CountClicks {
  numberOfClicks = 0;
  @HostListener('click', ['$event.target']) onClick(btn) {
    console.log("button", btn, "number of clicks:", this.numberOfClicks++);
  }
}
@Component({
  selector: 'my-app',
  template: `<button counting>Increment</button>`,
  directives: [CountClicks]
})
export class AppComponent {
  constructor() { console.clear(); }
}

Host binding can also be used to listen to global events:

To listen to global events, a target must be added to the event name. The target can be window, document or body (reference)

@HostListener('document:keyup', ['$event'])
handleKeyboardEvent(kbdEvent: KeyboardEvent) { ... }

How to find array / dictionary value using key?

It's as simple as this :

$array[$key];

How to use goto statement correctly

As already pointed out by all the answers goto - a reserved word in Java and is not used in the language.

restart: is called an identifier followed by a colon.

Here are a few things you need to take care of if you wish to achieve similar behavior -

outer:                  // Should be placed exactly before the loop
loopingConstructOne  {  // We can have statements before the outer but not inbetween the label and the loop          
    inner:
    loopingConstructTwo {
        continue;       // This goes to the top of loopingConstructTwo and continue.
        break;          // This breaks out of loopingConstructTwo.
        continue outer; // This goes to the outer label and reenters loopingConstructOne.
        break outer;    // This breaks out of the loopingConstructOne.
        continue inner; // This will behave similar to continue.
        break inner;    // This will behave similar to break.
    }
}

I'm not sure of whether should I say similar as I already have.

Windows path in Python

In case you'd like to paste windows path from other source (say, File Explorer) - you can do so via input() call in python console:

>>> input()
D:\EP\stuff\1111\this_is_a_long_path\you_dont_want\to_type\or_edit_by_hand
'D:\\EP\\stuff\\1111\\this_is_a_long_path\\you_dont_want\\to_type\\or_edit_by_hand'

Then just copy the result

Ranges of floating point datatype in C?

A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:

(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) = 
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) = 
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38

Select the first 10 rows - Laravel Eloquent

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

Traits vs. interfaces

The trait is same as a class we can use for multiple inheritance purposes and also code reusability.

We can use trait inside the class and also we can use multiple traits in the same class with 'use keyword'.

The interface is using for code reusability same as a trait

the interface is extend multiple interfaces so we can solve the multiple inheritance problems but when we implement the interface then we should create all the methods inside the class. For more info click below link:

http://php.net/manual/en/language.oop5.traits.php http://php.net/manual/en/language.oop5.interfaces.php

Combining INSERT INTO and WITH/CTE

Yep:

WITH tab (
  bla bla
)

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (  BatchID,                                                        AccountNo,
APartyNo,
SourceRowID)    

SELECT * FROM tab

Note that this is for SQL Server, which supports multiple CTEs:

WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y

Teradata allows only one CTE and the syntax is as your example.

MySQL error 2006: mysql server has gone away

uncomment the ligne below in your my.ini/my.cnf, this will split your large file into smaller portion

# binary logging format - mixed recommended
# binlog_format=mixed

TO

# binary logging format - mixed recommended
binlog_format=mixed

Batch script to find and replace a string in text file within a minute for files up to 12 MB

Try this:

@echo off &setlocal
setlocal enabledelayedexpansion

set "search=%1"
set "replace=%2"
set "textfile=Input.txt"
set "newfile=Output.txt"
(for /f "delims=" %%i in (%textfile%) do (
    set "line=%%i"
    set "line=!line:%search%=%replace%!"
    echo(!line!
))>"%newfile%"
del %textfile%
rename %newfile%  %textfile%
endlocal

Excel - Button to go to a certain sheet

Any reason they can't just click on the tab for your sheet when they want it?

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])

align divs to the bottom of their container

You can cheat! Say your div is 20px high, place the div at the top of the next container and set

position: absolute;
top: -20px;

It may not be semantically clean but does scale with responsive designs

A reference to the dll could not be added

For anyone else looking for help on this matter, or experiencing a FileNotFoundException or a FirstChanceException, check out my answer here:

A first chance exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.ni.dll - windows phone

In general you must be absolutely certain that you are meeting all of the requirements for making the reference - I know it's the obvious answer, but you're probably overlooking a relatively simple requirement.

Apache: "AuthType not set!" 500 Error

The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?

Require all granted is only in 2.4, but Allow all ... stops working in 2.4, and we want to be able to rollout a config that works in both.

The only solution I found, which I am not sure is the proper one, is to use:

# backwards compatibility with apache 2.2
Order allow,deny
Allow from all

# forward compatibility with apache 2.4
Require all granted
Satisfy Any

This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...

See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.

The opposite of Intersect()

string left = "411329_SOFT_MAC_GREEN";
string right= "SOFT_MAC_GREEN";

string[] l = left.Split('_');
string[] r = right.Split('_');

string[] distinctLeft = l.Distinct().ToArray();
string[] distinctRight = r.Distinct().ToArray();

var commonWord = l.Except(r, StringComparer.OrdinalIgnoreCase)
string result = String.Join("_",commonWord);
result = "411329"

How can I print out all possible letter combinations a given phone number can represent?

This is a recursive algorithm in C++11.

#include <iostream>
#include <array>
#include <list>

std::array<std::string, 10> pm = {
    "0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
};

void generate_mnemonic(const std::string& numbers, size_t i, std::string& m,
    std::list<std::string>& mnemonics)
{
    // Base case
    if (numbers.size() == i) {
        mnemonics.push_back(m);
        return;
    }

    for (char c : pm[numbers[i] - '0']) {
        m[i] = c;
        generate_mnemonic(numbers, i + 1, m, mnemonics);
    }
}

std::list<std::string> phone_number_mnemonics(const std::string& numbers)
{
    std::list<std::string> mnemonics;
    std::string m(numbers.size(), 0);
    generate_mnemonic(numbers, 0, m, mnemonics);
    return mnemonics;
}

int main() {
    std::list<std::string> result = phone_number_mnemonics("2276696");
    for (const std::string& s : result) {
        std::cout << s << std::endl;
    }
    return 0;
}

How do I detect a page refresh using jquery?

All the code is client side, I hope you fine this helpful:

First thing there are 3 functions we will use:

    function setCookie(c_name, value, exdays) {
            var exdate = new Date();
            exdate.setDate(exdate.getDate() + exdays);
            var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
            document.cookie = c_name + "=" + c_value;
        }

    function getCookie(c_name) {
        var i, x, y, ARRcookies = document.cookie.split(";");
        for (i = 0; i < ARRcookies.length; i++) {
            x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
            y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
            x = x.replace(/^\s+|\s+$/g, "");
            if (x == c_name) {
                return unescape(y);
            }
        }
    }

    function DeleteCookie(name) {
            document.cookie = name + '=; expires=Thu, 01-Jan-70 00:00:01 GMT;';
        }

Now we will start with the page load:

$(window).load(function () {
 //if IsRefresh cookie exists
 var IsRefresh = getCookie("IsRefresh");
 if (IsRefresh != null && IsRefresh != "") {
    //cookie exists then you refreshed this page(F5, reload button or right click and reload)
    //SOME CODE
    DeleteCookie("IsRefresh");
 }
 else {
    //cookie doesnt exists then you landed on this page
    //SOME CODE
    setCookie("IsRefresh", "true", 1);
 }
})

Relay access denied on sending mail, Other domain outside of network

Configuring $mail->SMTPAuth = true; was the solution for me. The reason why is because without authentication the mail server answers with 'Relay access denied'. Since putting this in my code, all mails work fine.

Does List<T> guarantee insertion order?

The List<> class does guarantee ordering - things will be retained in the list in the order you add them, including duplicates, unless you explicitly sort the list.

According to MSDN:

...List "Represents a strongly typed list of objects that can be accessed by index."

The index values must remain reliable for this to be accurate. Therefore the order is guaranteed.

You might be getting odd results from your code if you're moving the item later in the list, as your Remove() will move all of the other items down one place before the call to Insert().

Can you boil your code down to something small enough to post?

How to avoid HTTP error 429 (Too Many Requests) python

In many cases, continuing to scrape data from a website even when the server is requesting you not to is unethical. However, in the cases where it isn't, you can utilize a list of public proxies in order to scrape a website with many different IP addresses.

Vue.js: Conditional class style binding

the problem is blade, try this

<i class="fa" v-bind:class="['{{content['cravings']}}' ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i>

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

Java: Get month Integer from Date

tl;dr

myUtilDate.toInstant()                          // Convert from legacy class to modern. `Instant` is a point on the timeline in UTC.
          .atZone(                              // Adjust from UTC to a particular time zone to determine date. Renders a `ZonedDateTime` object. 
              ZoneId.of( "America/Montreal" )   // Better to specify desired/expected zone explicitly than rely implicitly on the JVM’s current default time zone.
          )                                     // Returns a `ZonedDateTime` object.
          .getMonthValue()                      // Extract a month number. Returns a `int` number.

java.time Details

The Answer by Ortomala Lokni for using java.time is correct. And you should be using java.time as it is a gigantic improvement over the old java.util.Date/.Calendar classes. See the Oracle Tutorial on java.time.

I'll add some code showing how to use java.time without regard to java.util.Date, for when you are starting out with fresh code.

Using java.time in a nutshell… An Instant is a moment on the timeline in UTC. Apply a time zone (ZoneId) to get a ZonedDateTime.

The Month class is a sophisticated enum to represent a month in general. That enum has handy methods such as getting a localized name. And rest assured that the month number in java.time is a sane one, 1-12, not the zero-based nonsense (0-11) found in java.util.Date/.Calendar.

To get the current date-time, time zone is crucial. At any moment the date is not the same around the world. Therefore the month is not the same around the world if near the ending/beginning of the month.

ZoneId zoneId = ZoneId.of( "America/Montreal" );  // Or 'ZoneOffset.UTC'.
ZonedDateTime now = ZonedDateTime.now( zoneId );
Month month = now.getMonth(); 
int monthNumber = month.getValue(); // Answer to the Question.
String monthName = month.getDisplayName( TextStyle.FULL , Locale.CANADA_FRENCH );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to implement "Access-Control-Allow-Origin" header in asp.net

1.Install-Package Microsoft.AspNet.WebApi.Cors

2 . Add this code in WebApiConfig.cs.

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes

    config.EnableCors();

    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );
}

3. Add this

using System.Web.Http.Cors; 

4. Add this code in Api Controller (HomeController.cs)

[EnableCors(origins: "*", headers: "*", methods: "*")]
public class HomeController : ApiController
{
    [HttpGet]
    [Route("api/Home/test")]
    public string test()
    {
       return "";
    }
}

Getting list of items inside div using Selenium Webdriver

Follow the code below exactly matched with your case.

  1. Create an interface of the web element for the div under div with class as facetContainerDiv

ie for

<div class="facetContainerDiv">
    <div>

    </div>
</div>

2. Create an IList with all the elements inside the second div i.e for,

<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>
<label class="facetLabel">
   <input class="facetCheck" type="checkbox" />
</label>

3. Access each check boxes using the index

Please find the code below

using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace SeleniumTests
{
  class ChechBoxClickWthIndex
    {
        static void Main(string[] args)
        {

            IWebDriver driver = new FirefoxDriver();

            driver.Navigate().GoToUrl("file:///C:/Users/chery/Desktop/CheckBox.html");

            // Create an interface WebElement of the div under div with **class as facetContainerDiv**
            IWebElement WebElement =    driver.FindElement(By.XPath("//div[@class='facetContainerDiv']/div"));
            // Create an IList and intialize it with all the elements of div under div with **class as facetContainerDiv**
            IList<IWebElement> AllCheckBoxes = WebElement.FindElements(By.XPath("//label/input"));
            int RowCount = AllCheckBoxes.Count;
            for (int i = 0; i < RowCount; i++)
            {
            // Check the check boxes based on index
               AllCheckBoxes[i].Click();

            }
            Console.WriteLine(RowCount);
            Console.ReadLine(); 

        }
    }
}

Run javascript function when user finishes typing instead of on key up?

So, I'm going to guess finish typing means you just stop for a while, say 5 seconds. So with that in mind, lets start a timer when the user releases a key and clear it when they press one. I decided the input in question will be #myInput.

Making a few assumptions...

//setup before functions
var typingTimer;                //timer identifier
var doneTypingInterval = 5000;  //time in ms, 5 second for example
var $input = $('#myInput');

//on keyup, start the countdown
$input.on('keyup', function () {
  clearTimeout(typingTimer);
  typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$input.on('keydown', function () {
  clearTimeout(typingTimer);
});

//user is "finished typing," do something
function doneTyping () {
  //do something
}

Convert integer to hexadecimal and back again

NET FRAMEWORK

Very well explained and few programming lines GOOD JOB

// Store integer 182
int intValue = 182;
// Convert integer 182 as a hex in a string variable
string hexValue = intValue.ToString("X");
// Convert the hex string back to the number
int intAgain = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber);

PASCAL >> C#

http://files.hddguru.com/download/Software/Seagate/St_mem.pas

Something from the old school very old procedure of pascal converted to C #

    /// <summary>
    /// Conver number from Decadic to Hexadecimal
    /// </summary>
    /// <param name="w"></param>
    /// <returns></returns>
    public string MakeHex(int w)
    {
        try
        {
           char[] b =  {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
           char[] S = new char[7];

              S[0] = b[(w >> 24) & 15];
              S[1] = b[(w >> 20) & 15];
              S[2] = b[(w >> 16) & 15];
              S[3] = b[(w >> 12) & 15];
              S[4] = b[(w >> 8) & 15];
              S[5] = b[(w >> 4) & 15];
              S[6] = b[w & 15];

              string _MakeHex = new string(S, 0, S.Count());

              return _MakeHex;
        }
        catch (Exception ex)
        {

            throw;
        }
    }

How to stop mysqld

Try:

/usr/local/mysql/bin/mysqladmin -u root -p shutdown 

Or:

sudo mysqld stop

Or:

sudo /usr/local/mysql/bin/mysqld stop

Or:

sudo mysql.server stop

If you install the Launchctl in OSX you can try:

MacPorts

sudo launchctl unload -w /Library/LaunchDaemons/org.macports.mysql.plist
sudo launchctl load -w /Library/LaunchDaemons/org.macports.mysql.plist

Note: this is persistent after reboot.

Homebrew

launchctl unload -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist
launchctl load -w ~/Library/LaunchAgents/homebrew.mxcl.mysql.plist

Binary installer

sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
sudo /Library/StartupItems/MySQLCOM/MySQLCOM start
sudo /Library/StartupItems/MySQLCOM/MySQLCOM restart

I found that in: https://stackoverflow.com/a/102094/58768

Javascript to export html table to Excel

ShieldUI's export to excel functionality should already support all special chars.

Overloading and overriding

Another point to add.

Overloading More than one method with Same name. Same or different return type. Different no of parameters or Different type of parameters. In Same Class or Derived class.

int Add(int num1, int num2) int Add(int num1, int num2, int num3) double Add(int num1, int num2) double Add(double num1, double num2)

Can be possible in same class or derived class. Generally prefers in same class. E.g. Console.WriteLine() has 19 overloaded methods.

Can overload class constructors, methods.

Can consider as Compile Time (static / Early Binding) polymorphism.

=====================================================================================================

Overriding cannot be possible in same class. Can Override class methods, properties, indexers, events.

Has some limitations like The overridden base method must be virtual, abstract, or override. You cannot use the new, static, or virtual modifiers to modify an override method.

Can Consider as Run Time (Dynamic / Late Binding) polymorphism.

Helps in versioning http://msdn.microsoft.com/en-us/library/6fawty39.aspx

=====================================================================================================

Helpful Links

http://msdn.microsoft.com/en-us/library/ms173152.aspx Compile time polymorphism vs. run time polymorphism

Adding 30 minutes to time formatted as H:i in PHP

In order for that to work $time has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00'); which is what you seem to do, because then I get 0:30 and 1:30 as results too.

Try

$time = strtotime('10:00');

As an alternative, consider using DateTime (the below requires PHP 5.3 though):

$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M'));              // substract 30 minutes
echo $dt->format('H:i');                          // echo modified time
$dt->add(new DateInterval('PT1H'));               // add 1 hour
echo $dt->format('H:i');                          // echo modified time

or procedural if you don't like OOP

$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');

Biggest advantage to using ASP.Net MVC vs web forms

MVC Controller:

    [HttpGet]
    public ActionResult DetailList(ImportDetailSearchModel model)
    {
        Data.ImportDataAccess ida = new Data.ImportDataAccess();
        List<Data.ImportDetailData> data = ida.GetImportDetails(model.FileId, model.FailuresOnly);

        return PartialView("ImportSummaryDetailPartial", data);
    }

MVC View:

<table class="sortable">
<thead>
    <tr><th>Unique Id</th><th class="left">Error Type</th><th class="left">Field</th><th class="left">Message</th><th class="left">State</th></tr>
</thead>
<tbody>
    @foreach (Data.ImportDetailData detail in Model)
    {
    <tr><th>@detail.UniqueID</th><th class="left">@detail.ErrorType</th><th class="left">@detail.FieldName</th><th class="left">@detail.Message</th><th class="left">@detail.ItemState</th></tr>
    }
</tbody></table>

How hard is that? No ViewState, No BS Page life-cycle...Just pure efficient code.

How is CountDownLatch used in Java Multithreading?

Best real time Example for countDownLatch explained in this link CountDownLatchExample

It is more efficient to use if-return-return or if-else-return?

From a performance point of view, it doesn't matter in Python, and I'd assume the same for every modern language out there.

It really comes down to style and readability. Your second option (if-else block) is more readable than the first, and a lot more readable than the one-liner ternary operation.

I want to convert std::string into a const wchar_t *

First convert it to std::wstring:

std::wstring widestr = std::wstring(str.begin(), str.end());

Then get the C string:

const wchar_t* widecstr = widestr.c_str();

This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

How do I implement interfaces in python?

Using the abc module for abstract base classes seems to do the trick.

from abc import ABCMeta, abstractmethod

class IInterface:
    __metaclass__ = ABCMeta

    @classmethod
    def version(self): return "1.0"
    @abstractmethod
    def show(self): raise NotImplementedError

class MyServer(IInterface):
    def show(self):
        print 'Hello, World 2!'

class MyBadServer(object):
    def show(self):
        print 'Damn you, world!'


class MyClient(object):

    def __init__(self, server):
        if not isinstance(server, IInterface): raise Exception('Bad interface')
        if not IInterface.version() == '1.0': raise Exception('Bad revision')

        self._server = server


    def client_show(self):
        self._server.show()


# This call will fail with an exception
try:
    x = MyClient(MyBadServer)
except Exception as exc:
    print 'Failed as it should!'

# This will pass with glory
MyClient(MyServer()).client_show()

Copy row but with new id

SET @table = 'the_table';
SELECT GROUP_CONCAT(IF(COLUMN_NAME IN ('id'), 0, CONCAT("\`", COLUMN_NAME, "\`"))) FROM INFORMATION_SCHEMA.COLUMNS
                  WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = @table INTO @columns;
SET @s = CONCAT('INSERT INTO ', @table, ' SELECT ', @columns,' FROM ', @table, ' WHERE id=1');
PREPARE stmt FROM @s;
EXECUTE stmt;

How to install Laravel's Artisan?

You just have to read the laravel installation page:

  1. Install Composer if not already installed
  2. Open a command line and do:
composer global require "laravel/installer"

Inside your htdocs or www directory, use either:

laravel new appName

(this can lead to an error on windows computers while using latest Laravel (1.3.2)) or:

composer create-project --prefer-dist laravel/laravel appName

(this works also on windows) to create a project called "appName".

To use "php artisan xyz" you have to be inside your project root! as artisan is a file php is going to use... Simple as that ;)

I'm trying to use python in powershell

This works for me permanently:

[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python27","User")

How do I get list of methods in a Python class?

This also works:

In mymodule.py:

def foo(x):
   return 'foo'
def bar():
   return 'bar'

In another file:

import inspect
import mymodule
method_list = [ func[0] for func in inspect.getmembers(mymodule, predicate=inspect.isroutine) if callable(getattr(mymodule, func[0])) ]

Output:

['foo', 'bar']

From the Python docs:

inspect.isroutine(object)

Return true if the object is a user-defined or built-in function or method.

How to use new PasswordEncoder from Spring Security

If you haven't actually registered any users with your existing format then you would be best to switch to using the BCrypt password encoder instead.

It's a lot less hassle, as you don't have to worry about salt at all - the details are completely encapsulated within the encoder. Using BCrypt is stronger than using a plain hash algorithm and it's also a standard which is compatible with applications using other languages.

There's really no reason to choose any of the other options for a new application.

How to map to multiple elements with Java 8 streams?

It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.


Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    Map<String, DataSet> result = new HashMap<>();
    multiDataPoints.forEach(pt ->
        pt.keyToData.forEach((key, value) ->
            result.computeIfAbsent(
                key, k -> new DataSet(k, new ArrayList<>()))
            .dataPoints.add(new DataPoint(pt.timestamp, value))));
    return result.values();
}

Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
            new Object() {
                String key = e.getKey();
                DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
            }))
        .collect(
            collectingAndThen(
                groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
                m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}

Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:

Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
    return multiDataPoints.stream()
        .map(mdp -> mdp.keyToData.entrySet().stream()
            .collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
        .reduce(new HashMap<>(), mapMerger())
        .entrySet().stream()
        .map(e -> new DataSet(e.getKey(), e.getValue()))
        .collect(toList());
}

You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:

<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
    return (lhs, rhs) -> {
        Map<K, List<V>> result = new HashMap<>();
        lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
        return result;
    };
}

Is ini_set('max_execution_time', 0) a bad idea?

Reason is to have some value other than zero. General practice to have it short globally and long for long working scripts like parsers, crawlers, dumpers, exporting & importing scripts etc.

  1. You can halt server, corrupt work of other people by memory consuming script without even knowing it.
  2. You will not be seeing mistakes where something, let's say, infinite loop happened, and it will be harder to diagnose.
  3. Such site may be easily DoSed by single user, when requesting pages with long execution time

How can I create an observable with a delay

It's little late to answer ... but just in case may be someone return to this question looking for an answer

'delay' is property(function) of an Observable

fakeObservable = Observable.create(obs => {
  obs.next([1, 2, 3]);
  obs.complete();
}).delay(3000);

This worked for me ...

Split Spark Dataframe string column into multiple columns

Here's another approach, in case you want split a string with a delimiter.

import pyspark.sql.functions as f

df = spark.createDataFrame([("1:a:2001",),("2:b:2002",),("3:c:2003",)],["value"])
df.show()
+--------+
|   value|
+--------+
|1:a:2001|
|2:b:2002|
|3:c:2003|
+--------+

df_split = df.select(f.split(df.value,":")).rdd.flatMap(
              lambda x: x).toDF(schema=["col1","col2","col3"])

df_split.show()
+----+----+----+
|col1|col2|col3|
+----+----+----+
|   1|   a|2001|
|   2|   b|2002|
|   3|   c|2003|
+----+----+----+

I don't think this transition back and forth to RDDs is going to slow you down... Also don't worry about last schema specification: it's optional, you can avoid it generalizing the solution to data with unknown column size.

Removing the remembered login and password list in SQL Server Management Studio

Delete:

C:\Documents and Settings\%Your Username%\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat"

How to use global variables in React Native?

Try to use global.foo = bar in index.android.js or index.ios.js, then you can call in other file js.

Run ScrollTop with offset of element by ID

No magic involved, just subtract from the offset top of the element

$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');

jQuery click / toggle between two functions

jQuery has two methods called .toggle(). The other one [docs] does exactly what you want for click events.

Note: It seems that at least since jQuery 1.7, this version of .toggle is deprecated, probably for exactly that reason, namely that two versions exist. Using .toggle to change the visibility of elements is just a more common usage. The method was removed in jQuery 1.9.

Below is an example of how one could implement the same functionality as a plugin (but probably exposes the same problems as the built-in version (see the last paragraph in the documentation)).


(function($) {
    $.fn.clickToggle = function(func1, func2) {
        var funcs = [func1, func2];
        this.data('toggleclicked', 0);
        this.click(function() {
            var data = $(this).data();
            var tc = data.toggleclicked;
            $.proxy(funcs[tc], this)();
            data.toggleclicked = (tc + 1) % 2;
        });
        return this;
    };
}(jQuery));

DEMO

(Disclaimer: I don't say this is the best implementation! I bet it can be improved in terms of performance)

And then call it with:

$('#test').clickToggle(function() {   
    $(this).animate({
        width: "260px"
    }, 1500);
},
function() {
    $(this).animate({
        width: "30px"
    }, 1500);
});

Update 2:

In the meantime, I created a proper plugin for this. It accepts an arbitrary number of functions and can be used for any event. It can be found on GitHub.

When does Git refresh the list of remote branches?

Use git fetch to fetch all latest created branches.

CSV new-line character seen in unquoted field error

Try to run dos2unix on your windows imported files first

Magento addFieldToFilter: Two fields, match as OR, not AND

This is the real magento way:

    $collection=Mage::getModel('sales/order')
                ->getCollection()
                ->addFieldToFilter(
                        array(
                            'customer_firstname',//attribute_1 with key 0
                            'remote_ip',//attribute_2 with key 1
                        ),
                        array(
                            array('eq'=>'gabe'),//condition for attribute_1 with key 0
                            array('eq'=>'127.0.0.1'),//condition for attribute_2
                                )
                            )
                        );

UnsatisfiedDependencyException: Error creating bean with name

There is another instance still same error will shown after you doing everything above mentioned. When you change your codes accordingly mentioned solutions make sure to keep originals. So you can easily go back. So go and again check dispatcher-servelet configuration file's base package location. Is it scanning all relevant packages when you running application.

<context:component-scan base-package="your.pakage.path.here"/>

source command not found in sh shell

The source command is built into some shells. If you have a script, it should specify what shell to use on the first line, such as:

#!/bin/bash

Can't import org.apache.http.HttpResponse in Android Studio

in case you are going to start development, go fot OkHttp from square, otherwise if you need to keep your previous code running, then add legacy library to your project dependencies:

dependencies {
    compile group: 'org.apache.httpcomponents' , name: 'httpclient-android' , version: '4.3.5.1'
}

Add key value pair to all objects in array

The map() function is a best choice for this case


tl;dr - Do this:

const newArr = [
  {name: 'eve'},
  {name: 'john'},
  {name: 'jane'}
].map(v => ({...v, isActive: true}))

The map() function won't modify the initial array, but creates a new one. This is also a good practice to keep initial array unmodified.


Alternatives:

const initialArr = [
      {name: 'eve'},
      {name: 'john'},
      {name: 'jane'}
    ]

const newArr1 = initialArr.map(v => ({...v, isActive: true}))
const newArr2 = initialArr.map(v => Object.assign(v, {isActive: true}))

// Results of newArr1 and newArr2 are the same

Add a key value pair conditionally

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr1 = arr.map(v => ({...v, isActive: v.value > 1}))

What if I don't want to add new field at all if the condition is false?

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr = arr.map(v => {
  return v.value > 1 ? {...v, isActive: true} : v 
})

Adding WITH modification of the initial array

const initialArr = [{a: 1}, {b: 2}]
initialArr.forEach(v => {v.isActive = true;});

This is probably not a best idea, but in a real life sometimes it's the only way.


Questions

  • Should I use a spread operator(...), or Object.assign and what's the difference?

Personally I prefer to use spread operator, because I think it uses much wider in modern web community (especially react's developers love it). But you can check the difference yourself: link(a bit opinionated and old, but still)

  • Can I use function keyword instead of =>?

Sure you can. The fat arrow (=>) functions play a bit different with this, but it's not so important for this particular case. But fat arrows function shorter and sometimes plays better as a callbacks. Therefore the usage of fat arrow functions is more modern approach.

  • What Actually happens inside map function: .map(v => ({...v, isActive: true})?

Map function iterates by array's elements and apply callback function for each of them. That callback function should return something that will become an element of a new array. We tell to the .map() function following: take current value(v which is an object), take all key-value pairs away from v andput it inside a new object({...v}), but also add property isActive and set it to true ({...v, isActive: true}) and then return the result. Btw, if original object contains isActive filed it will be overwritten. Object.assign works in a similar way.

  • Can I add more then one field at a time

Yes.

[{value: 1}, {value: 1}, {value: 2}].map(v => ({...v, isActive: true, howAreYou: 'good'}))
  • What I should not do inside .map() method

You shouldn't do any side effects[link 1, link 2], but apparently you can.

Also be noticed that map() iterates over each element of the array and apply function for each of them. So if you do some heavy stuff inside, you might be slow. This (a bit hacky) solution might be more productive in some cases (but I don't think you should apply it more then once in a lifetime).

  • Can I extract map's callback to a separate function?

Sure you can.

const arr = [{value: 1}, {value: 1}, {value: 2}]   
const newArr = arr.map(addIsActive)

function addIsActive(v) {
    return {...v, isActive: true}
}
  • What's wrong with old good for loop?

Nothing is wrong with for, you can still use it, it's just an old-school approach which is more verbose, less safe and mutate the initial array. But you can try:

const arr = [{a: 1}, {b: 2}]
for (let i = 0; i < arr.length; i++) {
 arr[i].isActive = true
}
  • What also i should learn

It would be smart to learn well following methods map(), filter(), reduce(), forEach(), and find(). These methods can solve 80% of what you usually want to do with arrays.

How to download a file over HTTP?

Python 3

  • urllib.request.urlopen

    import urllib.request
    response = urllib.request.urlopen('http://www.example.com/')
    html = response.read()
    
  • urllib.request.urlretrieve

    import urllib.request
    urllib.request.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
    

    Note: According to the documentation, urllib.request.urlretrieve is a "legacy interface" and "might become deprecated in the future" (thanks gerrit)

Python 2

  • urllib2.urlopen (thanks Corey)

    import urllib2
    response = urllib2.urlopen('http://www.example.com/')
    html = response.read()
    
  • urllib.urlretrieve (thanks PabloG)

    import urllib
    urllib.urlretrieve('http://www.example.com/songs/mp3.mp3', 'mp3.mp3')
    

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)

Volatile boolean vs AtomicBoolean

Volatile boolean vs AtomicBoolean

The Atomic* classes wrap a volatile primitive of the same type. From the source:

public class AtomicLong extends Number implements java.io.Serializable {
   ...
   private volatile long value;
   ...
   public final long get() {
       return value;
   }
   ...
   public final void set(long newValue) {
       value = newValue;
   }

So if all you are doing is getting and setting a Atomic* then you might as well just have a volatile field instead.

What does AtomicBoolean do that a volatile boolean cannot achieve?

Atomic* classes give you methods that provide more advanced functionality such as incrementAndGet() for numbers, compareAndSet() for booleans, and other methods that implement multiple operations (get/increment/set, test/set) without locking. That's why the Atomic* classes are so powerful.

For example, if multiple threads are using the following code using ++, there will be race conditions because ++ is actually: get, increment, and set.

private volatile value;
...
// race conditions here
value++;

However, the following code will work in a multi-threaded environment safely without locks:

private final AtomicLong value = new AtomicLong();
...
value.incrementAndGet();

It's also important to note that wrapping your volatile field using Atomic* class is a good way to encapsulate the critical shared resource from an object standpoint. This means that developers can't just deal with the field assuming it is not shared possibly injecting problems with a field++; or other code that introducing race conditions.

Convert List<String> to List<Integer> directly

Guava Converters do the trick.

import com.google.common.base.Splitter;
import com.google.common.primitives.Longs;

final Iterable<Long> longIds = 
    Longs.stringConverter().convertAll(
        Splitter.on(',').trimResults().omitEmptyStrings()
            .splitToList("1,2,3"));

What is “assert” in JavaScript?

As mentioned by T.J., There is no assert in JavaScript. However, there is a node module named assert, which is used mostly for testing. so, you might see code like:

const assert = require('assert');
assert(5 > 7);

What's the difference between align-content and align-items?

First, align-items is for items in a single row. So for a single row of elements on main axis, align-items will align these items respective of each other and it will start with fresh perspective from the next row.

Now, align-content doesn't interfere with items in a row but with rows itself. Hence, align-content will try to align rows with respect to each other and flex container.

Check this fiddle : https://jsfiddle.net/htym5zkn/8/

Allow access permission to write in Program Files of Windows 7

Your program has to run with Administrative Rights. You can't do this automatically with code, but you can request the user (in code) to elevate the rights of your program while it's running. There's a wiki on how to do this. Alternatively, any program can be run as administrator by right-clicking its icon and clicking "Run as administrator".

However, I wouldn't suggest doing this. It would be better to use something like this:

Environment.GetFolderPath(SpecialFolder.ApplicationData);

to get the AppData Folder path and create a folder there for your app. Then put the temp files there.

How to clear an EditText on click?

//To clear When Clear Button is Clicked

firstName = (EditText) findViewById(R.id.firstName);

    clear = (Button) findViewById(R.id.clearsearchSubmit);

    clear.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if (v.getId() == R.id.clearsearchSubmit);
            firstName.setText("");
        }
    });

This will help to clear the wrong keywords that you have typed in so instead of pressing backspace again and again you can simply click the button to clear everything.It Worked For me. Hope It Helps

How to create a HTML Table from a PHP array?

echo '<table><tr><th>Title</th><th>Price</th><th>Number</th></tr>';
foreach($shop as $id => $item) {
    echo '<tr><td>'.$item[0].'</td><td>'.$item[1].'</td><td>'.$item[2].'</td></tr>';
}
echo '</table>';

Is there a command to restart computer into safe mode?

In the command prompt, type the command below and press Enter.

bcdedit /enum

Under the Windows Boot Loader sections, make note of the identifier value.

To start in safe mode from command prompt :

bcdedit /set {identifier} safeboot minimal 

Then enter the command line to reboot your computer.

Where are shared preferences stored?

SharedPreferences are stored in an xml file in the app data folder, i.e.

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

or the default preferences at:

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml

SharedPreferences added during runtime are not stored in the Eclipse project.

Note: Accessing /data/data/<package_name> requires superuser privileges

What is a Sticky Broadcast?

A normal broadcast Intent is not available anymore after is was send and processed by the system. If you use the sendStickyBroadcast(Intent) method, the Intent is sticky, meaning the Intent you are sending stays around after the broadcast is complete.

you refer to my blog:enter link description here

How to add an item to a drop down list in ASP.NET?

Try this, it will insert the list item at index 0;

DropDownList1.Items.Insert(0, new ListItem("Add New", ""));

could not access the package manager. is the system running while installing android application

The solution for me was to restart the IDE. I suspect that a slow emulator was hiding from view, blocking installation on my device.

"Strict Standards: Only variables should be passed by reference" error

This should be OK

   $value = explode(".", $value);
   $extension = strtolower(array_pop($value));   //Line 32
   // the file name is before the last "."
   $fileName = array_shift($value);  //Line 34

Compile a DLL in C/C++, then call it from another program

Regarding building a DLL using MinGW, here are some very brief instructions.

First, you need to mark your functions for export, so they can be used by callers of the DLL. To do this, modify them so they look like (for example)

__declspec( dllexport ) int add2(int num){
   return num + 2;
}

then, assuming your functions are in a file called funcs.c, you can compile them:

gcc -shared -o mylib.dll funcs.c

The -shared flag tells gcc to create a DLL.

To check if the DLL has actually exported the functions, get hold of the free Dependency Walker tool and use it to examine the DLL.

For a free IDE which will automate all the flags etc. needed to build DLLs, take a look at the excellent Code::Blocks, which works very well with MinGW.

Edit: For more details on this subject, see the article Creating a MinGW DLL for Use with Visual Basic on the MinGW Wiki.

Java: Get last element after split

You can use the StringUtils class in Apache Commons:

StringUtils.substringAfterLast(one, "-");

Regular Expressions and negating a whole character group

Yes its called negative lookahead. It goes like this - (?!regex here). So abc(?!def) will match abc not followed by def. So it'll match abce, abc, abck, etc.

Similarly there is positive lookahead - (?=regex here). So abc(?=def) will match abc followed by def.

There are also negative and positive lookbehind - (?<!regex here) and (?<=regex here) respectively

One point to note is that the negative lookahead is zero-width. That is, it does not count as having taken any space.

So it may look like a(?=b)c will match "abc" but it won't. It will match 'a', then the positive lookahead with 'b' but it won't move forward into the string. Then it will try to match the 'c' with 'b' which won't work. Similarly ^a(?=b)b$ will match 'ab' and not 'abb' because the lookarounds are zero-width (in most regex implementations).

More information on this page

Link to reload current page

I AM USING HTML TO SOLVE THIS PROBLEM
Use:

<a href="page1.html"> Link </a>

*page1.html -> type the name of the file you are working on (your current HTML file)

How to read the post request parameters using JavaScript

POST variables are only available to the browser if that same browser sent them in the first place. If another website form submits via POST to another URL, the browser will not see the POST data come in.

SITE A: has a form submit to an external URL (site B) using POST SITE B: will receive the visitor but with only GET variables

How to Generate Barcode using PHP and Display it as an Image on the same page

There is a library for this BarCode PHP. You just need to include a few files:

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

You can generate many types of barcodes, namely 1D or 2D. Add the required library:

require_once('class/BCGcode39.barcode.php');

Generate the colours:

// The arguments are R, G, and B for color.
$colorFront = new BCGColor(0, 0, 0);
$colorBack = new BCGColor(255, 255, 255);

After you have added all the codes, you will get this way:

Example

Since several have asked for an example here is what I was able to do to get it done

require_once('class/BCGFontFile.php');
require_once('class/BCGColor.php');
require_once('class/BCGDrawing.php');

require_once('class/BCGcode128.barcode.php');

header('Content-Type: image/png');

$color_white = new BCGColor(255, 255, 255);

$code = new BCGcode128();
$code->parse('HELLO');

$drawing = new BCGDrawing('', $color_white);
$drawing->setBarcode($code);

$drawing->draw();
$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);

If you want to actually create the image file so you can save it then change

$drawing = new BCGDrawing('', $color_white);

to

$drawing = new BCGDrawing('image.png', $color_white);

Android - Best and safe way to stop thread

My requirement was slightly different than the question, still this is also a useful way of stopping the thread to be executing its tasks. All I wanted to do is to stop the thread on exiting the screen and resumes while returning to the screen.

As per the Android docs, this would be the proposed replacement for stop method which has been deprecated from API 15

Many uses of stop should be replaced by code that simply modifies some variable to indicate that the target thread should stop running. The target thread should check this variable regularly, and return from its run method in an orderly fashion if the variable indicates that it is to stop running.

My Thread class

   class ThreadClass implements Runnable {
            ...
                  @Override
                        public void run() {
                            while (count < name.length()) {

                                if (!exited) // checks boolean  
                                  {
                                   // perform your task
                                                     }
            ...

OnStop and OnResume would look like this

  @Override
    protected void onStop() {
        super.onStop();
        exited = true;
    }

    @Override
    protected void onResume() {
        super.onResume();
        exited = false;
    }

where to place CASE WHEN column IS NULL in this query

Not able to understand your actual problem but your case statement is incorrect

CASE 
WHEN 
TABLE3.COL3 IS NULL
THEN TABLE2.COL3
ELSE
TABLE3.COL3
END 
AS
COL4

Remove a file from the list that will be committed

You have to reset that file to the original state and commit it again using --amend. This is done easiest using git checkout HEAD^.

Prepare demo:

$ git init
$ date >file-a
$ date >file-b
$ git add .
$ git commit -m "Initial commit"
$ date >file-a
$ date >file-b
$ git commit -a -m "the change which should only be file-a"

State before:

$ git show --stat
commit 4aa38f84e04d40a1cb40a5207ccd1a3cb3a4a317 (HEAD -> master)
Date:   Wed Feb 7 17:24:45 2018 +0100

    the change which should only be file-a

 file-a | 2 +-
 file-b | 2 +-
 2 files changed, 2 insertions(+), 2 deletions(-)

Here it comes: restore the previous version

$ git checkout HEAD^ file-b

commit it:

$ git commit --amend file-b
[master 9ef8b8b] the change which should only be file-a
 Date: Wed Feb 7 17:24:45 2018 +0100
 1 file changed, 1 insertion(+), 1 deletion(-)

State after:

$ git show --stat
commit 9ef8b8bab224c4d117f515fc9537255941b75885 (HEAD -> master)
Date:   Wed Feb 7 17:24:45 2018 +0100

    the change which should only be file-a

 file-a | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

Web Reference vs. Service Reference

In the end, both do the same thing. There are some differences in code: Web Services doesn't add a Root namespace of project, but Service Reference adds service classes to the namespace of the project. The ServiceSoapClient class gets a different naming, which is not important. In working with TFS I'd rather use Service Reference because it works better with source control. Both work with SOAP protocols.

I find it better to use the Service Reference because it is new and will thus be better maintained.

How to get the filename without the extension from a path in Python?

@IceAdor's refers to rsplit in a comment to @user2902201's solution. rsplit is the simplest solution that supports multiple periods.

Here it is spelt out:

file = 'my.report.txt'
print file.rsplit('.', 1)[0]

my.report

Pure Javascript listen to input value change

Default usage

el.addEventListener('input', function () {
    fn();
});

But, if you want to fire event when you change inputs value manualy via JS you should use custom event(any name, like 'myEvent' \ 'ev' etc.) IF you need to listen forms 'change' or 'input' event and you change inputs value via JS - you can name your custom event 'change' \ 'input' and it will work too.

var event = new Event('input');
el.addEventListener('input', function () { 
  fn();
});
form.addEventListener('input', function () { 
  anotherFn();
});


el.value = 'something';
el.dispatchEvent(input);

https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Creating_and_triggering_events

Creating a timer in python

mins = minutes + 1

should be

minutes = minutes + 1

Also,

minutes = 0

needs to be outside of the while loop.

Style jQuery autocomplete in a Bootstrap input field

I don't know if you fixed it, but I did had the same issue, finally it was a dumb thing, I had:

<script src="jquery-ui/jquery-ui.min.css" rel="stylesheet">

but it should be:

<link href="jquery-ui/jquery-ui.min.css" rel="stylesheet">

Just change <scrip> to <link> and src to href

Postgres ERROR: could not open file for reading: Permission denied

Copy the CSV file to /tmp

For me this solved the issue.

ToString() function in Go

I prefer something like the following:

type StringRef []byte

func (s StringRef) String() string {
        return string(s[:])
}

…

// rather silly example, but ...
fmt.Printf("foo=%s\n",StringRef("bar"))

how to parse xml to java object?

One thing that is really important to understand considering you have an XML file as :

<customer id="100">
    <Age>29</Age>
    <NAME>mkyong</NAME>
</customer>

I am sorry to inform you but :

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

will not help you, as it tries to look for "age" instead of "Age" element name from the XML.

I encourage you to manually specify the element name matching the one in the XML file :

@XmlElement(name="Age")
public void setAge(int age) {
    this.age = age;
}

And if you have for example :

@XmlRootElement
@XmlAccessorType (XmlAccessType.FIELD)
public class Customer {
...

It means it will use java beans by default, and at this time if you specify that you must not set another

@XmlElement(name="NAME")

annotation above a setter method for an element <NAME>..</NAME> it will fail saying that there cannot be two elements on one single variables.

I hope that it helps.

How to remove the underline for anchors(links)?

Use css property,

text-decoration:none;

To remove underline from the link.

Assigning strings to arrays of characters

1    char s[100];
2    s = "hello";

In the example you provided, s is actually initialized at line 1, not line 2. Even though you didn't assign it a value explicitly at this point, the compiler did.

At line 2, you're performing an assignment operation, and you cannot assign one array of characters to another array of characters like this. You'll have to use strcpy() or some kind of loop to assign each element of the array.

How can I enable MySQL's slow query log without restarting MySQL?

This should work on mysql > 5.5

SHOW VARIABLES LIKE '%long%';

SET GLOBAL long_query_time = 1;

How to add parameters into a WebRequest?

If these are the parameters of url-string then you need to add them through '?' and '&' chars, for example http://example.com/index.aspx?username=Api_user&password=Api_password.

If these are the parameters of POST request, then you need to create POST data and write it to request stream. Here is sample method:

private static string doRequestWithBytesPostData(string requestUri, string method, byte[] postData,
                                        CookieContainer cookieContainer,
                                        string userAgent, string acceptHeaderString,
                                        string referer,
                                        string contentType, out string responseUri)
        {
            var result = "";
            if (!string.IsNullOrEmpty(requestUri))
            {
                var request = WebRequest.Create(requestUri) as HttpWebRequest;
                if (request != null)
                {
                    request.KeepAlive = true;
                    var cachePolicy = new RequestCachePolicy(RequestCacheLevel.BypassCache);
                    request.CachePolicy = cachePolicy;
                    request.Expect = null;
                    if (!string.IsNullOrEmpty(method))
                        request.Method = method;
                    if (!string.IsNullOrEmpty(acceptHeaderString))
                        request.Accept = acceptHeaderString;
                    if (!string.IsNullOrEmpty(referer))
                        request.Referer = referer;
                    if (!string.IsNullOrEmpty(contentType))
                        request.ContentType = contentType;
                    if (!string.IsNullOrEmpty(userAgent))
                        request.UserAgent = userAgent;
                    if (cookieContainer != null)
                        request.CookieContainer = cookieContainer;

                    request.Timeout = Constants.RequestTimeOut;

                    if (request.Method == "POST")
                    {
                        if (postData != null)
                        {
                            request.ContentLength = postData.Length;
                            using (var dataStream = request.GetRequestStream())
                            {
                                dataStream.Write(postData, 0, postData.Length);
                            }
                        }
                    }

                    using (var httpWebResponse = request.GetResponse() as HttpWebResponse)
                    {
                        if (httpWebResponse != null)
                        {
                            responseUri = httpWebResponse.ResponseUri.AbsoluteUri;
                            cookieContainer.Add(httpWebResponse.Cookies);
                            using (var streamReader = new StreamReader(httpWebResponse.GetResponseStream()))
                            {
                                result = streamReader.ReadToEnd();
                            }
                            return result;
                        }
                    }
                }
            }
            responseUri = null;
            return null;
        }

convert string to specific datetime format?

This another helpful code:

"2011-05-19 10:30:14".to_datetime.strftime('%a %b %d %H:%M:%S %Z %Y')

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

warning: implicit declaration of function

When you get the error: implicit declaration of function it should also list the offending function. Often this error happens because of a forgotten or missing header file, so at the shell prompt you can type man 2 functionname and look at the SYNOPSIS section at the top, as this section will list any header files that need to be included. Or try http://linux.die.net/man/ This is the online man pages they are hyperlinked and easy to search. Functions are often defined in the header files, including any required header files is often the answer. Like cnicutar said,

You are using a function for which the compiler has not seen a declaration ("prototype") yet.

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

Tried these but for my purposes in MS SQL Server 2005 the following was most useful, which I found at xaprb

declare @result varchar(8000);

set @result = '';

select @result = @result + name + ' '

from master.dbo.systypes;

select rtrim(@result);

@Mark as you mentioned it was the space character that caused issues for me.

./configure : /bin/sh^M : bad interpreter

Use the dos2unix command in linux to convert the saved file. example :

dos2unix file_name

SSL InsecurePlatform error when using Requests package

I don't use this in production, just some test runners. And to reiterate the urllib3 documentation

If you know what you are doing and would like to disable this and other warnings

import requests.packages.urllib3
requests.packages.urllib3.disable_warnings()

Edit / Update:

The following should also work:

import logging
import requests

# turn down requests log verbosity
logging.getLogger('requests').setLevel(logging.CRITICAL)

How to delete selected text in the vi editor

Highlighting with your mouse only highlights characters on the terminal. VI doesn't really get this information, so you have to highlight differently.

Press 'v' to enter a select mode, and use arrow keys to move that around. To delete, press x. To select lines at a time, press shift+v. To select blocks, try ctrl+v. That's good for, say, inserting lots of comment lines in front of your code :).

I'm OK with VI, but it took me a while to improve. My work mates recommended me this cheat sheet. I keep a printout on the wall for those odd moments when I forget something.

Happy hacking!

Should I initialize variable within constructor or outside constructor

Both the options can be correct depending on your situation.

A very simple example would be: If you have multiple constructors all of which initialize the variable the same way(int x=2 for each one of them). It makes sense to initialize the variable at declaration to avoid redundancy.

It also makes sense to consider final variables in such a situation. If you know what value a final variable will have at declaration, it makes sense to initialize it outside the constructors. However, if you want the users of your class to initialize the final variable through a constructor, delay the initialization until the constructor.

Entity Framework and Connection Pooling

According to Daniel Simmons:

Create a new ObjectContext instance in a Using statement for each service method so that it is disposed of before the method returns. This step is critical for scalability of your service. It makes sure that database connections are not kept open across service calls and that temporary state used by a particular operation is garbage collected when that operation is over. The Entity Framework automatically caches metadata and other information it needs in the app domain, and ADO.NET pools database connections, so re-creating the context each time is a quick operation.

This is from his comprehensive article here:

http://msdn.microsoft.com/en-us/magazine/ee335715.aspx

I believe this advice extends to HTTP requests, so would be valid for ASP.NET. A stateful, fat-client application such as a WPF application might be the only case for a "shared" context.

How to List All Redis Databases?

you can use redis-cli INFO keyspace

localhost:8000> INFO keyspace
# Keyspace
db0:keys=7,expires=0,avg_ttl=0
db1:keys=1,expires=0,avg_ttl=0
db2:keys=1,expires=0,avg_ttl=0
db11:keys=1,expires=0,avg_ttl=0

Calculating distance between two geographic locations

public double distance(Double latitude, Double longitude, double e, double f) {
        double d2r = Math.PI / 180;

        double dlong = (longitude - f) * d2r;
        double dlat = (latitude - e) * d2r;
        double a = Math.pow(Math.sin(dlat / 2.0), 2) + Math.cos(e * d2r)
                * Math.cos(latitude * d2r) * Math.pow(Math.sin(dlong / 2.0), 2)
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double d = 6367 * c;
                return d;

    }

cmake error 'the source does not appear to contain CMakeLists.txt'

You should do mkdir build and cd build while inside opencv folder, not the opencv-contrib folder. The CMakeLists.txt is there.

git checkout master error: the following untracked working tree files would be overwritten by checkout

Try git checkout -f master.

-f or --force

Source: https://www.kernel.org/pub/software/scm/git/docs/git-checkout.html

When switching branches, proceed even if the index or the working tree differs from HEAD. This is used to throw away local changes.

When checking out paths from the index, do not fail upon unmerged entries; instead, unmerged entries are ignored.

Removing leading and trailing spaces from a string

string trim(const string & sStr)
{
    int nSize = sStr.size();
    int nSPos = 0, nEPos = 1, i;
    for(i = 0; i< nSize; ++i) {
        if( !isspace( sStr[i] ) ) {
            nSPos = i ;
            break;
        }
    }
    for(i = nSize -1 ; i >= 0 ; --i) {
        if( !isspace( sStr[i] ) ) {
            nEPos = i;
            break;
        }
    }
    return string(sStr, nSPos, nEPos - nSPos + 1);
}

How to specify names of columns for x and y when joining in dplyr?

This is more a workaround than a real solution. You can create a new object test_data with another column name:

left_join("names<-"(test_data, "name"), kantrowitz, by = "name")

     name gender
1    john      M
2    bill either
3 madison      M
4    abby either
5     zzz   <NA>

How to set a cookie to expire in 1 hour in Javascript?

You can write this in a more compact way:

var now = new Date();
now.setTime(now.getTime() + 1 * 3600 * 1000);
document.cookie = "name=value; expires=" + now.toUTCString() + "; path=/";

And for someone like me, who wasted an hour trying to figure out why the cookie with expiration is not set up (but without expiration can be set up) in Chrome, here is in answer:

For some strange reason Chrome team decided to ignore cookies from local pages. So if you do this on localhost, you will not be able to see your cookie in Chrome. So either upload it on the server or use another browser.

Subset and ggplot2

Try filter to subset only the rows of P1 and P3

df2 <- filter(df, ID == "P1" | ID == "P3")

Than yo can plot Value1. vs Value2.

How to call a web service from jQuery

Incase people have a problem like myself following Marwan Aouida's answer ... the code has a small typo. Instead of "success" it says "sucess" change the spelling and the code works fine.

How to match "any character" in regular expression?

.* and .+ are for any chars except for new lines.

Double Escaping

Just in case, you would wanted to include new lines, the following expressions might also work for those languages that double escaping is required such as Java or C++:

[\\s\\S]*
[\\d\\D]*
[\\w\\W]*

for zero or more times, or

[\\s\\S]+
[\\d\\D]+
[\\w\\W]+

for one or more times.

Single Escaping:

Double escaping is not required for some languages such as, C#, PHP, Ruby, PERL, Python, JavaScript:

[\s\S]*
[\d\D]*
[\w\W]*
[\s\S]+
[\d\D]+
[\w\W]+

Test

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class RegularExpression{

    public static void main(String[] args){

        final String regex_1 = "[\\s\\S]*";
        final String regex_2 = "[\\d\\D]*";
        final String regex_3 = "[\\w\\W]*";
        final String string = "AAA123\n\t"
             + "ABCDEFGH123\n\t"
             + "XXXX123\n\t";

        final Pattern pattern_1 = Pattern.compile(regex_1);
        final Pattern pattern_2 = Pattern.compile(regex_2);
        final Pattern pattern_3 = Pattern.compile(regex_3);

        final Matcher matcher_1 = pattern_1.matcher(string);
        final Matcher matcher_2 = pattern_2.matcher(string);
        final Matcher matcher_3 = pattern_3.matcher(string);

        if (matcher_1.find()) {
            System.out.println("Full Match for Expression 1: " + matcher_1.group(0));
        }

        if (matcher_2.find()) {
            System.out.println("Full Match for Expression 2: " + matcher_2.group(0));
        }
        if (matcher_3.find()) {
            System.out.println("Full Match for Expression 3: " + matcher_3.group(0));
        }
    }
}

Output

Full Match for Expression 1: AAA123
    ABCDEFGH123
    XXXX123

Full Match for Expression 2: AAA123
    ABCDEFGH123
    XXXX123

Full Match for Expression 3: AAA123
    ABCDEFGH123
    XXXX123

If you wish to explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

How to get time (hour, minute, second) in Swift 3 using NSDate?

For best useful I create this function:

func dateFormatting() -> String {
    let date = Date()
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "EEEE dd MMMM yyyy - HH:mm:ss"//"EE" to get short style
    let mydt = dateFormatter.string(from: date).capitalized

    return "\(mydt)"
}

You simply call it wherever you want like this:

print("Date = \(self.dateFormatting())")

this is the Output:

Date = Monday 15 October 2018 - 17:26:29

if want only the time simply change :

dateFormatter.dateFormat  = "HH:mm:ss"

and this is the output:

Date = 17:27:30

and that's it...

Why should text files end with a newline?

Because that’s how the POSIX standard defines a line:

3.206 Line
A sequence of zero or more non- <newline> characters plus a terminating <newline> character.

Therefore, lines not ending in a newline character aren't considered actual lines. That's why some programs have problems processing the last line of a file if it isn't newline terminated.

There's at least one hard advantage to this guideline when working on a terminal emulator: All Unix tools expect this convention and work with it. For instance, when concatenating files with cat, a file terminated by newline will have a different effect than one without:

$ more a.txt
foo
$ more b.txt
bar$ more c.txt
baz
$ cat {a,b,c}.txt
foo
barbaz

And, as the previous example also demonstrates, when displaying the file on the command line (e.g. via more), a newline-terminated file results in a correct display. An improperly terminated file might be garbled (second line).

For consistency, it’s very helpful to follow this rule – doing otherwise will incur extra work when dealing with the default Unix tools.


Think about it differently: If lines aren’t terminated by newline, making commands such as cat useful is much harder: how do you make a command to concatenate files such that

  1. it puts each file’s start on a new line, which is what you want 95% of the time; but
  2. it allows merging the last and first line of two files, as in the example above between b.txt and c.txt?

Of course this is solvable but you need to make the usage of cat more complex (by adding positional command line arguments, e.g. cat a.txt --no-newline b.txt c.txt), and now the command rather than each individual file controls how it is pasted together with other files. This is almost certainly not convenient.

… Or you need to introduce a special sentinel character to mark a line that is supposed to be continued rather than terminated. Well, now you’re stuck with the same situation as on POSIX, except inverted (line continuation rather than line termination character).


Now, on non POSIX compliant systems (nowadays that’s mostly Windows), the point is moot: files don’t generally end with a newline, and the (informal) definition of a line might for instance be “text that is separated by newlines” (note the emphasis). This is entirely valid. However, for structured data (e.g. programming code) it makes parsing minimally more complicated: it generally means that parsers have to be rewritten. If a parser was originally written with the POSIX definition in mind, then it might be easier to modify the token stream rather than the parser — in other words, add an “artificial newline” token to the end of the input.

Wait until flag=true

Try avoid while loop as it could be blocking your code, use async and promises.

Just wrote this library:

https://www.npmjs.com/package/utilzed

There is a function waitForTrue

import utilzed from 'utilzed'

const checkCondition = async () => {
  // anything that you are polling for to be expecting to be true
  const response = await callSomeExternalApi();
  return response.success;
}

// this will waitForTrue checkCondition to be true
// checkCondition will be called every 100ms
const success = await utilzed.waitForTrue(100, checkCondition, 1000);

if (success) {
  // Meaning checkCondition function returns true before 1000 ms
  return;
}

// meaning after 1000ms the checkCondition returns false still
// handle unsuccessful "poll for true" 

Passing command line arguments from Maven as properties in pom.xml

Inside pom.xml

<project>

.....

<profiles>
    <profile>
        <id>linux64</id>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
        <properties>
            <build_os>linux</build_os>
            <build_ws>gtk</build_ws>
            <build_arch>x86_64</build_arch>
        </properties>
    </profile>

    <profile>
        <id>win64</id>
        <activation>
            <property>
                <name>env</name>
                <value>win64</value>
            </property>
        </activation>
        <properties>
            <build_os>win32</build_os>
            <build_ws>win32</build_ws>
            <build_arch>x86_64</build_arch>
        </properties>
    </profile>
</profiles>

.....

<plugin>
    <groupId>org.eclipse.tycho</groupId>
    <artifactId>target-platform-configuration</artifactId>
    <version>${tycho.version}</version>
    <configuration>
        <environments>
            <environment>
                <os>${build_os}</os>
                <ws>${build_ws}</ws>
                <arch>${build_arch}</arch>
            </environment>
        </environments>
    </configuration>
</plugin>

.....

In this example when you run the pom without any argument mvn clean install default profile will execute.

When executed with mvn -Denv=win64 clean install

win64 profile will executed.

Please refer http://maven.apache.org/guides/introduction/introduction-to-profiles.html

Classes cannot be accessed from outside package

closeDrawers(boolean) is not public in android.support.v4.widget.DrawerLayout. Cannot be accessed from outside package

@Override
public void onBackPressed() {
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
       super.onBackPressed();
    }
}

No mapping found for HTTP request with URI Spring MVC

I have the same problem.... I change my project name and i have this problem...my solution was the checking project refences and use / in my web.xml (instead of /*)

Convert factor to integer

You can combine the two functions; coerce to characters thence to numerics:

> fac <- factor(c("1","2","1","2"))
> as.numeric(as.character(fac))
[1] 1 2 1 2

How to throw std::exceptions with variable messages?

Here is my solution:

#include <stdexcept>
#include <sstream>

class Formatter
{
public:
    Formatter() {}
    ~Formatter() {}

    template <typename Type>
    Formatter & operator << (const Type & value)
    {
        stream_ << value;
        return *this;
    }

    std::string str() const         { return stream_.str(); }
    operator std::string () const   { return stream_.str(); }

    enum ConvertToString 
    {
        to_str
    };
    std::string operator >> (ConvertToString) { return stream_.str(); }

private:
    std::stringstream stream_;

    Formatter(const Formatter &);
    Formatter & operator = (Formatter &);
};

Example:

throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData);   // implicitly cast to std::string
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str);    // explicitly cast to std::string

Disable clipboard prompt in Excel VBA on workbook close

If you don't want to save any changes and don't want that Save prompt while saving an Excel file using Macro then this piece of code may helpful for you

Sub Auto_Close()

     ThisWorkbook.Saved = True

End Sub

Because the Saved property is set to True, Excel responds as though the workbook has already been saved and no changes have occurred since that last save, so no Save prompt.

How to create new folder?

Have you tried os.mkdir?

You might also try this little code snippet:

mypath = ...
if not os.path.isdir(mypath):
   os.makedirs(mypath)

makedirs creates multiple levels of directories, if needed.

Circular dependency in Spring

Problem ->

Class A {
    private final B b; // must initialize in ctor/instance block
    public A(B b) { this.b = b };
}


Class B {
    private final A a; // must initialize in ctor/instance block
    public B(A a) { this.a = a };
 }

// Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'A': Requested bean is currently in creation: Is there an unresolvable circular reference?

Solution 1 ->

Class A {
    private B b; 
    public A( ) {  };
    //getter-setter for B b
}

Class B {
    private A a;
    public B( ) {  };
    //getter-setter for A a
}

Solution 2 ->

Class A {
    private final B b; // must initialize in ctor/instance block
    public A(@Lazy B b) { this.b = b };
}

Class B {
    private final A a; // must initialize in ctor/instance block
    public B(A a) { this.a = a };
}

Using Pandas to pd.read_excel() for multiple worksheets of the same workbook

Yes unfortunately it will always load the full file. If you're doing this repeatedly probably best to extract the sheets to separate CSVs and then load separately. You can automate that process with d6tstack which also adds additional features like checking if all the columns are equal across all sheets or multiple Excel files.

import d6tstack
c = d6tstack.convert_xls.XLStoCSVMultiSheet('multisheet.xlsx')
c.convert_all() # ['multisheet-Sheet1.csv','multisheet-Sheet2.csv']

See d6tstack Excel examples

How can I use JSON data to populate the options of a select box?

zeusstl is right. it works for me too.

   <select class="form-control select2" id="myselect">
                      <option disabled="disabled" selected></option>
                      <option>Male</option>
                      <option>Female</option>
                    </select>

   $.getJSON("mysite/json1.php", function(json){
        $('#myselect').empty();
        $('#myselect').append($('<option>').text("Select"));
        $.each(json, function(i, obj){

  $('#myselect').append($('<option>').text(obj.text).attr('value', obj.val));
        });
  });

Linux: command to open URL in default browser

At least on Debian and all its derivatives, there is a 'sensible-browser' shell script which choose the browser best suited for the given url.

http://man.he.net/man1/sensible-browser

HTML5 iFrame Seamless Attribute

According to the latest W3C HTML5 recommendation (which is likely to be the final HTML5 standard) published today, there is no seamless attribute in the iframe element anymore. It seems to have been removed somewhere in the standardization process.

According to caniuse.com no major browser does support this attribute (anymore), so you probably shouldn't use it.

Fixing slow initial load for IIS

See this article for tips on how to help performance issues. This includes both performance issues related to starting up, under the "cold start" section. Most of this will matter no matter what type of server you are using, locally or in production.

https://blogs.msdn.microsoft.com/b/mcsuksoldev/2011/01/19/common-performance-issues-on-asp-net-web-sites/

If the application deserializes anything from XML (and that includes web services…) make sure SGEN is run against all binaries involved in deseriaization and place the resulting DLLs in the Global Assembly Cache (GAC). This precompiles all the serialization objects used by the assemblies SGEN was run against and caches them in the resulting DLL. This can give huge time savings on the first deserialization (loading) of config files from disk and initial calls to web services. http://msdn.microsoft.com/en-us/library/bk3w6240(VS.80).aspx

If any IIS servers do not have outgoing access to the internet, turn off Certificate Revocation List (CRL) checking for Authenticode binaries by adding generatePublisherEvidence=”false” into machine.config. Otherwise every worker processes can hang for over 20 seconds during start-up while it times out trying to connect to the internet to obtain a CRL list. http://blogs.msdn.com/amolravande/archive/2008/07/20/startup-performance-disable-the-generatepublisherevidence-property.aspx

http://msdn.microsoft.com/en-us/library/bb629393.aspx

Consider using NGEN on all assemblies. However without careful use this doesn’t give much of a performance gain. This is because the base load addresses of all the binaries that are loaded by each process must be carefully set at build time to not overlap. If the binaries have to be rebased when they are loaded because of address clashes, almost all the performance gains of using NGEN will be lost. http://msdn.microsoft.com/en-us/magazine/cc163610.aspx

Angular2 - Input Field To Accept Only Numbers

Use pattern attribute for input like below:

<input type="text" pattern="[0-9]+" >

Display SQL query results in php

You need to do a while loop to get the result from the SQL query, like this:

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )    
FROM modul1open) ORDER BY idM1O LIMIT 1";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {

    // If you want to display all results from the query at once:
    print_r($row);

    // If you want to display the results one by one
    echo $row['column1'];
    echo $row['column2']; // etc..

}

Also I would strongly recommend not using mysql_* since it's deprecated. Instead use the mysqli or PDO extension. You can read more about that here.

How do I get next month date from today's date and insert it in my database?

Adding my solution here, as this is the thread that comes in google search. This is to get the next date of month, fixing any skips, keeping the next date within next month.

PHP adds current months total number of days to current date, if you do +1 month for example.

So applying +1 month to 30-01-2016 will return 02-03-2016. (Adding 31 days)

For my case, I needed to get 28-02-2016, so as to keep it within next month. In such cases you can use the solution below.

This code will identify if the given date's day is greater than next month's total days. If so It will subtract the days smartly and return the date within the month range.

Do note the return value is in timestamp format.

function getExactDateAfterMonths($timestamp, $months){
    $day_current_date            = date('d', $timestamp);
    $first_date_of_current_month = date('01-m-Y', $timestamp);
    // 't' gives last day of month, which is equal to no of days
    $days_in_next_month          = date('t',  strtotime("+".$months." months", strtotime($first_date_of_current_month)));

    $days_to_substract = 0;
    if($day_current_date > $days_in_next_month)
         $days_to_substract = $day_current_date - $days_in_next_month;

    $php_date_after_months   = strtotime("+".$months." months", $timestamp);
    $exact_date_after_months = strtotime("-".$days_to_substract." days", $php_date_after_months);

    return $exact_date_after_months;
}

getExactDateAfterMonths(strtotime('30-01-2016'), 1);
// $php_date_after_months   => 02-03-2016
// $exact_date_after_months => 28-02-2016

Why is my element value not getting changed? Am I using the wrong function?

Sounds like we need to assume that your textbox name and ID are both set to "Tue." If that's the case, try using a lower-case V on .value.

Android ADB devices unauthorized

I had the same problem after reinstalled my android studio. Here's what I did to make my adb work again:

-path to C:\Users\User\AppData\Local\Android\sdk\platform-tools
-Shift+r.click and start command from here instead.

How to remove constraints from my MySQL table?

this will works on MySQL to drop constraints

alter table tablename drop primary key;

alter table tablename drop foreign key;

How to remove an element from a list by index

It doesn't sound like you're working with a list of lists, so I'll keep this short. You want to use pop since it will remove elements not elements that are lists, you should use del for that. To call the last element in python it's "-1"

>>> test = ['item1', 'item2']
>>> test.pop(-1)
'item2'
>>> test
['item1']

How to sort the letters in a string alphabetically in Python

Python functionsorted returns ASCII based result for string.

INCORRECT: In the example below, e and d is behind H and W due it's to ASCII value.

>>>a = "Hello World!"
>>>"".join(sorted(a))
' !!HWdellloor'

CORRECT: In order to write the sorted string without changing the case of letter. Use the code:

>>> a = "Hello World!"
>>> "".join(sorted(a,key=lambda x:x.lower()))
' !deHllloorW'

If you want to remove all punctuation and numbers. Use the code:

>>> a = "Hello World!"
>>> "".join(filter(lambda x:x.isalpha(), sorted(a,key=lambda x:x.lower())))
'deHllloorW'

How can I disable all views inside the layout?

You can have whichever children that you want to have the same state as the parents include android:duplicateParentState="true".  Then if you disable the parent, whatever children you have that set on will follow suit.  

This will allow you to dynamically control all states at once from the parent view.

<LinearLayout
    android:id="@+id/some_parent_something"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
     <Button 
        android:id="@+id/backbutton"
        android:text="Back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        android:duplicateParentState="true"/>
    <LinearLayout
        android:id="@+id/my_layout"
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" 
        android:duplicateParentState="true">
        <TextView
            android:id="@+id/my_text_view"
            android:text="First Name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:duplicateParentState="true" />
        <EditText
            android:id="@+id/my_edit_view"
            android:width="100px"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" 
            android:duplicateParentState="true" /> 
        <View .../>
        <View .../>
        ...
           <View .../>
    </LinearLayout>

</LinearLayout>

Java and HTTPS url connection without downloading certificate

If you are using any Payment Gateway to hit any url just to send a message, then i used a webview by following it : How can load https url without use of ssl in android webview

and make a webview in your activity with visibility gone. What you need to do : just load that webview.. like this:

 webViewForSms.setWebViewClient(new SSLTolerentWebViewClient());
                webViewForSms.loadUrl(" https://bulksms.com/" +
                        "?username=test&password=test@123&messageType=text&mobile="+
                        mobileEditText.getText().toString()+"&senderId=ATZEHC&message=Your%20OTP%20for%20A2Z%20registration%20is%20124");

Easy.

You will get this: SSLTolerentWebViewClient from this link: How can load https url without use of ssl in android webview

How to remove all files from directory without removing directory in Node.js

There is package called rimraf that is very handy. It is the UNIX command rm -rf for node.

Nevertheless, it can be too powerful too because you can delete folders very easily using it. The following commands will delete the files inside the folder. If you remove the *, you will remove the log folder.

const rimraf = require('rimraf');
rimraf('./log/*', function () { console.log('done'); });

https://www.npmjs.com/package/rimraf

How to restart Postgresql

macOS:

  1. On the top left of the MacOS menu bar you have the Postgres Icon
  2. Click on it this opens a drop down menu
  3. Click on Stop -> than click on start

Android: How to create a Dialog without a title?

ProgressDialog dialog = ProgressDialog.show(MyActivity.this, "", 
                             "Loading. Please wait...", true);

creates a title less dialog