Programs & Examples On #Background thread

A background thread is a thread that not directly driving the application but does some processing asynchronously.

Getting a "This application is modifying the autolayout engine from a background thread" error?

For me the issue was the following. Make sure performSegueWithIdentifier: is performed on the main thread:

dispatch_async (dispatch_get_main_queue(), ^{
  [self performSegueWithIdentifier:@"ViewController" sender:nil];
});

How to run certain task every day at a particular time using ScheduledExecutorService?

Have you considered using something like Quartz Scheduler? This library has a mechanism for scheduling tasks to run at a set period of time every day using a cron like expression (take a look at CronScheduleBuilder).

Some example code (not tested):

public class GetDatabaseJob implements InterruptableJob
{
    public void execute(JobExecutionContext arg0) throws JobExecutionException
    {
        getFromDatabase();
    }
}

public class Example
{
    public static void main(String[] args)
    {
        JobDetails job = JobBuilder.newJob(GetDatabaseJob.class);

        // Schedule to run at 5 AM every day
        ScheduleBuilder scheduleBuilder = 
                CronScheduleBuilder.cronSchedule("0 0 5 * * ?");
        Trigger trigger = TriggerBuilder.newTrigger().
                withSchedule(scheduleBuilder).build();

        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.scheduleJob(job, trigger);

        scheduler.start();
    }
}

There's a bit more work upfront, and you may need to rewrite your job execution code, but it should give you more control over how you want you job to run. Also it would be easier to change the schedule should you need to.

angular.service vs angular.factory

All the answers here seem to be around service and factory, and that's valid since that was what was being asked about. But it's also important to keep in mind that there are several others including provider(), value(), and constant().

The key to remember is that each one is a special case of the other. Each special case down the chain allowing you to do the same thing with less code. Each one also having some additional limitation.

To decide when to use which you just see which one allows you to do what you want in less code. Here is an image illustrating just how similar they are:

enter image description here

For a complete step by step breakdown and quick reference of when to use each you can visit the blog post where I got this image from:

http://www.simplygoodcode.com/2015/11/the-difference-between-service-provider-and-factory-in-angularjs/

Simple JavaScript problem: onClick confirm not preventing default action

I use this, works like a charm. No need to have any functions, just inline with your link(s)

onclick="javascript:return confirm('Are you sure you want to delete this comment?')"

How to do a scatter plot with empty circles in Python?

Basend on the example of Gary Kerr and as proposed here one may create empty circles related to specified values with following code:

import matplotlib.pyplot as plt 
import numpy as np 
from matplotlib.markers import MarkerStyle

x = np.random.randn(60) 
y = np.random.randn(60)
z = np.random.randn(60)

g=plt.scatter(x, y, s=80, c=z)
g.set_facecolor('none')
plt.colorbar()
plt.show()

How to type a new line character in SQL Server Management Studio

If you are trying to enter data directly into the table in grid view (presumably Right Click TableName and Select Open Table), then you can enter your unicode text string and wherever you want a carriage return just type 13 with the alt key pressed in the numeric keypad.

That would be Alt+13. This works only from the numeric keypad and does not work with the number keys on the top of the keyboard. The carriage return will be stored as a square

malloc an array of struct pointers

array is a slightly misleading name. For a dynamically allocated array of pointers, malloc will return a pointer to a block of memory. You need to use Chess* and not Chess[] to hold the pointer to your array.

Chess *array = malloc(size * sizeof(Chess));
array[i] = NULL;

and perhaps later:

/* create new struct chess */
array[i] = malloc(sizeof(struct chess));

/* set up its members */
array[i]->size = 0;
/* etc. */

jQuery how to bind onclick event to dynamically added HTML element

I believe the good way it to do:

$('#id').append('<a id="#subid" href="#">...</a>');
$('#subid').click( close_link );

HTML5 Form Input Pattern Currency Format

Another answer for this would be

^((\d+)|(\d{1,3})(\,\d{3}|)*)(\.\d{2}|)$

This will match a string of:

  • one or more numbers with out the decimal place (\d+)
  • any number of commas each of which must be followed by 3 numbers and have upto 3 numbers before it (\d{1,3})(\,\d{3}|)*

Each or which can have a decimal place which must be followed by 2 numbers (.\d{2}|)

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

function rmdir_recursive( $dirname ) {

    /**
     * FilesystemIterator and SKIP_DOTS
     */

    if ( class_exists( 'FilesystemIterator' ) && defined( 'FilesystemIterator::SKIP_DOTS' ) ) {

        if ( !is_dir( $dirname ) ) {
            return false;
        }

        foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname, FilesystemIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) {
            $path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() );
        }

        return rmdir( $dirname );

    }

    /**
     * RecursiveDirectoryIterator and SKIP_DOTS
     */

    if ( class_exists( 'RecursiveDirectoryIterator' ) && defined( 'RecursiveDirectoryIterator::SKIP_DOTS' ) ) {

        if ( !is_dir( $dirname ) ) {
            return false;
        }

        foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname, RecursiveDirectoryIterator::SKIP_DOTS ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) {
            $path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() );
        }

        return rmdir( $dirname );

    }

    /**
     * RecursiveIteratorIterator and RecursiveDirectoryIterator
     */

    if ( class_exists( 'RecursiveIteratorIterator' ) && class_exists( 'RecursiveDirectoryIterator' ) ) {

        if ( !is_dir( $dirname ) ) {
            return false;
        }

        foreach( new RecursiveIteratorIterator( new RecursiveDirectoryIterator( $dirname ), RecursiveIteratorIterator::CHILD_FIRST ) as $path ) {
            if ( in_array( $path->getFilename(), array( '.', '..' ) ) ) {
                continue;
            }
            $path->isDir() ? rmdir( $path->getPathname() ) : unlink( $path->getRealPath() );
        }

        return rmdir( $dirname );

    }

    /**
     * Scandir Recursive
     */

    if ( !is_dir( $dirname ) ) {
        return false;
    }

    $objects = scandir( $dirname );

    foreach ( $objects as $object ) {
        if ( $object === '.' || $object === '..' ) {
            continue;
        }
        filetype( $dirname . DIRECTORY_SEPARATOR . $object ) === 'dir' ? rmdir_recursive( $dirname . DIRECTORY_SEPARATOR . $object ) : unlink( $dirname . DIRECTORY_SEPARATOR . $object );
    }

    reset( $objects );
    rmdir( $dirname );

    return !is_dir( $dirname );

}

What does Visual Studio mean by normalize inconsistent line endings?

It's not just Visual Studio... It'd be any tools that read the files, compilers, linkers, etc. that would have to be able to handle it.

In general (for software development) we accept the multiplatform line ending issue, but let the version control software deal with it.

Eclipse: How to build an executable jar with external jar?

Try the fat-jar extension. It will include all external jars inside the jar.

Virtual Serial Port for Linux

Use socat for this:

For example:

socat PTY,link=/dev/ttyS10 PTY,link=/dev/ttyS11

How to "grep" for a filename instead of the contents of a file?

find . | grep KeywordToSearch

Here . means current directory which is value for path parameter for find command. It is piped to grep to search keyword which should return all matching result.

Note: This is case sensitive. So for example fileName and FileName are not same.

Assigning default value while creating migration file

Yes, I couldn't see how to use 'default' in the migration generator command either but was able to specify a default value for a new string column as follows by amending the generated migration file before applying "rake db:migrate":

class AddColumnToWidgets < ActiveRecord::Migration
  def change
    add_column :widgets, :colour, :string, default: 'red'
  end
end

This adds a new column called 'colour' to my 'Widget' model and sets the default 'colour' of new widgets to 'red'.

Cannot find either column "dbo" or the user-defined function or aggregate "dbo.Splitfn", or the name is ambiguous

A general answer

select * from [dbo].[SplitString]('1,2',',') -- Will work 

but

select [dbo].[SplitString]('1,2',',')  -- will not work and throws this error

PHP mkdir: Permission denied problem

This error occurs if you are using the wrong path.

For e.g:

I'm using ubuntu system and my project folder name is 'myproject'

Suppose I have myproject/public/report directory exist and want to create a new folder called orders

Then I need a whole path where my project exists. You can get the path by PWD command

So my root path will be = '/home/htdocs/myproject/'

$dir = '/home/htdocs/myproject/public/report/Orders';

if (!is_dir($dir)) {
   mkdir($dir, 0775, true);
}

It will work for you !! Enjoy !!

When to use CouchDB over MongoDB and vice versa

The answers above all over complicate the story.

  1. If you plan to have a mobile component, or need desktop users to work offline and then sync their work to a server you need CouchDB.
  2. If your code will run only on the server then go with MongoDB

That's it. Unless you need CouchDB's (awesome) ability to replicate to mobile and desktop devices, MongoDB has the performance, community and tooling advantage at present.

Convert byte to string in Java

System.out.println(new String(new byte[]{ (byte)0x63 }, "US-ASCII"));

Note especially that converting bytes to Strings always involves an encoding. If you do not specify it, you'll be using the platform default encoding, which means the code can break when running in different environments.

Tomcat Server not starting with in 45 seconds

Folks, I had this same problem and tried raising the timeout, deleting the server and creating again and did not work. I was running Eclipse Kepler in Linux. The solution proposed by @Phoenix is what worked for me:

Window -> Preferences -> General -> Network Connections

Set Active Providers in manual and then configure or not the proxy. I had this option in "Native".

Then I realized I had the variable http_proxy set. It was set in the ~/.bashrc file. This environment variable is the culprit of many problems.

Once I set http_proxy to empty

export http_proxy=

to check it:

echo $http_proxy

I was able to leave option "Active Provider" in "Native" and solve the timeout problem. This is useful because Eclipse adopts the native configuration, in case you change it often.

In my case, where I had configured http_proxy in ~./bashrc, I had to close Eclipse and even log out and log in again.

JQuery wait for page to finish loading before starting the slideshow?

did you try this ?

$("#yourdiv").load(url, function(){ 

         your functions goes here !!!

}); 

How to check if a .txt file is in ASCII or UTF-8 format in Windows environment?

If you use Windows 10 and has Windows Subsystem for Linux (WSL), it can be easily done by typing "file " from the shell.

For example:

$ file code.cpp

code.cpp: C source, UTF-8 Unicode (with BOM) text, with CRLF line terminators

Change UITableView height dynamically

This can be massively simplified with just 1 line of code in viewDidAppear:

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)

        tableViewHeightConstraint.constant = tableView.contentSize.height
    }

Change Primary Key

Assuming that your table name is city and your existing Primary Key is pk_city, you should be able to do the following:

ALTER TABLE city
DROP CONSTRAINT pk_city;

ALTER TABLE city
ADD CONSTRAINT pk_city PRIMARY KEY (city_id, buildtime, time);

Make sure that there are no records where time is NULL, otherwise you won't be able to re-create the constraint.

Extreme wait-time when taking a SQL Server database offline

Also, close any query windows you may have open that are connected to the database in question ;)

Get the last insert id with doctrine 2?

Calling flush() can potentially add lots of new entities, so there isnt really the notion of "lastInsertId". However Doctrine will populate the identity fields whenever one is generated, so accessing the id field after calling flush will always contain the ID of a newly "persisted" entity.

How to change line-ending settings

For a repository setting solution, that can be redistributed to all developers, check out the text attribute in the .gitattributes file. This way, developers dont have to manually set their own line endings on the repository, and because different repositories can have different line ending styles, global core.autocrlf is not the best, at least in my opinion.

For example unsetting this attribute on a given path [. - text] will force git not to touch line endings when checking in and checking out. In my opinion, this is the best behavior, as most modern text editors can handle both type of line endings. Also, if you as a developer still want to do line ending conversion when checking in, you can still set the path to match certain files or set the eol attribute (in .gitattributes) on your repository.

Also check out this related post, which describes .gitattributes file and text attribute in more detail: What's the best CRLF (carriage return, line feed) handling strategy with Git?

Android - How to decode and decompile any APK file?

You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.

Rollback one specific migration in Laravel

If you look in your migrations table, then you’ll see each migration has a batch number. So when you roll back, it rolls back each migration that was part of the last batch.

If you only want to roll back the very last migration, then just increment the batch number by one. Then next time you run the rollback command, it’ll only roll back that one migration as it’s in a “batch” of its own.

Alternatively, from Laravel 5.3 onwards, you can just run:

php artisan migrate:rollback --step=1

That will rollback the last migration, no matter what its batch number is.

How to show "if" condition on a sequence diagram?

If you paste

A.do() {
  if (condition1) {
   X.doSomething
  } else if (condition2) {
   Y.doSomethingElse
  } else {
   donotDoAnything
  }
}

onto https://www.zenuml.com. It will generate a diagram for you.If/else sequence diagram

HTML Form: Select-Option vs Datalist-Option

I noticed that there is no selected feature in datalist. It only gives you choice but can't have a default option. You can't show the selected option on the next page either.

Regular expression for not allowing spaces in the input field

While you have specified the start anchor and the first letter, you have not done anything for the rest of the string. You seem to want repetition of that character class until the end of the string:

var regexp = /^\S*$/; // a string consisting only of non-whitespaces

Redirecting to a relative URL in JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

  • window.location.assign("../"); // one level up
  • window.location.assign("/path"); // relative to domain

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

How to get a path to a resource in a Java JAR file

This is same code from user Tombart with stream flush and close to avoid incomplete temporary file content copy from jar resource and to have unique temp file names.

File file = null;
String resource = "/view/Trial_main.html" ;
URL res = getClass().getResource(resource);
if (res.toString().startsWith("jar:")) {
    try {
        InputStream input = getClass().getResourceAsStream(resource);
        file = File.createTempFile(new Date().getTime()+"", ".html");
        OutputStream out = new FileOutputStream(file);
        int read;
        byte[] bytes = new byte[1024];

        while ((read = input.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
        input.close();
        file.deleteOnExit();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
} else {
    //this will probably work in your IDE, but not from a JAR
    file = new File(res.getFile());
}
         

FFmpeg on Android

The most easy to build, easy to use implementation I have found is made by theguardianproject team: https://github.com/guardianproject/android-ffmpeg

Number of visitors on a specific page

If you want to know the number of visitors (as is titled in the question) and not the number of pageviews, then you'll need to create a custom report.

 

Terminology


Google Analytics has changed the terminology they use within the reports. Now, visits is named "sessions" and unique visitors is named "users."

User - A unique person who has visited your website. Users may visit your website multiple times, and they will only be counted once.

Session - The number of different times that a visitor came to your site.

Pageviews - The total number of pages that a user has accessed.

 

Creating a Custom Report


  1. To create a custom report, click on the "Customization" item in the left navigation menu, and then click on "Custom Reports".

customization item expanded in navigation menu

  1. The "Create Custom Report" page will open.
  2. Enter a name for your report.
  3. In the "Metric Groups" section, enter either "Users" or "Sessions" depending on what information you want to collect (see Terminology, above).
  4. In the "Dimension Drilldowns" section, enter "Page".
  5. Under "Filters" enter the individual page (exact) or group of pages (using regex) that you would like to see the data for. enter image description here
  6. Save the report and run it.

How can I convert a string with dot and comma into a float in Python

Just replace, with replace().

f = float("123,456.908".replace(',','')) print(type(f)

type() will show you that it has converted into a float

SQL LIKE condition to check for integer?

PostgreSQL supports regular expressions matching.

So, your example would look like

SELECT * FROM books WHERE title ~ '^\d+ ?' 

This will match a title starting with one or more digits and an optional space

gridview data export to excel in asp.net

I don't there there is any DataSource for the gridview
Though you have DataBind in your code as

gvdetails.DataBind(); 

Variable that has the path to the current ansible-playbook that is executing?

There don't seem to be a variable which holds exactly what you want.

However, quoting the docs:

Also available, inventory_dir is the pathname of the directory holding Ansible’s inventory host file, inventory_file is the pathname and the filename pointing to the Ansible’s inventory host file.

playbook_dir contains the playbook base directory.

And finally, role_path will return the current role’s pathname (since 1.8). This will only work inside a role.

Dependent on your setup, those or the $ pwd -based solution might be enough.

jQuery location href

Use:

window.location.replace(...)

See this Stack Overflow question for more information:

How do I redirect to another webpage?

Or perhaps it was this you remember:

var url = "http://stackoverflow.com";
$(location).attr('href',url);

How to get first/top row of the table in Sqlite via Sql Query

LIMIT 1 is what you want. Just keep in mind this returns the first record in the result set regardless of order (unless you specify an order clause in an outer query).

Could not reserve enough space for object heap to start JVM

According to this post this error message means:

Heap size is larger than your computer's physical memory.

Edit: Heap is not the only memory that is reserved, I suppose. At least there are other JVM settings like PermGenSpace that ask for the memory. With heap size 128M and a PermGenSpace of 64M you already fill the space available.

Why not downsize other memory settings to free up space for the heap?

Clearing NSUserDefaults

Expanding on @folse's answer... I believe a more correct implementation would be...

NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
NSDictionary *defaultsDictionary = [[NSUserDefaults standardUserDefaults] persistentDomainForName: appDomain];
    for (NSString *key in [defaultsDictionary allKeys]) {
      NSLog(@"removing user pref for %@", key);
      [[NSUserDefaults standardUserDefaults] removeObjectForKey:key];
    }

...calling NSUserDefault's persistentDomainForName: method. As the docs state, the method "Returns a dictionary containing the keys and values in the specified persistent domain." Calling dictionaryRepresentation: instead, will return a dictionary that will likely include other settings as it applies to a wider scope.

If you need to filter out any of the values that are to be reset, then iterating over the keys is the way to do it. Obviously, if you want to just nuke all of the prefs for the app without regard, then one of the other methods posted above is the most efficient.

Why can't C# interfaces contain fields?

A lot has been said already, but to make it simple, here's my take. Interfaces are intended to have method contracts to be implemented by the consumers or classes and not to have fields to store values.

You may argue that then why properties are allowed? So the simple answer is - properties are internally defined as methods only.

How to enable cURL in PHP / XAMPP

On Debian with Apache 2:

apt-get install php5-curl
/etc/init.d/apache2 restart

(php4-curl if it's php4)

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

Look at the following example code:

public class MyWorker
{
    public SharedData state;
    public void DoWork(SharedData someData)
    {
        this.state = someData;
        while (true) ;
    }

}

public class SharedData {
    X myX;
    public getX() { etc
    public setX(anX) { etc

}

public class Program
{
    public static void Main()
    {
        SharedData data = new SharedDate()
        MyWorker work1 = new MyWorker(data);
        MyWorker work2 = new MyWorker(data);
        Thread thread = new Thread(new ThreadStart(work1.DoWork));
        thread.Start();
        Thread thread2 = new Thread(new ThreadStart(work2.DoWork));
        thread2.Start();
    }
}

In this case, the thread class MyWorker has a variable state. We initialise it with the same object. Now you can see that the two workers access the same SharedData object. Changes made by one worker are visible to the other.

You have quite a few remaining issues. How does worker 2 know when changes have been made by worker 1 and vice-versa? How do you prevent conflicting changes? Maybe read: this tutorial.

Example use of "continue" statement in Python?

Some people have commented about readability, saying "Oh it doesn't help readability that much, who cares?"

Suppose you need a check before the main code:

if precondition_fails(message): continue

''' main code here '''

Note you can do this after the main code was written without changing that code in anyway. If you diff the code, only the added line with "continue" will be highlighted since there are no spacing changes to the main code.

Imagine if you have to do a breakfix of production code, which turns out to simply be adding a line with continue. It's easy to see that's the only change when you review the code. If you start wrapping the main code in if/else, diff will highlight the newly indented code, unless you ignore spacing changes, which is dangerous particularly in Python. I think unless you've been in the situation where you have to roll out code on short notice, you might not fully appreciate this.

How to select a schema in postgres when using psql?

In PostgreSQL the system determines which table is meant by following a search path, which is a list of schemas to look in.

The first matching table in the search path is taken to be the one wanted, otherwise, if there is no match a error is raised, even if matching table names exist in other schemas in the database.

To show the current search path you can use the following command:

SHOW search_path;

And to put the new schema in the path, you could use:

SET search_path TO myschema;

Or if you want multiple schemas:

SET search_path TO myschema, public;

Reference: https://www.postgresql.org/docs/current/static/ddl-schemas.html

java.net.SocketTimeoutException: Read timed out under Tomcat

I am using 11.2 and received timeouts.

I resolved by using the version of jsoup below.

    <dependency>
        <groupId>org.jsoup</groupId>
        <artifactId>jsoup</artifactId>
        <version>1.7.2</version>
        <scope>compile</scope>
    </dependency>

How can I force browsers to print background images in CSS?

it is working in google chrome when you add !important attribute to background image make sure you add attribute first and try again, you can do it like that

    .inputbg {
background: url('inputbg.png') !important;  

}

How to perform a for loop on each character in a string in Bash?

I'm surprised no one has mentioned the obvious bash solution utilizing only while and read.

while read -n1 character; do
    echo "$character"
done < <(echo -n "$words")

Note the use of echo -n to avoid the extraneous newline at the end. printf is another good option and may be more suitable for your particular needs. If you want to ignore whitespace then replace "$words" with "${words// /}".

Another option is fold. Please note however that it should never be fed into a for loop. Rather, use a while loop as follows:

while read char; do
    echo "$char"
done < <(fold -w1 <<<"$words")

The primary benefit to using the external fold command (of the coreutils package) would be brevity. You can feed it's output to another command such as xargs (part of the findutils package) as follows:

fold -w1 <<<"$words" | xargs -I% -- echo %

You'll want to replace the echo command used in the example above with the command you'd like to run against each character. Note that xargs will discard whitespace by default. You can use -d '\n' to disable that behavior.


Internationalization

I just tested fold with some of the Asian characters and realized it doesn't have Unicode support. So while it is fine for ASCII needs, it won't work for everyone. In that case there are some alternatives.

I'd probably replace fold -w1 with an awk array:

awk 'BEGIN{FS=""} {for (i=1;i<=NF;i++) print $i}'

Or the grep command mentioned in another answer:

grep -o .


Performance

FYI, I benchmarked the 3 aforementioned options. The first two were fast, nearly tying, with the fold loop slightly faster than the while loop. Unsurprisingly xargs was the slowest... 75x slower.

Here is the (abbreviated) test code:

words=$(python -c 'from string import ascii_letters as l; print(l * 100)')

testrunner(){
    for test in test_while_loop test_fold_loop test_fold_xargs test_awk_loop test_grep_loop; do
        echo "$test"
        (time for (( i=1; i<$((${1:-100} + 1)); i++ )); do "$test"; done >/dev/null) 2>&1 | sed '/^$/d'
        echo
    done
}

testrunner 100

Here are the results:

test_while_loop
real    0m5.821s
user    0m5.322s
sys     0m0.526s

test_fold_loop
real    0m6.051s
user    0m5.260s
sys     0m0.822s

test_fold_xargs
real    7m13.444s
user    0m24.531s
sys     6m44.704s

test_awk_loop
real    0m6.507s
user    0m5.858s
sys     0m0.788s

test_grep_loop
real    0m6.179s
user    0m5.409s
sys     0m0.921s

How do I mock a service that returns promise in AngularJS Jasmine unit test?

I found that useful, stabbing service function as sinon.stub().returns($q.when({})):

this.myService = {
   myFunction: sinon.stub().returns( $q.when( {} ) )
};

this.scope = $rootScope.$new();
this.angularStubs = {
    myService: this.myService,
    $scope: this.scope
};
this.ctrl = $controller( require( 'app/bla/bla.controller' ), this.angularStubs );

controller:

this.someMethod = function(someObj) {
   myService.myFunction( someObj ).then( function() {
        someObj.loaded = 'bla-bla';
   }, function() {
        // failure
   } );   
};

and test

const obj = {
    field: 'value'
};
this.ctrl.someMethod( obj );

this.scope.$digest();

expect( this.myService.myFunction ).toHaveBeenCalled();
expect( obj.loaded ).toEqual( 'bla-bla' );

How to call external JavaScript function in HTML

If a <script> has a src then the text content of the element will be not be executed as JS (although it will appear in the DOM).

You need to use multiple script elements.

  1. a <script> to load the external script
  2. a <script> to hold your inline code (with the call to the function in the external script)

    scroll_messages();

What is aria-label and how should I use it?

It's an attribute designed to help assistive technology (e.g. screen readers) attach a label to an otherwise anonymous HTML element.

So there's the <label> element:

<label for="fmUserName">Your name</label>
<input id="fmUserName">

The <label> explicitly tells the user to type their name into the input box where id="fmUserName".

aria-label does much the same thing, but it's for those cases where it isn't practical or desirable to have a label on screen. Take the MDN example:

<button aria-label="Close" onclick="myDialog.close()">X</button>`

Most people would be able to infer visually that this button will close the dialog. A blind person using assistive technology might just hear "X" read aloud, which doesn't mean much without the visual clues. aria-label explicitly tells them what the button will do.

Why use Ruby's attr_accessor, attr_reader and attr_writer?

It is important to understand that accessors restrict access to variable, but not their content. In ruby, like in some other OO languages, every variable is a pointer to an instance. So if you have an attribute to an Hash, for example, and you set it to be "read only" you always could change its content, but not the content of pointer. Look at this:

irb(main):024:0> class A
irb(main):025:1> attr_reader :a
irb(main):026:1> def initialize
irb(main):027:2> @a = {a:1, b:2}
irb(main):028:2> end
irb(main):029:1> end
=> :initialize
irb(main):030:0> a = A.new
=> #<A:0x007ffc5a10fe88 @a={:a=>1, :b=>2}>
irb(main):031:0> a.a
=> {:a=>1, :b=>2}
irb(main):032:0> a.a.delete(:b)
=> 2
irb(main):033:0> a.a
=> {:a=>1}
irb(main):034:0> a.a = {}
NoMethodError: undefined method `a=' for #<A:0x007ffc5a10fe88 @a={:a=>1}>
        from (irb):34
        from /usr/local/bin/irb:11:in `<main>'

As you can see is possible delete a key/value pair from the Hash @a, as add new keys, change values, eccetera. But you can't point to a new object because is a read only instance variable.

How to markdown nested list items in Bitbucket?

Possibilities

  • It is possible to nest a bulleted-unnumbered list into a higher numbered list.
  • But in the bulleted-unnumbered list the automatically numbered list will not start: Its is not supported.
    • To start a new numbered list after a bulleted-unnumbered one, put a piece of text between them, or a subtitle: A new numbered list cannot start just behind the bulleted: The interpreter will not start the numbering.

in practice

  1. Dog

    1. German Shepherd - with only a single space ahead.
    2. Belgian Shepherd - max 4 spaces ahead.
      • Number in front of a line interpreted as a "numbering bullet", so making the indentation.
        • ..and ignores the written digit: Places/generates its own, in compliance with the structure.
        • So it is OK to use only just "1" ones, to get your numbered list.
          • Or whatever integer number, even of more digits: The list numbering will continue by increment ++1.
        • However, the first item in the numbered list will be kept, so the first leading will usually be the number "1".
    3. Malinois - 5 spaces makes 3rd level already.
      1. MalinoisB - 5 spaces makes 3rd level already.
      2. Groenendael - 8 spaces makes 3rd level yet too.
        1. Tervuren - 9 spaces for 4th level - Intentionaly started by "55".
        2. TervurenB - numbered by "88", in the source code.
  2. Cat

    1. Siberian; a. SiberianA - problem reproduced: letters (i.e. "a" here) not recognized by the interpreter as "numbering".
      • No matter, it is indented to its separated line, in the source code.
    2. Siamese
      • a. so written manually as a workaround misusing bullets, unnumbered list.

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

Note that in both CMake and Autotools you don't always have to set the installation path at configure time. You can use DESTDIR at install time (see also here) instead as in:

make DESTDIR=<installhere> install

See also this question which explains the subtle difference between DESTDIR and PREFIX.

This is intended for staged installs and to allow for storing programs in a different location from where they are run e.g. /etc/alternatives via symbolic links.

However, if your package is relocatable and doesn't need any hard-coded (prefix) paths set via the configure stage you may be able to skip it. So instead of:

cmake -DCMAKE_INSTALL_PREFIX=/usr . && make all install

you would run:

cmake . && make DESTDIR=/usr all install

Note that, as user7498341 points out, this is not appropriate for cases where you really should be using PREFIX.

Get just the filename from a path in a Bash script

Here is an easy way to get the file name from a path:

echo "$PATH" | rev | cut -d"/" -f1 | rev

To remove the extension you can use, assuming the file name has only ONE dot (the extension dot):

cut -d"." -f1

List of standard lengths for database fields

I would say to err on the high side. Since you'll probably be using varchar, any extra space you allow won't actually use up any extra space unless somebody needs it. I would say for names (first or last), go at least 50 chars, and for email address, make it at least 128. There are some really long email addresses out there.

Another thing I like to do is go to Lipsum.com and ask it to generate some text. That way you can get a good idea of just what 100 bytes looks like.

Form inside a form, is that alright?

Form nesting can be achieved with new HTML5 input element's form attribute. Although we don't nest forms structurally, inputs are evaluated as they are in their own form. In my tests, 3 major browsers support this except IE(IE11). Form nesting limitation was a big obstacle for HTML UI design.

Here is a sample code, when you click Save button you should see "2 3 success" (Original http://www.impressivewebs.com/html5-form-attribute/):

<form id="saveForm" action="/post/dispatch/save" method="post"></form>
<form id="deleteForm" action="/post/dispatch/delete" method="post"></form>

<div id="toolbar">
    <input type="text" name="foo" form="saveForm" />
    <input type="hidden" value="some_id" form="deleteForm" />
    <input type="text" name="foo2" id="foo2" form="saveForm" value="success" />

    <input type="submit" name="save" value="Save" form="saveForm" onclick="alert(document.getElementById('deleteForm').elements.length + ' ' + document.getElementById('saveForm').elements.length + ' ' + document.getElementById('saveForm').elements['foo2'].value);return false;" />
    <input type="submit" name="delete" value="Delete" form="deleteForm" />
    <a href="/home/index">Cancel</a>
</div>

How to import local packages in go?

If you are using Go 1.5 above, you can try to use vendoring feature. It allows you to put your local package under vendor folder and import it with shorter path. In your case, you can put your common and routers folder inside vendor folder so it would be like

myapp/
--vendor/
----common/
----routers/
------middleware/
--main.go

and import it like this

import (
    "common"
    "routers"
    "routers/middleware"
)

This will work because Go will try to lookup your package starting at your project’s vendor directory (if it has at least one .go file) instead of $GOPATH/src.

FYI: You can do more with vendor, because this feature allows you to put "all your dependency’s code" for a package inside your own project's directory so it will be able to always get the same dependencies versions for all builds. It's like npm or pip in python, but you need to manually copy your dependencies to you project, or if you want to make it easy, try to look govendor by Daniel Theophanes

For more learning about this feature, try to look up here

Understanding and Using Vendor Folder by Daniel Theophanes

Understanding Go Dependency Management by Lucas Fernandes da Costa

I hope you or someone else find it helpfully

How to Retrieve value from JTextField in Java Swing?

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Swingtest extends JFrame implements ActionListener
{
    JTextField txtdata;
    JButton calbtn = new JButton("Calculate");

    public Swingtest()
    {
        JPanel myPanel = new JPanel();
        add(myPanel);
        myPanel.setLayout(new GridLayout(3, 2));
        myPanel.add(calbtn);
        calbtn.addActionListener(this);
        txtdata = new JTextField();
        myPanel.add(txtdata);
    }

    public void actionPerformed(ActionEvent e)
    {
        if (e.getSource() == calbtn) {
            String data = txtdata.getText(); //perform your operation
            System.out.println(data);
        }
    }

    public static void main(String args[])
    {
        Swingtest g = new Swingtest();
        g.setLocation(10, 10);
        g.setSize(300, 300);
        g.setVisible(true);
    }
}

now its working

How to use a calculated column to calculate another column in the same view

In SQL Server

You can do this using With CTE

WITH common_table_expression (Transact-SQL)

CREATE TABLE tab(ColumnA DECIMAL(10,2), ColumnB DECIMAL(10,2), ColumnC DECIMAL(10,2))

INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2),(3, 15, 6),(7, 14, 3)

WITH tab_CTE (ColumnA, ColumnB, ColumnC,calccolumn1)  
AS  
(  
Select
    ColumnA,
    ColumnB,
    ColumnC,
    ColumnA + ColumnB As calccolumn1
  from tab
)  

SELECT
  ColumnA,
  ColumnB,
  calccolumn1,
  calccolumn1 / ColumnC AS calccolumn2
FROM  tab_CTE

DBFiddle Demo

Why does Date.parse give incorrect results?

While CMS is correct that passing strings into the parse method is generally unsafe, the new ECMA-262 5th Edition (aka ES5) specification in section 15.9.4.2 suggests that Date.parse() actually should handle ISO-formatted dates. The old specification made no such claim. Of course, old browsers and some current browsers still do not provide this ES5 functionality.

Your second example isn't wrong. It is the specified date in UTC, as implied by Date.prototype.toISOString(), but is represented in your local timezone.

How to start http-server locally

When you're running npm install in the project's root, it installs all of the npm dependencies into the project's node_modules directory.

If you take a look at the project's node_modules directory, you should see a directory called http-server, which holds the http-server package, and a .bin folder, which holds the executable binaries from the installed dependencies. The .bin directory should have the http-server binary (or a link to it).

So in your case, you should be able to start the http-server by running the following from your project's root directory (instead of npm start):

./node_modules/.bin/http-server -a localhost -p 8000 -c-1

This should have the same effect as running npm start.

If you're running a Bash shell, you can simplify this by adding the ./node_modules/.bin folder to your $PATH environment variable:

export PATH=./node_modules/.bin:$PATH

This will put this folder on your path, and you should be able to simply run

http-server -a localhost -p 8000 -c-1

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

Step For Windows

  1. press the ctrl + r.then type cmd and hit enter.
  2. now command prompt will be open.

  3. after the type cd filepath of file. ex(cd C:\Users\user\Desktop\ ) then hit the enter.

  4. please check if npm installed or not using this command node -v. then if you installed will get node version.
  5. type the command on command prompt like this node filename.js . example(node app.js)

C:\Users\user\Desktop>node app.js

How to delete session cookie in Postman?

Note that this answer applies only to the standalone Postman UI and not the Postman app/add-on for Chrome.

How to clear the cache in Postman (so that you are required to log in again when requesting a token, for example):

  • navigate to View: Show DevTools
  • navigate to the Application tab, then the Clear Storage view in the left menu
  • deselect all choices except Cache Storage, then click on ‘Clear site data’
  • restart Postman
  • you should now be prompted to log in again when requesting a new token

Name [jdbc/mydb] is not bound in this Context

you put resource-ref in the description tag in web.xml

How to create a directory and give permission in single command

you can use following command to create directory and give permissions at the same time

mkdir -m777 path/foldername 

How to sort an array of objects with jquery or javascript

the sort method contains an optional argument to pass a custom compare function.

Assuming you wanted an array of arrays:

var arr = [[3, "Mike", 20],[5, "Alex", 15]];

function compareName(a, b)
{

  if (a[1] < b[1]) return -1;
  if (a[1] > b[1]) return 1;
  return 0;
}
arr.sort(compareName);

Otherwise if you wanted an array of objects, you could do:

function compareName(a, b)
{

  if (a.name < b.name) return -1;
  if (a.name > b.name) return 1;
  return 0;
}

Show special characters in Unix while using 'less' Command

Now, sometimes you already have less open, and you can't use cat on it. For example, you did a | less, and you can't just reopen a file, as that's actually a stream.

If all you need is to identify end of line, one easy way is to search for the last character on the line: /.$. The search will highlight the last character, even if it is a blank, making it easy to identify it.

That will only help with the end of line case. If you need other special characters, you can use the cat -vet solution above with marks and pipe:

  • mark the top of the text you're interested in: ma
  • go to the bottom of the text you're interested in and mark it, as well: mb
  • go back to the mark a: 'a
  • pipe from a to b through cat -vet and view the result in another less command: |bcat -vet | less

This will open another less process, which shows the result of running cat -vet on the text that lies between marks a and b.

If you want the whole thing, instead, do g|$cat -vet | less, to go to the first line and filter all lines through cat.

The advantage of this method over less options is that it does not mess with the output you see on the screen.

One would think that eight years after this question was originally posted, less would have that feature... But I can't even see a feature request for it on https://github.com/gwsw/less/issues

Blur effect on a div element

I got blur working with SVG blur filter:

CSS

-webkit-filter: url(#svg-blur);
        filter: url(#svg-blur);

SVG

<svg id="svg-filter">
    <filter id="svg-blur">
        <feGaussianBlur in="SourceGraphic" stdDeviation="4"></feGaussianBlur>
    </filter>
</svg>

Working example:

https://jsfiddle.net/1k5x6dgm/

Please note - this will not work in IE versions

How to find all the tables in MySQL with specific column names in them?

If you want "To get all tables only", Then use this query:

SELECT TABLE_NAME 
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME like '%'
and TABLE_SCHEMA = 'tresbu_lk'

If you want "To get all tables with Columns", Then use this query:

SELECT DISTINCT TABLE_NAME, COLUMN_NAME  
FROM INFORMATION_SCHEMA.COLUMNS  
WHERE column_name LIKE '%'  
AND TABLE_SCHEMA='tresbu_lk'

How to use shell commands in Makefile

Also, in addition to torek's answer: one thing that stands out is that you're using a lazily-evaluated macro assignment.

If you're on GNU Make, use the := assignment instead of =. This assignment causes the right hand side to be expanded immediately, and stored in the left hand variable.

FILES := $(shell ...)  # expand now; FILES is now the result of $(shell ...)

FILES = $(shell ...)   # expand later: FILES holds the syntax $(shell ...)

If you use the = assignment, it means that every single occurrence of $(FILES) will be expanding the $(shell ...) syntax and thus invoking the shell command. This will make your make job run slower, or even have some surprising consequences.

How to get a Docker container's IP address from the host

Combining previous answers with finding the container ID based on the Docker image name:

docker inspect --format '{{ .NetworkSettings.IPAddress }}' `docker ps | grep $IMAGE_NAME | sed 's/\|/ /' | awk '{print $1}'`

Filtering JSON array using jQuery grep()

var data = {
    "items": [{
        "id": 1,
        "category": "cat1"
    }, {
        "id": 2,
        "category": "cat2"
    }, {
        "id": 3,
        "category": "cat1"
    }]
};

var returnedData = $.grep(data.items, function (element, index) {
    return element.id == 1;
});


alert(returnedData[0].id + "  " + returnedData[0].category);

The returnedData is returning an array of objects, so you can access it by array index.

http://jsfiddle.net/wyfr8/913/

Check if current directory is a Git repository

Based on @Alex Cory's answer:

[ "$(git rev-parse --is-inside-work-tree 2>/dev/null)" == "true" ]

doesn't contain any redundant operations and works in -e mode.

  • As @go2null noted, this will not work in a bare repo. If you want to work with a bare repo for whatever reason, you can just check for git rev-parse succeeding, ignoring its output.
    • I don't consider this a drawback because the above line is indended for scripting, and virtually all git commands are only valid inside a worktree. So for scripting purposes, you're most likely interested in being not just inside a "git repo" but inside a worktree.

MongoDB: update every document on one field

I have been using MongoDB .NET driver for a little over a month now. If I were to do it using .NET driver, I would use Update method on the collection object. First, I will construct a query that will get me all the documents I am interested in and do an Update on the fields I want to change. Update in Mongo only affects the first document and to update all documents resulting from the query one needs to use 'Multi' update flag. Sample code follows...

var collection = db.GetCollection("Foo");
var query = Query.GTE("No", 1); // need to construct in such a way that it will give all 20K //docs.
var update = Update.Set("timestamp", datetime.UtcNow);
collection.Update(query, update, UpdateFlags.Multi);

How to disable PHP Error reporting in CodeIgniter?

Here is the typical structure of new Codeigniter project:

- application/
- system/
- user_guide/
- index.php <- this is the file you need to change

I usually use this code in my CI index.php. Just change local_server_name to the name of your local webserver.

With this code you can deploy your site to your production server without changing index.php each time.

// Domain-based environment
if ($_SERVER['SERVER_NAME'] == 'local_server_name') {
    define('ENVIRONMENT', 'development');
} else {
    define('ENVIRONMENT', 'production');
}

/*
 *---------------------------------------------------------------
 * ERROR REPORTING
 *---------------------------------------------------------------
 *
 * Different environments will require different levels of error reporting.
 * By default development will show errors but testing and live will hide them.
 */

if (defined('ENVIRONMENT')) {
    switch (ENVIRONMENT) {
        case 'development':
            error_reporting(E_ALL);
            break;
        case 'testing':
        case 'production':
            error_reporting(0);
            ini_set('display_errors', 0);  
            break;
        default:
            exit('The application environment is not set correctly.');
    }
}

RegEx to parse or validate Base64 data

The best regexp which I could find up till now is in here https://www.npmjs.com/package/base64-regex

which is in the current version looks like:

module.exports = function (opts) {
  opts = opts || {};
  var regex = '(?:[A-Za-z0-9+\/]{4}\\n?)*(?:[A-Za-z0-9+\/]{2}==|[A-Za-z0-9+\/]{3}=)';

  return opts.exact ? new RegExp('(?:^' + regex + '$)') :
                    new RegExp('(?:^|\\s)' + regex, 'g');
};

Width of input type=text element

I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.

How do I check that multiple keys are in a dict in a single pass?

Another option for detecting whether all keys are in a dict:

dict_to_test = { ... }  # dict
keys_sought = { "key_sought_1", "key_sought_2", "key_sought_3" }  # set

if keys_sought & dict_to_test.keys() == keys_sought: 
    # True -- dict_to_test contains all keys in keys_sought
    # code_here
    pass

How to declare variable and use it in the same Oracle SQL script?

Try using double quotes if it's a char variable:

DEFINE stupidvar = "'stupidvarcontent'";

or

DEFINE stupidvar = 'stupidvarcontent';

SELECT stupiddata  
FROM stupidtable  
WHERE stupidcolumn = '&stupidvar'

upd:

SQL*Plus: Release 10.2.0.1.0 - Production on Wed Aug 25 17:13:26 2010

Copyright (c) 1982, 2005, Oracle.  All rights reserved.

SQL> conn od/od@etalon
Connected.
SQL> define var = "'FL-208'";
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = 'FL-208'

CODE
---------------
FL-208

SQL> define var = 'FL-208';
SQL> select code from product where code = &var;
old   1: select code from product where code = &var
new   1: select code from product where code = FL-208
select code from product where code = FL-208
                                      *
ERROR at line 1:
ORA-06553: PLS-221: 'FL' is not a procedure or is undefined

Pretty printing XML in Python

I found this question while looking for "how to pretty print html"

Using some of the ideas in this thread I adapted the XML solutions to work for XML or HTML:

from xml.dom.minidom import parseString as string_to_dom

def prettify(string, html=True):
    dom = string_to_dom(string)
    ugly = dom.toprettyxml(indent="  ")
    split = list(filter(lambda x: len(x.strip()), ugly.split('\n')))
    if html:
        split = split[1:]
    pretty = '\n'.join(split)
    return pretty

def pretty_print(html):
    print(prettify(html))

When used this is what it looks like:

html = """\
<div class="foo" id="bar"><p>'IDK!'</p><br/><div class='baz'><div>
<span>Hi</span></div></div><p id='blarg'>Try for 2</p>
<div class='baz'>Oh No!</div></div>
"""

pretty_print(html)

Which returns:

<div class="foo" id="bar">
  <p>'IDK!'</p>
  <br/>
  <div class="baz">
    <div>
      <span>Hi</span>
    </div>
  </div>
  <p id="blarg">Try for 2</p>
  <div class="baz">Oh No!</div>
</div>

SQL Last 6 Months

In MySQL

where datetime_column > curdate() - interval (dayofmonth(curdate()) - 1) day - interval 6 month

SQLFiddle demo

In SQL Server

where datetime_column > dateadd(m, -6, getdate() - datepart(d, getdate()) + 1)

SQLFiddle demo

When a 'blur' event occurs, how can I find out which element focus went *to*?

The type FocusEvent instances have relatedTarget attribute, however, up to version 47 of the FF, specifically, this attribute returns null, from 48 already works.

You can to see more here.

How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

The solutions posted so far only deal with part of the problem, converting DOS/Windows' CRLF into Unix's LF; the part they're missing is that DOS use CRLF as a line separator, while Unix uses LF as a line terminator. The difference is that a DOS file (usually) won't have anything after the last line in the file, while Unix will. To do the conversion properly, you need to add that final LF (unless the file is zero-length, i.e. has no lines in it at all). My favorite incantation for this (with a little added logic to handle Mac-style CR-separated files, and not molest files that're already in unix format) is a bit of perl:

perl -pe 'if ( s/\r\n?/\n/g ) { $f=1 }; if ( $f || ! $m ) { s/([^\n])\z/$1\n/ }; $m=1' PCfile.txt

Note that this sends the Unixified version of the file to stdout. If you want to replace the file with a Unixified version, add perl's -i flag.

What are the ways to sum matrix elements in MATLAB?

The best practice is definitely to avoid loops or recursions in Matlab.

Between sum(A(:)) and sum(sum(A)). In my experience, arrays in Matlab seems to be stored in a continuous block in memory as stacked column vectors. So the shape of A does not quite matter in sum(). (One can test reshape() and check if reshaping is fast in Matlab. If it is, then we have a reason to believe that the shape of an array is not directly related to the way the data is stored and manipulated.)

As such, there is no reason sum(sum(A)) should be faster. It would be slower if Matlab actually creates a row vector recording the sum of each column of A first and then sum over the columns. But I think sum(sum(A)) is very wide-spread amongst users. It is likely that they hard-code sum(sum(A)) to be a single loop, the same to sum(A(:)).

Below I offer some testing results. In each test, A=rand(size) and size is specified in the displayed texts.

First is using tic toc.

Size 100x100
sum(A(:))
Elapsed time is 0.000025 seconds.
sum(sum(A))
Elapsed time is 0.000018 seconds.

Size 10000x1
sum(A(:))
Elapsed time is 0.000014 seconds.
sum(A)
Elapsed time is 0.000013 seconds.

Size 1000x1000
sum(A(:))
Elapsed time is 0.001641 seconds.
sum(A)
Elapsed time is 0.001561 seconds.

Size 1000000
sum(A(:))
Elapsed time is 0.002439 seconds.
sum(A)
Elapsed time is 0.001697 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.148504 seconds.
sum(A)
Elapsed time is 0.155160 seconds.

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27 (line 70)
A=rand(100000000,1);

Below is using cputime

Size 100x100
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x1
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000x1000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 1000000
The cputime for sum(A(:)) in seconds is 
0
The cputime for sum(sum(A)) in seconds is 
0

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 100000000
Error using rand
Out of memory. Type HELP MEMORY for your options.

Error in test27_2 (line 70)
A=rand(100000000,1);

In my experience, both timers are only meaningful up to .1s. So if you have similar experience with Matlab timers, none of the tests can discern sum(A(:)) and sum(sum(A)).

I tried the largest size allowed on my computer a few more times.

Size 10000x10000
sum(A(:))
Elapsed time is 0.151256 seconds.
sum(A)
Elapsed time is 0.143937 seconds.

Size 10000x10000
sum(A(:))
Elapsed time is 0.149802 seconds.
sum(A)
Elapsed time is 0.145227 seconds.

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.2808
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

Size 10000x10000
The cputime for sum(A(:)) in seconds is 
0.312
The cputime for sum(sum(A)) in seconds is 
0.312

They seem equivalent. Either one is good. But sum(sum(A)) requires that you know the dimension of your array is 2.

How to use UIVisualEffectView to Blur Image?

You can also use the interface builder to create these effects easily for simple situations. Since the z-values of the views will depend on the order they are listed in the Document Outline, you can drag a UIVisualEffectView onto the document outline before the view you want to blur. This automatically creates a nested UIView, which is the contentView property of the given UIVisualEffectView. Nest things within this view that you want to appear on top of the blur.

XCode6 beta5

You can also easily take advantage of the vibrancy UIVisualEffect, which will automatically create another nested UIVisualEffectView in the document outline with vibrancy enabled by default. You can then add a label or text view to the nested UIView (again, the contentView property of the UIVisualEffectView), to achieve the same effect that the "> slide to unlock" UI element.

enter image description here

Get Time from Getdate()

You might want to check out this old thread.

If you can omit AM/PM portion and using SQL Server 2008, you should go with the approach suggested here

To get the rid from nenoseconds in time(SQL Server 2008), do as below :

SELECT CONVERT(TIME(0),GETDATE()) AS HourMinuteSecond

I hope it helps!!

How to make one Observable sequence wait for another to complete before emitting?

Here's yet another, but I feel more straightforward and intuitive (or at least natural if you're used to Promises), approach. Basically, you create an Observable using Observable.create() to wrap one and two as a single Observable. This is very similar to how Promise.all() may work.

var first = someObservable.take(1);
var second = Observable.create((observer) => {
  return first.subscribe(
    function onNext(value) {
      /* do something with value like: */
      // observer.next(value);
    },
    function onError(error) {
      observer.error(error);
    },
    function onComplete() {
      someOtherObservable.take(1).subscribe(
        function onNext(value) {
          observer.next(value);
        },
        function onError(error) {
          observer.error(error);
        },
        function onComplete() {
          observer.complete();
        }
      );
    }
  );
});

So, what's going on here? First, we create a new Observable. The function passed to Observable.create(), aptly named onSubscription, is passed the observer (built from the parameters you pass to subscribe()), which is similar to resolve and reject combined into a single object when creating a new Promise. This is how we make the magic work.

In onSubscription, we subscribe to the first Observable (in the example above, this was called one). How we handle next and error is up to you, but the default provided in my sample should be appropriate generally speaking. However, when we receive the complete event, which means one is now done, we can subscribe to the next Observable; thereby firing the second Observable after the first one is complete.

The example observer provided for the second Observable is fairly simple. Basically, second now acts like what you would expect two to act like in the OP. More specifically, second will emit the first and only the first value emitted by someOtherObservable (because of take(1)) and then complete, assuming there is no error.

Example

Here is a full, working example you can copy/paste if you want to see my example working in real life:

var someObservable = Observable.from([1, 2, 3, 4, 5]);
var someOtherObservable = Observable.from([6, 7, 8, 9]);

var first = someObservable.take(1);
var second = Observable.create((observer) => {
  return first.subscribe(
    function onNext(value) {
      /* do something with value like: */
      observer.next(value);
    },
    function onError(error) {
      observer.error(error);
    },
    function onComplete() {
      someOtherObservable.take(1).subscribe(
        function onNext(value) {
          observer.next(value);
        },
        function onError(error) {
          observer.error(error);
        },
        function onComplete() {
          observer.complete();
        }
      );
    }
  );
}).subscribe(
  function onNext(value) {
    console.log(value);
  },
  function onError(error) {
    console.error(error);
  },
  function onComplete() {
    console.log("Done!");
  }
);

If you watch the console, the above example will print:

1

6

Done!

Google Maps: How to create a custom InfoWindow?

You can even append your own css class on the popup container/canvas or how do you want. Current google maps 3.7 has popups styled by canvas element which prepends popup div container in code. So at googlemaps 3.7 You can get into rendering process by popup's domready event like this:

var popup = new google.maps.InfoWindow();
google.maps.event.addListener(popup, 'domready', function() {
  if (this.content && this.content.parentNode && this.content.parentNode.parentNode) {
    if (this.content.parentNode.parentNode.previousElementSibling) {
      this.content.parentNode.parentNode.previousElementSibling.className = 'my-custom-popup-container-css-classname';
    }
  }
});

element.previousElementSibling is not present at IE8- so if you want to make it work at it, follow this.

check the latest InfoWindow reference for events and more..

I found this most clean in some cases.

SQL query for finding records where count > 1

create table payment(
    user_id int(11),
    account int(11) not null,
    zip int(11) not null,
    dt date not null
);

insert into payment values
(1,123,55555,'2009-12-12'),
(1,123,66666,'2009-12-12'),
(1,123,77777,'2009-12-13'),
(2,456,77777,'2009-12-14'),
(2,456,77777,'2009-12-14'),
(2,789,77777,'2009-12-14'),
(2,789,77777,'2009-12-14');

select foo.user_id, foo.cnt from
(select user_id,count(account) as cnt, dt from payment group by account, dt) foo
where foo.cnt > 1;

Difference between arguments and parameters in Java

There are different points of view. One is they are the same. But in practice, we need to differentiate formal parameters (declarations in the method's header) and actual parameters (values passed at the point of invocation). While phrases "formal parameter" and "actual parameter" are common, "formal argument" and "actual argument" are not used. This is because "argument" is used mainly to denote "actual parameter". As a result, some people insist that "parameter" can denote only "formal parameter".

How can I tail a log file in Python?

Using the sh module (pip install sh):

from sh import tail
# runs forever
for line in tail("-f", "/var/log/some_log_file.log", _iter=True):
    print(line)

[update]

Since sh.tail with _iter=True is a generator, you can:

import sh
tail = sh.tail("-f", "/var/log/some_log_file.log", _iter=True)

Then you can "getNewData" with:

new_data = tail.next()

Note that if the tail buffer is empty, it will block until there is more data (from your question it is not clear what you want to do in this case).

[update]

This works if you replace -f with -F, but in Python it would be locking. I'd be more interested in having a function I could call to get new data when I want it, if that's possible. – Eli

A container generator placing the tail call inside a while True loop and catching eventual I/O exceptions will have almost the same effect of -F.

def tail_F(some_file):
    while True:
        try:
            for line in sh.tail("-f", some_file, _iter=True):
                yield line
        except sh.ErrorReturnCode_1:
            yield None

If the file becomes inaccessible, the generator will return None. However it still blocks until there is new data if the file is accessible. It remains unclear for me what you want to do in this case.

Raymond Hettinger approach seems pretty good:

def tail_F(some_file):
    first_call = True
    while True:
        try:
            with open(some_file) as input:
                if first_call:
                    input.seek(0, 2)
                    first_call = False
                latest_data = input.read()
                while True:
                    if '\n' not in latest_data:
                        latest_data += input.read()
                        if '\n' not in latest_data:
                            yield ''
                            if not os.path.isfile(some_file):
                                break
                            continue
                    latest_lines = latest_data.split('\n')
                    if latest_data[-1] != '\n':
                        latest_data = latest_lines[-1]
                    else:
                        latest_data = input.read()
                    for line in latest_lines[:-1]:
                        yield line + '\n'
        except IOError:
            yield ''

This generator will return '' if the file becomes inaccessible or if there is no new data.

[update]

The second to last answer circles around to the top of the file it seems whenever it runs out of data. – Eli

I think the second will output the last ten lines whenever the tail process ends, which with -f is whenever there is an I/O error. The tail --follow --retry behavior is not far from this for most cases I can think of in unix-like environments.

Perhaps if you update your question to explain what is your real goal (the reason why you want to mimic tail --retry), you will get a better answer.

The last answer does not actually follow the tail and merely reads what's available at run time. – Eli

Of course, tail will display the last 10 lines by default... You can position the file pointer at the end of the file using file.seek, I will left a proper implementation as an exercise to the reader.

IMHO the file.read() approach is far more elegant than a subprocess based solution.

How to call JavaScript function instead of href in HTML

Your should also separate the javascript from the HTML.
HTML:

<a href="#" id="function-click"><img title="next page" alt="next page" src="/themes/me/img/arrn.png"></a>

javascript:

myLink = document.getElementById('function-click');
myLink.onclick = ShowOld(2367,146986,2);

Just make sure the last line in the ShowOld function is:

return false;

as this will stop the link from opening in the browser.

Formatting MM/DD/YYYY dates in textbox in VBA

You could use an input mask on the text box, too. If you set the mask to ##/##/#### it will always be formatted as you type and you don't need to do any coding other than checking to see if what was entered was a true date.

Which just a few easy lines

txtUserName.SetFocus
If IsDate(txtUserName.text) Then
    Debug.Print Format(CDate(txtUserName.text), "MM/DD/YYYY")
Else
    Debug.Print "Not a real date"
End If

How can I autoformat/indent C code in vim?

I like to use the program Artistic Style. According to their website:

Artistic Style is a source code indenter, formatter, and beautifier for the C, C++, C# and Java programming languages.

It runs in Window, Linux and Mac. It will do things like indenting, replacing tabs with spaces or vice-versa, putting spaces around operations however you like (converting if(x<2) to if ( x<2 ) if that's how you like it), putting braces on the same line as function definitions, or moving them to the line below, etc. All the options are controlled by command line parameters.

In order to use it in vim, just set the formatprg option to it, and then use the gq command. So, for example, I have in my .vimrc:

autocmd BufNewFile,BufRead *.cpp set formatprg=astyle\ -T4pb

so that whenever I open a .cpp file, formatprg is set with the options I like. Then, I can type gg to go to the top of the file, and gqG to format the entire file according to my standards. If I only need to reformat a single function, I can go to the top of the function, then type gq][ and it will reformat just that function.

The options I have for astyle, -T4pb, are just my preferences. You can look through their docs, and change the options to have it format the code however you like.

Here's a demo. Before astyle:

int main(){if(x<2){x=3;}}

float test()
{
if(x<2)
x=3;
}

After astyle (gggqG):

int main()
{
    if (x < 2)
    {
        x = 3;
    }
}

float test()
{
    if (x < 2)
        x = 3;
}

Hope that helps.

How do I set the default schema for a user in MySQL

There is no default database for user. There is default database for current session.

You can get it using DATABASE() function -

SELECT DATABASE();

And you can set it using USE statement -

USE database1;

You should set it manually - USE db_name, or in the connection string.

View not attached to window manager crash

This issue is because of your activity gets finished before the dismiss function gets called. Handle the exception and check your ADB log for the exact reason.

/**
     * After completing background task Dismiss the progress dialog
     * **/
    protected void onPostExecute(String file_url) {
    try {
         if (pDialog!=null) {
            pDialog.dismiss();   //This is line 624!    
         }
    } catch (Exception e) {
        // do nothing
    }
     something(note);
}

Convert JSON format to CSV format for MS Excel

I'm not sure what you're doing, but this will go from JSON to CSV using JavaScript. This is using the open source JSON library, so just download JSON.js into the same folder you saved the code below into, and it will parse the static JSON value in json3 into CSV and prompt you to download/open in Excel.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>JSON to CSV</title>
    <script src="scripts/json.js" type="text/javascript"></script>
    <script type="text/javascript">
    var json3 = { "d": "[{\"Id\":1,\"UserName\":\"Sam Smith\"},{\"Id\":2,\"UserName\":\"Fred Frankly\"},{\"Id\":1,\"UserName\":\"Zachary Zupers\"}]" }

    DownloadJSON2CSV(json3.d);

    function DownloadJSON2CSV(objArray)
    {
        var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;

        var str = '';

        for (var i = 0; i < array.length; i++) {
            var line = '';

            for (var index in array[i]) {
                line += array[i][index] + ',';
            }

            // Here is an example where you would wrap the values in double quotes
            // for (var index in array[i]) {
            //    line += '"' + array[i][index] + '",';
            // }

            line.slice(0,line.Length-1); 

            str += line + '\r\n';
        }
        window.open( "data:text/csv;charset=utf-8," + escape(str))
    }

    </script>

</head>
<body>
    <h1>This page does nothing....</h1>
</body>
</html>

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

How can I plot a confusion matrix?

IF you want more data in you confusion matrix, including "totals column" and "totals line", and percents (%) in each cell, like matlab default (see image below)

enter image description here

including the Heatmap and other options...

You should have fun with the module above, shared in the github ; )

https://github.com/wcipriano/pretty-print-confusion-matrix


This module can do your task easily and produces the output above with a lot of params to customize your CM: enter image description here

Pip Install not installing into correct directory?

  1. download pip at https://pypi.python.org/pypi/pip (tar)
  2. unzip tar file
  3. cd to the file’s directory
  4. sudo python2.7 setup.py install

How to define dimens.xml for every different screen size in android?

You have to create Different values folder for different screens . Like

values-sw720dp          10.1” tablet 1280x800 mdpi

values-sw600dp          7.0”  tablet 1024x600 mdpi

values-sw480dp          5.4”  480x854 mdpi 
values-sw480dp          5.1”  480x800 mdpi 

values-xxhdpi           5.5"  1080x1920 xxhdpi
values-xxxhdpi           5.5" 1440x2560 xxxhdpi

values-xhdpi            4.7”   1280x720 xhdpi 
values-xhdpi            4.65”  720x1280 xhdpi 

values-hdpi             4.0” 480x800 hdpi
values-hdpi             3.7” 480x854 hdpi

values-mdpi             3.2” 320x480 mdpi

values-ldpi             3.4” 240x432 ldpi
values-ldpi             3.3” 240x400 ldpi
values-ldpi             2.7” 240x320 ldpi

enter image description here

For more information you may visit here

Different values folders in android

http://android-developers.blogspot.in/2011/07/new-tools-for-managing-screen-sizes.html

Edited By @humblerookie

You can make use of Android Studio plugin called Dimenify to auto generate dimension values for other pixel buckets based on custom scale factors. Its still in beta, be sure to notify any issues/suggestions you come across to the developer.

Is It Possible to NSLog C Structs (Like CGRect or CGPoint)?

Yes, you can use bellow few functions like: First you have to convert CGPoint struct into string, see example

1) NSStringFromCGPoint,  
2) NSStringFromCGSize,  
3) NSStringFromCGRect,  
4) NSStringFromCGAffineTransform,  
5) NSStringFromUIEdgeInsets,

For example:

1) NSLog(@"NSStringFromCGPoint = %@", NSStringFromCGRect(cgPointValue));

Like this...

Making interface implementations async

An abstract class can be used instead of an interface (in C# 7.3).

// Like interface
abstract class IIO
{
    public virtual async Task<string> DoOperation(string Name)
    {
        throw new NotImplementedException(); // throwing exception
        // return await Task.Run(() => { return ""; }); // or empty do
    }
}

// Implementation
class IOImplementation : IIO
{
    public override async Task<string> DoOperation(string Name)
    {
        return await await Task.Run(() =>
        {
            if(Name == "Spiderman")
                return "ok";
            return "cancel";
        }); 
    }
}

What does "wrong number of arguments (1 for 0)" mean in Ruby?

When you define a function, you also define what info (arguments) that function needs to work. If it is designed to work without any additional info, and you pass it some, you are going to get that error.

Example: Takes no arguments:

def dog
end

Takes arguments:

def cat(name)
end

When you call these, you need to call them with the arguments you defined.

dog                  #works fine
cat("Fluffy")        #works fine


dog("Fido")          #Returns ArgumentError (1 for 0)
cat                  #Returns ArgumentError (0 for 1)

Check out the Ruby Koans to learn all this.

How can I get the current class of a div with jQuery?

Simply by

var divClass = $("#div1").attr("class")

You can do some other stuff to manipulate element's class

$("#div1").addClass("foo"); // add class 'foo' to div1
$("#div1").removeClass("foo"); // remove class 'foo' from div1
$("#div1").toggleClass("foo"); // toggle class 'foo'

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

Task.Run with Parameter(s)?

private void RunAsync()
{
    string param = "Hi";
    Task.Run(() => MethodWithParameter(param));
}

private void MethodWithParameter(string param)
{
    //Do stuff
}

Edit

Due to popular demand I must note that the Task launched will run in parallel with the calling thread. Assuming the default TaskScheduler this will use the .NET ThreadPool. Anyways, this means you need to account for whatever parameter(s) being passed to the Task as potentially being accessed by multiple threads at once, making them shared state. This includes accessing them on the calling thread.

In my above code that case is made entirely moot. Strings are immutable. That's why I used them as an example. But say you're not using a String...

One solution is to use async and await. This, by default, will capture the SynchronizationContext of the calling thread and will create a continuation for the rest of the method after the call to await and attach it to the created Task. If this method is running on the WinForms GUI thread it will be of type WindowsFormsSynchronizationContext.

The continuation will run after being posted back to the captured SynchronizationContext - again only by default. So you'll be back on the thread you started with after the await call. You can change this in a variety of ways, notably using ConfigureAwait. In short, the rest of that method will not continue until after the Task has completed on another thread. But the calling thread will continue to run in parallel, just not the rest of the method.

This waiting to complete running the rest of the method may or may not be desirable. If nothing in that method later accesses the parameters passed to the Task you may not want to use await at all.

Or maybe you use those parameters much later on in the method. No reason to await immediately as you could continue safely doing work. Remember, you can store the Task returned in a variable and await on it later - even in the same method. For instance, once you need to access the passed parameters safely after doing a bunch some other work. Again, you do not need to await on the Task right when you run it.

Anyways, a simple way to make this thread-safe with respect to the parameters passed to Task.Run is to do this:

You must first decorate RunAsync with async:

private async void RunAsync()

Important Note

Preferably the method marked async should not return void, as the linked documentation mentions. The common exception to this is event handlers such as button clicks and such. They must return void. Otherwise I always try to return a Task or Task<TResult> when using async. It's good practice for a quite a few reasons.

Now you can await running the Task like below. You cannot use await without async.

await Task.Run(() => MethodWithParameter(param));
//Code here and below in the same method will not run until AFTER the above task has completed in one fashion or another

So, in general, if you await the task you can avoid treating passed in parameters as a potentially shared resource with all the pitfalls of modifying something from multiple threads at once. Also, beware of closures. I won't cover those in depth but the linked article does a great job of it.

Side Note

A bit off topic, but be careful using any type of "blocking" on the WinForms GUI thread due to it being marked with [STAThread]. Using await won't block at all, but I do sometimes see it used in conjunction with some sort of blocking.

"Block" is in quotes because you technically cannot block the WinForms GUI thread. Yes, if you use lock on the WinForms GUI thread it will still pump messages, despite you thinking it's "blocked". It's not.

This can cause bizarre issues in very rare cases. One of the reasons you never want to use a lock when painting, for example. But that's a fringe and complex case; however I've seen it cause crazy issues. So I noted it for completeness sake.

MySQL error 1241: Operand should contain 1 column(s)

Syntax error, remove the ( ) from select.

insert into table2 (name, subject, student_id, result)
select name, subject, student_id, result
from table1;

How to confirm RedHat Enterprise Linux version?

That's the RHEL release version.

You can see the kernel version by typing uname -r. It'll be 2.6.something.

How to check whether Kafka Server is running?

Paul's answer is very good and it is actually how Kafka & Zk work together from a broker point of view.

I would say that another easy option to check if a Kafka server is running is to create a simple KafkaConsumer pointing to the cluste and try some action, for example, listTopics(). If kafka server is not running, you will get a TimeoutException and then you can use a try-catch sentence.

  def validateKafkaConnection(kafkaParams : mutable.Map[String, Object]) : Unit = {
    val props = new Properties()
    props.put("bootstrap.servers", kafkaParams.get("bootstrap.servers").get.toString)
    props.put("group.id", kafkaParams.get("group.id").get.toString)
    props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer")
    val simpleConsumer = new KafkaConsumer[String, String](props)
    simpleConsumer.listTopics()
  }

PHP PDO with foreach and fetch

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}

Here $users is a PDOStatement object over which you can iterate. The first iteration outputs all results, the second does nothing since you can only iterate over the result once. That's because the data is being streamed from the database and iterating over the result with foreach is essentially shorthand for:

while ($row = $users->fetch()) ...

Once you've completed that loop, you need to reset the cursor on the database side before you can loop over it again.

$users = $dbh->query($sql);
foreach ($users as $row) {
    print $row["name"] . "-" . $row["sex"] ."<br/>";
}
echo "<br/>";
$result = $users->fetch(PDO::FETCH_ASSOC);
foreach($result as $key => $value) {
    echo $key . "-" . $value . "<br/>";
}

Here all results are being output by the first loop. The call to fetch will return false, since you have already exhausted the result set (see above), so you get an error trying to loop over false.

In the last example you are simply fetching the first result row and are looping over it.

Combining a class selector and an attribute selector with jQuery

This code works too:

$("input[reference=12345].myclass").css('border', '#000 solid 1px');

Using .htaccess to make all .html pages to run as .php files?

For anyone out there still having trouble,

try this (my hosting was from Godaddy and this is the only thing that worked for me among all the answers out there.

AddHandler x-httpd-php5-cgi .html

SQL Insert Multiple Rows

1--> {Simple Insertion when table column sequence is known}
    Insert into Table1
    values(1,2,...)

2--> {Simple insertion mention column}  
    Insert into Table1(col2,col4)
    values(1,2)

3--> {bulk insertion when num of selected collumns of a table(#table2) are equal to Insertion table(Table1) }   
    Insert into Table1 {Column sequence}
    Select * -- column sequence should be same.
       from #table2

4--> {bulk insertion when you want to insert only into desired column of a table(table1)}
    Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  
    Select Column1,Column2..desired column from #table2

Jupyter Notebook not saving: '_xsrf' argument missing from post

The only solution worked for me was:

  1. I opened a new tab in chrome
  2. I pasted : http://localhost:8888/?token=......
  3. then I went to my original notebook and I was able to save it

How to create a vector of user defined size but with no predefined values?

With the constructor:

// create a vector with 20 integer elements
std::vector<int> arr(20);

for(int x = 0; x < 20; ++x)
   arr[x] = x;

How to implement WiX installer upgrade?

You might be better asking this on the WiX-users mailing list.

WiX is best used with a firm understanding of what Windows Installer is doing. You might consider getting "The Definitive Guide to Windows Installer".

The action that removes an existing product is the RemoveExistingProducts action. Because the consequences of what it does depends on where it's scheduled - namely, whether a failure causes the old product to be reinstalled, and whether unchanged files are copied again - you have to schedule it yourself.

RemoveExistingProducts processes <Upgrade> elements in the current installation, matching the @Id attribute to the UpgradeCode (specified in the <Product> element) of all the installed products on the system. The UpgradeCode defines a family of related products. Any products which have this UpgradeCode, whose versions fall into the range specified, and where the UpgradeVersion/@OnlyDetect attribute is no (or is omitted), will be removed.

The documentation for RemoveExistingProducts mentions setting the UPGRADINGPRODUCTCODE property. It means that the uninstall process for the product being removed receives that property, whose value is the Product/@Id for the product being installed.

If your original installation did not include an UpgradeCode, you will not be able to use this feature.

How can I inspect element in an Android browser?

Chrome on Android makes it possible to use the Chrome developer tools on the desktop to inspect the HTML that was loaded from the Chrome application on the Android device.

See: https://developers.google.com/chrome-developer-tools/docs/remote-debugging

Javascript - removing undefined fields from an object

This solution also avoids hasOwnProperty() as Object.keys returns an array of a given object's own enumerable properties.

Object.keys(obj).forEach(function (key) {
 if(typeof obj[key] === 'undefined'){
    delete obj[key];
  }
});

and you can add this as null or '' for stricter cleaning.

How can I read a whole file into a string variable

I'm not with computer,so I write a draft. You might be clear of what I say.

func main(){
    const dir = "/etc/"
    filesInfo, e := ioutil.ReadDir(dir)
    var fileNames = make([]string, 0, 10)
    for i,v:=range filesInfo{
        if !v.IsDir() {
            fileNames = append(fileNames, v.Name())
        }
    }

    var fileNumber = len(fileNames)
    var contents = make([]string, fileNumber, 10)
    wg := sync.WaitGroup{}
    wg.Add(fileNumber)

    for i,_:=range content {
        go func(i int){
            defer wg.Done()
            buf,e := ioutil.Readfile(fmt.Printf("%s/%s", dir, fileName[i]))
            defer file.Close()  
            content[i] = string(buf)
        }(i)   
    }
    wg.Wait()
}

How do I register a .NET DLL file in the GAC?

You'll need:

  • Strong name your assembly (Visual Studio, Project Properties, Signing tab, Sign the assembly)
  • Alter your Build Events (Project Properties, Build Events tab, Post-build command line)
   cd C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin
   gacutil.exe /i "$(TargetPath)" /f /nologo
   gacutil /l "$(TargetName)" /nologo

Now, everytime you build your project, it'll be installed on GAC.

No module named setuptools

The question mentions Windows, and the accepted answer also works for Ubuntu, but for those who found this question coming from a Redhat flavor of Linux, this did the trick:

sudo yum install -y python-setuptools

Running powershell script within python script, how to make python print the powershell output while it is running

I don't have Python 2.7 installed, but in Python 3.3 calling Popen with stdout set to sys.stdout worked just fine. Not before I had escaped the backslashes in the path, though.

>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_

Regular expression to match DNS hostname or IP Address?

I think this is the best Ip validation regex. please check it once!!!

^(([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))\.){3}([01]?[0-9]?[0-9]|2([0-4][0-9]|5[0-5]))$

Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop

I also have the same problem, and the solution is I didn't bind the event in my onClick. so when it renders for the first time and the data is more, which ends up calling the state setter again, which triggers React to call your function again and so on.

export default function Component(props) {

function clickEvent (event, variable){
    console.log(variable);
}

return (
    <div>
        <IconButton
            key="close"
            aria-label="Close"
            color="inherit"
            onClick={e => clickEvent(e, 10)} // or you can call like this:onClick={() => clickEvent(10)} 
        >
    </div>
)
}

Java Compare Two Lists

I found a very basic example of List comparison at List Compare This example verifies the size first and then checks the availability of the particular element of one list in another.

ssh script returns 255 error

I was stumped by this. Once I got passed the 255 problem... I ended up with a mysterious error code 1. This is the foo to get that resolved:

 pssh -x '-tt' -h HOSTFILELIST -P "sudo yum -y install glibc"

-P means write the output out as you go and is optional. But the -x '-tt' trick is what forces a psuedo tty to be allocated.

You can get a clue what the error code 1 means this if you try:

ssh AHOST "sudo yum -y install glibc"

You may see:

[slc@bastion-ci ~]$ ssh MYHOST "sudo yum -y install glibc"
sudo: sorry, you must have a tty to run sudo
[slc@bastion-ci ~]$ echo $?
1

Notice the return code for this is 1, which is what pssh is reporting to you.

I found this -x -tt trick here. Also note that turning on verbose mode (pssh --verbose) for these cases does nothing to help you.

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

Ternary operator ?: vs if...else

They are the same, however, the ternary operator can be used in places where it is difficult to use a if/else:

printf("Total: %d item%s", cnt, cnt != 1 ? "s" : "");

Doing that statement with an if/else, would generate a very different compiled code.


Update after 8 years...

Actually, I think this would be better:

printf(cnt == 1 ? "Total: %d item" : "Total: %d items", cnt);

(actually, I'm pretty sure you can replace the "%d" in the first string with "one")

How to delay the .keyup() handler until the user stops typing?

var globalTimeout = null;  
$('#search').keyup(function(){
  if(globalTimeout != null) clearTimeout(globalTimeout);  
  globalTimeout =setTimeout(SearchFunc,200);  
});
function SearchFunc(){  
  globalTimeout = null;  
  console.log('Search: '+$('#search').val());
  //ajax code
};

disabling spring security in spring boot app

This was the only thing that worked for me, I added the following annotation to my Application class and exclude SecurityAutoConfiguration

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;

@EnableAutoConfiguration(exclude = {
        SecurityAutoConfiguration.class
})

go to link on button click - jquery

You need to specify the domain:

 $('.button1').click(function() {
   window.location = 'www.example.com/index.php?id=' + this.id;
 });

What is the most efficient way of finding all the factors of a number in Python?

For n up to 10**16 (maybe even a bit more), here is a fast pure Python 3.6 solution,

from itertools import compress

def primes(n):
    """ Returns  a list of primes < n for n > 2 """
    sieve = bytearray([True]) * (n//2)
    for i in range(3,int(n**0.5)+1,2):
        if sieve[i//2]:
            sieve[i*i//2::i] = bytearray((n-i*i-1)//(2*i)+1)
    return [2,*compress(range(3,n,2), sieve[1:])]

def factorization(n):
    """ Returns a list of the prime factorization of n """
    pf = []
    for p in primeslist:
      if p*p > n : break
      count = 0
      while not n % p:
        n //= p
        count += 1
      if count > 0: pf.append((p, count))
    if n > 1: pf.append((n, 1))
    return pf

def divisors(n):
    """ Returns an unsorted list of the divisors of n """
    divs = [1]
    for p, e in factorization(n):
        divs += [x*p**k for k in range(1,e+1) for x in divs]
    return divs

n = 600851475143
primeslist = primes(int(n**0.5)+1) 
print(divisors(n))

Create a List of primitive int?

In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object they cannot be used as generic type arguments for a parametrized type.

Instead use the Integer class which is a wrapper for int:

List<Integer> list = new ArrayList<Integer>();

If your using Java 7 you can simplify this declaration using the diamond operator:

List<Integer> list = new ArrayList<>();

With autoboxing in Java the primitive type int will become an Integer when necessary.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

So the following is valid:

int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);

System.out.println(list.get(0)); //prints 1

CMake error at CMakeLists.txt:30 (project): No CMAKE_C_COMPILER could be found

Those error messages

CMake Error at ... (project):
    No CMAKE_C_COMPILER could be found.
-- Configuring incomplete, errors occurred!
See also ".../CMakeFiles/CMakeOutput.log".
See also ".../CMakeFiles/CMakeError.log".

or

CMake Error: your CXX compiler: "CMAKE_CXX_COMPILER-NOTFOUND" was not found.
Please set CMAKE_CXX_COMPILER to a valid compiler path or name.
...
-- Configuring incomplete, errors occurred!

just mean that CMake was unable to find your C/CXX compiler to compile a simple test program (one of the first things CMake tries while detecting your build environment).

The steps to find your problem are dependent on the build environment you want to generate. The following tutorials are a collection of answers here on Stack Overflow and some of my own experiences with CMake on Microsoft Windows 7/8/10 and Ubuntu 14.04.

Preconditions

  • You have installed the compiler/IDE and it was able to once compile any other program (directly without CMake)
  • You have the latest CMake version
  • You have access rights on the drive you want CMake to generate your build environment
  • You have a clean build directory (because CMake does cache things from the last try) e.g. as sub-directory of your source tree

    Windows cmd.exe

    > rmdir /s /q VS2015
    > mkdir VS2015
    > cd VS2015
    

    Bash shell

    $ rm -rf MSYS
    $ mkdir MSYS
    $ cd MSYS
    

    and make sure your command shell points to your newly created binary output directory.

General things you can/should try

  1. Is CMake able find and run with any/your default compiler? Run without giving a generator

    > cmake ..
    -- Building for: Visual Studio 14 2015
    ...
    

    Perfect if it correctly determined the generator to use - like here Visual Studio 14 2015

  2. What was it that actually failed?

    In the previous build output directory look at CMakeFiles\CMakeError.log for any error message that make sense to you or try to open/compile the test project generated at CMakeFiles\[Version]\CompilerIdC|CompilerIdCXX directly from the command line (as found in the error log).

CMake can't find Visual Studio

  1. Try to select the correct generator version:

    > cmake --help
    > cmake -G "Visual Studio 14 2015" ..
    
  2. If that doesn't help, try to set the Visual Studio environment variables first (the path could vary):

    > "c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
    > cmake ..
    

    or use the Developer Command Prompt for VS2015 short-cut in your Windows Start Menu under All Programs/Visual Studio 2015/Visual Studio Tools (thanks at @Antwane for the hint).

Background: CMake does support all Visual Studio releases and flavors (Express, Community, Professional, Premium, Test, Team, Enterprise, Ultimate, etc.). To determine the location of the compiler it uses a combination of searching the registry (e.g. at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\[Version];InstallDir), system environment variables and - if none of the others did come up with something - plainly try to call the compiler.

CMake can't find GCC (MinGW/MSys)

  1. You start the MSys bash shell with msys.bat and just try to directly call gcc

    $ gcc
    gcc.exe: fatal error: no input files
    compilation terminated.
    

    Here it did find gcc and is complaining that I didn't gave it any parameters to work with.

    So the following should work:

    $ cmake -G "MSYS Makefiles" ..
    -- The CXX compiler identification is GNU 4.8.1
    ...
    $ make
    

    If GCC was not found call export PATH=... to add your compilers path (see How to set PATH environment variable in CMake script?) and try again.

  2. If it's still not working, try to set the CXX compiler path directly by exporting it (path may vary)

    $ export CC=/c/MinGW/bin/gcc.exe
    $ export CXX=/c/MinGW/bin/g++.exe
    $ cmake -G "MinGW Makefiles" ..
    -- The CXX compiler identification is GNU 4.8.1
    ...
    $ mingw32-make
    

    For more details see How to specify new GCC path for CMake

    Note: When using the "MinGW Makefiles" generator you have to use the mingw32-make program distributed with MinGW

  3. Still not working? That's weird. Please make sure that the compiler is there and it has executable rights (see also preconditions chapter above).

    Otherwise the last resort of CMake is to not try any compiler search itself and set CMake's internal variables directly by

    $ cmake -DCMAKE_C_COMPILER=/c/MinGW/bin/gcc.exe -DCMAKE_CXX_COMPILER=/c/MinGW/bin/g++.exe ..
    

    For more details see Cmake doesn't honour -D CMAKE_CXX_COMPILER=g++ and Cmake error setting compiler

    Alternatively those variables can also be set via cmake-gui.exe on Windows. See Cmake cannot find compiler

Background: Much the same as with Visual Studio. CMake supports all sorts of GCC flavors. It searches the environment variables (CC, CXX, etc.) or simply tries to call the compiler. In addition it will detect any prefixes (when cross-compiling) and tries to add it to all binutils of the GNU compiler toolchain (ar, ranlib, strip, ld, nm, objdump, and objcopy).

Paste Excel range in Outlook

Often this question is asked in the context of Ron de Bruin's RangeToHTML function, which creates an HTML PublishObject from an Excel.Range, extracts that via FSO, and inserts the resulting stream HTML in to the email's HTMLBody. In doing so, this removes the default signature (the RangeToHTML function has a helper function GetBoiler which attempts to insert the default signature).

Unfortunately, the poorly-documented Application.CommandBars method is not available via Outlook:

wdDoc.Application.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"

It will raise a runtime 6158:

enter image description here

But we can still leverage the Word.Document which is accessible via the MailItem.GetInspector method, we can do something like this to copy & paste the selection from Excel to the Outlook email body, preserving your default signature (if there is one).

Dim rng as Range
Set rng = Range("A1:F10") 'Modify as needed

With OutMail
    .To = "[email protected]"
    .BCC = ""
    .Subject = "Subject"
    .Display
    Dim wdDoc As Object     '## Word.Document
    Dim wdRange As Object   '## Word.Range
    Set wdDoc = OutMail.GetInspector.WordEditor
    Set wdRange = wdDoc.Range(0, 0)
    wdRange.InsertAfter vbCrLf & vbCrLf
    'Copy the range in-place
    rng.Copy
    wdRange.Paste
End With

Note that in some cases this may not perfectly preserve the column widths or in some instances the row heights, and while it will also copy shapes and other objects in the Excel range, this may also cause some funky alignment issues, but for simple tables and Excel ranges, it is very good:

enter image description here

Setting std=c99 flag in GCC

Instead of calling /usr/bin/gcc, use /usr/bin/c99. This is the Single-Unix-approved way of invoking a C99 compiler. On an Ubuntu system, this points to a script which invokes gcc after having added the -std=c99 flag, which is precisely what you want.

How to configure static content cache per folder and extension in IIS7?

You can set specific cache-headers for a whole folder in either your root web.config:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <!-- Note the use of the 'location' tag to specify which 
       folder this applies to-->
  <location path="images">
    <system.webServer>
      <staticContent>
        <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
      </staticContent>
    </system.webServer>
  </location>
</configuration>

Or you can specify these in a web.config file in the content folder:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
  <system.webServer>
    <staticContent>
      <clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
    </staticContent>
  </system.webServer>
</configuration>

I'm not aware of a built in mechanism to target specific file types.

What do the icons in Eclipse mean?

In eclipse help documentation, we can all icons information as follows. Common path for all eclipse versions except eclipse version:

enter image description here

https://help.eclipse.org/2019-09/index.jsp?nav=%2F1

In which conda environment is Jupyter executing?

As mentioned in the comments, conda support for jupyter notebooks is needed to switch kernels. Seems like this support is now available through conda itself (rather than relying on pip). http://docs.continuum.io/anaconda/user-guide/tasks/use-jupyter-notebook-extensions/

conda install nb_conda

which brings three other handy extensions in addition to Notebook Conda Kernels.

RegEx for validating an integer with a maximum length of 10 characters

Don't forget that integers can be negative:

^\s*-?[0-9]{1,10}\s*$

Here's the meaning of each part:

  • ^: Match must start at beginning of string
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • -: The hyphen-minus character, used to denote a negative integer
    • ?: May or may not occur
  • [0-9]: Any character whose ASCII code (or Unicode code point) is between '0' and '9'
    • {1,10}: Occurring at least one, but not more than ten times
  • \s: Any whitespace character
    • *: Occurring zero or more times
  • $: Match must end at end of string

This ignores leading and trailing whitespace and would be more complex if you consider commas acceptable or if you need to count the minus sign as one of the ten allowed characters.

How to change resolution (DPI) of an image?

It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.

For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.

To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.

Pseudo code

ratio = 300.0 / 72.0   // 4.167
image.width * ratio
image.height * ratio

Changing the interval of SetInterval while it's running

This can be initiated however you want. timeout is the method i used to keep it on the top of the hour.

I had the need for every hour to begin a code block on the hour. So this would start at server startup and run the interval hourly. Basicaly the initial run is to begin the interval within the same minute. So in a second from init, run immediately then on every 5 seconds.

var interval = 1000;
var timing =function(){
    var timer = setInterval(function(){
        console.log(interval);
        if(interval == 1000){ /*interval you dont want anymore or increment/decrement */
            interval = 3600000; /* Increment you do want for timer */
            clearInterval(timer);
            timing();
        }
    },interval);
}
timing();

Alternately if you wanted to just have something happen at start and then forever at a specific interval you could just call it at the same time as the setInterval. For example:

var this = function(){
 //do
}
setInterval(function(){
  this()
},3600000)
this()

Here we have this run the first time and then every hour.

How do I resolve a path relative to an ASP.NET MVC 4 application root?

I find this code useful when I need a path outside of a controller, such as when I'm initializing components in Global.asax.cs:

HostingEnvironment.MapPath("~/Data/data.html")

Mobile Redirect using htaccess

I modified Tim Stone's solution even further. This allows the cookie to be in 2 states, 1 for mobile and 0 for full. When the mobile cookie is set to 0 even a mobile browser will go to the full site.

Here is the code:

<IfModule mod_rewrite.c>
    RewriteBase /
    RewriteEngine On

    # Check if mobile=1 is set and set cookie 'mobile' equal to 1
    RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
    RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

    # Check if mobile=0 is set and set cookie 'mobile' equal to 0
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

    # cookie can't be set and read in the same request so check
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [S=1]

    # Check if this looks like a mobile device
    RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
    RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
    RewriteCond %{HTTP:Profile}       !^$

    # Check if we're not already on the mobile site
    RewriteCond %{HTTP_HOST}          !^m\.
    # Check to make sure we haven't set the cookie before
    RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
    # Now redirect to the mobile site
    RewriteRule ^ http://m.example.com%{REQUEST_URI} [R,L]
</IfModule>

How to parse XML using shellscript?

Here's a solution using xml_grep (because xpath wasn't part of our distributable and I didn't want to add it to all production machines)...

If you are looking for a specific setting in an XML file, and if all elements at a given tree level are unique, and there are no attributes, then you can use this handy function:

# File to be parsed
xmlFile="xxxxxxx"

# use xml_grep to find settings in an XML file
# Input ($1): path to setting
function getXmlSetting() {

    # Filter out the element name for parsing
    local element=`echo $1 | sed 's/^.*\///'`

    # Verify the element is not empty
    local check=${element:?getXmlSetting invalid input: $1}

    # Parse out the CDATA from the XML element
    # 1) Find the element (xml_grep)
    # 2) Remove newlines (tr -d \n)
    # 3) Extract CDATA by looking for *element> CDATA <element*
    # 4) Remove leading and trailing spaces
    local getXmlSettingResult=`xml_grep --cond $1 $xmlFile 2>/dev/null | tr -d '\n' | sed -n -e "s/.*$element>[[:space:]]*\([^[:space:]].*[^[:space:]]\)[[:space:]]*<\/$element.*/\1/p"`

    # Return the result
    echo $getXmlSettingResult
}

#EXAMPLE
logPath=`getXmlSetting //config/logs/path`
check=${logPath:?"XML file missing //config/logs/path"}

This will work with this structure:

<config>
  <logs>
     <path>/path/to/logs</path>
  <logs>
</config>

It will also work with this (but it won't keep the newlines):

<config>
  <logs>
     <path>
          /path/to/logs
     </path>
  <logs>
</config>

If you have duplicate <config> or <logs> or <path>, then it will only return the last one. You can probably modify the function to return an array if it finds multiple matches.

FYI: This code works on RedHat 6.3 with GNU BASH 4.1.2, but I don't think I'm doing anything particular to that, so should work everywhere.

NOTE: For anybody new to scripting, make sure you use the right types of quotes, all three are used in this code (normal single quote '=literal, backward single quote `=execute, and double quote "=group).

Converting an integer to a hexadecimal string in Ruby

How about using %/sprintf:

i = 20
"%x" % i  #=> "14"

Convert Pandas Series to DateTime in a DataFrame

df=pd.read_csv("filename.csv" , parse_dates=["<column name>"])

type(df.<column name>)

example: if you want to convert day which is initially a string to a Timestamp in Pandas

df=pd.read_csv("weather_data2.csv" , parse_dates=["day"])

type(df.day)

The output will be pandas.tslib.Timestamp

Command to close an application of console?

 //How to start another application from the current application
 Process runProg = new Process();
 runProg.StartInfo.FileName = pathToFile; //the path of the application
 runProg.StartInfo.Arguments = genArgs; //any arguments you want to pass
 runProg.StartInfo.CreateNoWindow = true;
 runProg.Start();

 //How to end the same application from the current application
 int IDstring = System.Convert.ToInt32(runProg.Id.ToString());
 Process tempProc = Process.GetProcessById(IDstring);
 tempProc.CloseMainWindow();
 tempProc.WaitForExit();

How to convert int to NSString?

int i = 25;
NSString *myString = [NSString stringWithFormat:@"%d",i];

This is one of many ways.

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

I had to downgrade OpenSSL in this way:

brew uninstall --ignore-dependencies openssl
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/30fd2b68feb458656c2da2b91e577960b11c42f4/Formula/openssl.rb

It was the only solution that worked for me.

How to install MinGW-w64 and MSYS2?

MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw and cygwin fork package.

To install the MinGW-w64 toolchain (Reference):

  1. Open MSYS2 shell from start menu
  2. Run pacman -Sy pacman to update the package database
  3. Re-open the shell, run pacman -Syu to update the package database and core system packages
  4. Re-open the shell, run pacman -Su to update the rest
  5. Install compiler:
    • For 32-bit target, run pacman -S mingw-w64-i686-toolchain
    • For 64-bit target, run pacman -S mingw-w64-x86_64-toolchain
  6. Select which package to install, default is all
  7. You may also need make, run pacman -S make

How to determine the IP address of a Solaris system

hostname and uname will give you the name of the host. Then use nslookup to translate that to an IP address.

Set content of HTML <span> with Javascript

The Maximally Standards Compliant way to do it is to create a text node containing the text you want and append it to the span (removing any currently extant text nodes).

The way I would actually do it is to use jQuery's .text().

docker-compose up for only certain containers

One good solution is to run only desired services like this:

docker-compose up --build $(<services.txt)

and services.txt file look like this:

services1 services2, etc

of course if dependancy (depends_on), need to run related services together.

--build is optional, just for example.

Standard deviation of a list

pure python code:

from math import sqrt

def stddev(lst):
    mean = float(sum(lst)) / len(lst)
    return sqrt(float(reduce(lambda x, y: x + y, map(lambda x: (x - mean) ** 2, lst))) / len(lst))

In Python, how do I split a string and keep the separators?

One Lazy and Simple Solution

Assume your regex pattern is split_pattern = r'(!|\?)'

First, you add some same character as the new separator, like '[cut]'

new_string = re.sub(split_pattern, '\\1[cut]', your_string)

Then you split the new separator, new_string.split('[cut]')

Binding ComboBox SelectedItem using MVVM

You seem to be unnecessarily setting properties on your ComboBox. You can remove the DisplayMemberPath and SelectedValuePath properties which have different uses. It might be an idea for you to take a look at the Difference between SelectedItem, SelectedValue and SelectedValuePath post here for an explanation of these properties. Try this:

<ComboBox Name="cbxSalesPeriods"
    ItemsSource="{Binding SalesPeriods}"
    SelectedItem="{Binding SelectedSalesPeriod}"
    IsSynchronizedWithCurrentItem="True"/>

Furthermore, it is pointless using your displayPeriod property, as the WPF Framework would call the ToString method automatically for objects that it needs to display that don't have a DataTemplate set up for them explicitly.


UPDATE >>>

As I can't see all of your code, I cannot tell you what you are doing wrong. Instead, all I can do is to provide you with a complete working example of how to achieve what you want. I've removed the pointless displayPeriod property and also your SalesPeriodVO property from your class as I know nothing about it... maybe that is the cause of your problem??. Try this:

public class SalesPeriodV
{
    private int month, year;

    public int Year
    {
        get { return year; }
        set
        {
            if (year != value)
            {
                year = value;
                NotifyPropertyChanged("Year");
            }
        }
    }

    public int Month
    {
        get { return month; }
        set
        {
            if (month != value)
            {
                month = value;
                NotifyPropertyChanged("Month");
            }
        }
    }

    public override string ToString()
    {
        return String.Format("{0:D2}.{1}", Month, Year);
    }

    public virtual event PropertyChangedEventHandler PropertyChanged;
    protected virtual void NotifyPropertyChanged(params string[] propertyNames)
    {
        if (PropertyChanged != null)
        {
            foreach (string propertyName in propertyNames) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            PropertyChanged(this, new PropertyChangedEventArgs("HasError"));
        }
    }
}

Then I added two properties into the view model:

private ObservableCollection<SalesPeriodV> salesPeriods = new ObservableCollection<SalesPeriodV>();
public ObservableCollection<SalesPeriodV> SalesPeriods
{
    get { return salesPeriods; }
    set { salesPeriods = value; NotifyPropertyChanged("SalesPeriods"); }
}
private SalesPeriodV selectedItem = new SalesPeriodV();
public SalesPeriodV SelectedItem
{
    get { return selectedItem; }
    set { selectedItem = value; NotifyPropertyChanged("SelectedItem"); }
}

Then initialised the collection with your values:

SalesPeriods.Add(new SalesPeriodV() { Month = 3, Year = 2013 } );
SalesPeriods.Add(new SalesPeriodV() { Month = 4, Year = 2013 } );

And then data bound only these two properties to a ComboBox:

<ComboBox ItemsSource="{Binding SalesPeriods}" SelectedItem="{Binding SelectedItem}" />

That's it... that's all you need for a perfectly working example. You should see that the display of the items comes from the ToString method without your displayPeriod property. Hopefully, you can work out your mistakes from this code example.

How to create json by JavaScript for loop?

If you want a single JavaScript object such as the following:

{ uniqueIDofSelect: "uniqueID", optionValue: "2" }

(where option 2, "Absent", is the current selection) then the following code should produce it:

  var jsObj = null;
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsObj = { uniqueIDofSelect: status.id, optionValue: options[i].value };
        break;
     }
  }

If you want an array of all such objects (not just the selected one), use michael's code but swap out status.options[i].text for status.id.

If you want a string that contains a JSON representation of the selected object, use this instead:

  var jsonStr = "";
  var status = document.getElementsByName("status")[0];
  for (i = 0, i < status.options.length, ++i) {
     if (options[i].selected ) {
        jsonStr = '{ '
                  + '"uniqueIDofSelect" : '
                  + '"' + status.id + '"'
                  + ", "
                  + '"optionValue" : '
                  + '"'+ options[i].value + '"'
                  + ' }';
        break;
     }
  }

bash: pip: command not found

Not sure why this wasnt mentioned before, but the only thing that worked for me (on my NVIDIA Xavier) was:

sudo apt-get install python3-pip

(or sudo apt-get install python-pip for python 2)

How to access the php.ini from my CPanel?

You cant do it on shared hosting , Add ticket to support of hosting for same ( otherwise you can look for dedicated server where you can manage anything )

Spaces cause split in path with PowerShell

Using Powershell on Windows10 in 2018, what worked for me was simply to replace double quotes " by simple quotes '. Adding the backtick before the space, as suggested in an answer, broke the path.

How to use Console.WriteLine in ASP.NET (C#) during debug?

using System.Diagnostics;

The following will print to your output as long as the dropdown is set to 'Debug' as shown below.

Debug.WriteLine("Hello, world!");


enter image description here

Simple argparse example wanted: 1 argument, 3 results

I went through all the examples and answers and in a way or another they didn't address my need. So I will list her a scenario that I need more help and I hope this can explain the idea more.

Initial Problem

I need to develop a tool which is getting a file to process it and it needs some optional configuration file to be used to configure the tool.

so what I need is something like the following

mytool.py file.text -config config-file.json

The solution

Here is the solution code

import argparse

def main():
    parser = argparse.ArgumentParser(description='This example for a tool to process a file and configure the tool using a config file.')
    parser.add_argument('filename', help="Input file either text, image or video")
    # parser.add_argument('config_file', help="a JSON file to load the initial configuration ")
    # parser.add_argument('-c', '--config_file', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)
    parser.add_argument('-c', '--config', default='configFile.json', dest='config_file', help="a JSON file to load the initial configuration " )
    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

    args = parser.parse_args()
    
    filename = args.filename
    configfile = args.config_file

    print("The file to be processed is", filename)
    print("The config file is", configfile)

    if args.debug:
        print("Debug mode enabled")
    else:
        print("Debug mode disabled")

    print("and all arguments are: ", args)

if __name__ == '__main__':
    main()

I will show the solution in multiple enhancements to show the idea

First Round: List the arguments

List all input as mandatory inputs so second argument will be

parser.add_argument('config_file', help="a JSON file to load the initial configuration ")

When we get the help command for this tool we find the following outcome

(base) > python .\argparser_example.py -h
usage: argparser_example.py [-h] filename config_file

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename     Input file either text, image or video
  config_file  a JSON file to load the initial configuration

optional arguments:
  -h, --help   show this help message and exit

and when I execute it as the following

(base) > python .\argparser_example.py filename.txt configfile.json

the outcome will be

The file to be processed is filename.txt
The config file is configfile.json
and all arguments are:  Namespace(config_file='configfile.json', filename='filename.txt')

But the config file should be optional, I removed it from the arguments

(base) > python .\argparser_example.py filename.txt

The outcome will be is:

usage: argparser_example.py [-h] filename config_file
argparser_example.py: error: the following arguments are required: c

Which means we have a problem in the tool

Second Round : Make it optimal

So to make it optional I modified the program as follows

    parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', required=False)

The help outcome should be

usage: argparser_example.py [-h] [-c CONFIG] filename

This example for a tool to process a file and configure the tool using a config file.

positional arguments:
  filename              Input file either text, image or video

optional arguments:
  -h, --help            show this help message and exit
  -c CONFIG, --config CONFIG
                        a JSON file to load the initial configuration

so when I execute the program

(base) > python .\argparser_example.py filename.txt

the outcome will be

The file to be processed is filename.txt
The config file is configFile.json
and all arguments are:  Namespace(config_file='configFile.json', filename='filename.txt')

with arguments like

(base) > python .\argparser_example.py filename.txt --config_file anotherConfig.json

The outcome will be

The file to be processed is filename.txt
The config file is anotherConfig.json
and all arguments are:  Namespace(config_file='anotherConfig.json', filename='filename.txt')

Round 3: Enhancements

to change the flag name from --config_file to --config while we keep the variable name as is we modify the code to include dest='config_file' as the following:

parser.add_argument('-c', '--config', help="a JSON file to load the initial configuration ", default='configFile.json', dest='config_file')

and the command will be

(base) > python .\argparser_example.py filename.txt --config anotherConfig.json

To add the support for having a debug mode flag, we need to add a flag in the arguments to support a boolean debug flag. To implement it i added the following:

    parser.add_argument('-d', '--debug', action="store_true", help="Enable the debug mode for logging debug statements." )

the tool command will be:

(carnd-term1-38) > python .\argparser_example.py image.jpg -c imageConfig,json --debug

the outcome will be

The file to be processed is image.jpg
The config file is imageConfig,json
Debug mode enabled
and all arguments are:  Namespace(config_file='imageConfig,json', debug=True, filename='image.jpg')

Find files in a folder using Java

Appache commons IO various

FilenameUtils.wildcardMatch

See Apache javadoc here. It matches the wildcard with the filename. So you can use this method for your comparisons.

How can I remove the search bar and footer added by the jQuery DataTables plugin?

I think the simplest way is:

<th data-searchable="false">Column</th>

You can edit only the table you have to modify, without change common CSS or JS.

Spring Security redirect to previous page after successful login

I've custom OAuth2 authorization and request.getHeader("Referer") is not available at poit of decision. But security request already saved in ExceptionTranslationFilter.sendStartAuthentication:

protected void sendStartAuthentication(HttpServletRequest request,...
    ...
    requestCache.saveRequest(request, response);

So, all what we need is share requestCache as Spring bean:

@Bean
public RequestCache requestCache() {
   return new HttpSessionRequestCache();
}

@Override
protected void configure(HttpSecurity http) throws Exception {
   http.authorizeRequests()
   ... 
   .requestCache().requestCache(requestCache()).and()
   ...
}     

and use it wheen authorization is finished:

@Autowired
private RequestCache requestCache;

public void authenticate(HttpServletRequest req, HttpServletResponse resp){
    ....
    SavedRequest savedRequest = requestCache.getRequest(req, resp);
    resp.sendRedirect(savedRequest != null && "GET".equals(savedRequest.getMethod()) ?  
    savedRequest.getRedirectUrl() : "defaultURL");
}

Get attribute name value of <input>

var value_input = $("input[name*='xxxx']").val();

node.js - how to write an array to file

If it's a huuge array and it would take too much memory to serialize it to a string before writing, you can use streams:

var fs = require('fs');

var file = fs.createWriteStream('array.txt');
file.on('error', function(err) { /* error handling */ });
arr.forEach(function(v) { file.write(v.join(', ') + '\n'); });
file.end();

Official reasons for "Software caused connection abort: socket write error"

ssl client side will throw such exception in below situation(I had tested), :

server is asked to authenticate client certificate, but the client provide a certificate which Extended Key Usage donot support client auth.

Get scroll position using jquery

cross browser variant

$(document).scrollTop();

DateTime.Compare how to check if a date is less than 30 days old?

You can try to do like this:

var daysPassed = (DateTime.UtcNow - expiryDate).Days;
if (daysPassed > 30)
{ 
    // ...
}

Remove URL parameters without refreshing page

TL;DR

1- To modify current URL and add / inject it (the new modified URL) as a new URL entry to history list, use pushState:

window.history.pushState({}, document.title, "/" + "my-new-url.html");

2- To replace current URL without adding it to history entries, use replaceState:

window.history.replaceState({}, document.title, "/" + "my-new-url.html");

3- Depending on your business logic, pushState will be useful in cases such as:

  • you want to support the browser's back button

  • you want to create a new URL, add/insert/push the new URL to history entries, and make it current URL

  • allowing users to bookmark the page with the same parameters (to show the same contents)

  • to programmatically access the data through the stateObj then parse from the anchor


As I understood from your comment, you want to clean your URL without redirecting again.

Note that you cannot change the whole URL. You can just change what comes after the domain's name. This means that you cannot change www.example.com/ but you can change what comes after .com/

www.example.com/old-page-name => can become =>  www.example.com/myNewPaage20180322.php

Background

We can use:

1- The pushState() method if you want to add a new modified URL to history entries.

2- The replaceState() method if you want to update/replace current history entry.

.replaceState() operates exactly like .pushState() except that .replaceState() modifies the current history entry instead of creating a new one. Note that this doesn't prevent the creation of a new entry in the global browser history.


.replaceState() is particularly useful when you want to update the state object or URL of the current history entry in response to some user action.


Code

To do that I will use The pushState() method for this example which works similarly to the following format:

var myNewURL = "my-new-URL.php";//the new URL
window.history.pushState("object or string", "Title", "/" + myNewURL );

Feel free to replace pushState with replaceState based on your requirements.

You can substitute the paramter "object or string" with {} and "Title" with document.title so the final statment will become:

window.history.pushState({}, document.title, "/" + myNewURL );

Results

The previous two lines of code will make a URL such as:

https://domain.tld/some/randome/url/which/will/be/deleted/

To become:

https://domain.tld/my-new-url.php

Action

Now let's try a different approach. Say you need to keep the file's name. The file name comes after the last / and before the query string ?.

http://www.someDomain.com/really/long/address/keepThisLastOne.php?name=john

Will be:

http://www.someDomain.com/keepThisLastOne.php

Something like this will get it working:

 //fetch new URL
 //refineURL() gives you the freedom to alter the URL string based on your needs. 
var myNewURL = refineURL();

//here you pass the new URL extension you want to appear after the domains '/'. Note that the previous identifiers or "query string" will be replaced. 
window.history.pushState("object or string", "Title", "/" + myNewURL );


//Helper function to extract the URL between the last '/' and before '?' 
//If URL is www.example.com/one/two/file.php?user=55 this function will return 'file.php' 
 //pseudo code: edit to match your URL settings  

   function refineURL()
{
    //get full URL
    var currURL= window.location.href; //get current address
    
    //Get the URL between what's after '/' and befor '?' 
    //1- get URL after'/'
    var afterDomain= currURL.substring(currURL.lastIndexOf('/') + 1);
    //2- get the part before '?'
    var beforeQueryString= afterDomain.split("?")[0];  
 
    return beforeQueryString;     
}

UPDATE:

For one liner fans, try this out in your console/firebug and this page URL will change:

    window.history.pushState("object or string", "Title", "/"+window.location.href.substring(window.location.href.lastIndexOf('/') + 1).split("?")[0]);

This page URL will change from:

http://stackoverflow.com/questions/22753052/remove-url-parameters-without-refreshing-page/22753103#22753103

To

http://stackoverflow.com/22753103#22753103

Note: as Samuel Liew indicated in the comments below, this feature has been introduced only for HTML5.

An alternative approach would be to actually redirect your page (but you will lose the query string `?', is it still needed or the data has been processed?).

window.location.href =  window.location.href.split("?")[0]; //"http://www.newurl.com";

Note 2:

Firefox seems to ignore window.history.pushState({}, document.title, ''); when the last argument is an empty string. Adding a slash ('/') worked as expected and removed the whole query part of the url string. Chrome seems to be fine with an empty string.

How do I install the OpenSSL libraries on Ubuntu?

You want to install the development package, which is libssl-dev:

sudo apt-get install libssl-dev

How to add local jar files to a Maven project?

On your local repository you can install your jar by issuing the commands

 mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>

Follow this useful link to do the same from mkyoung's website. You can also check maven guide for the same

How to change package name in android studio?

Another good method is: First create a new package with the desired name by right clicking on the java folder -> new -> package.

Then, select and drag all your classes to the new package. Android Studio will refactor the package name everywhere.

Finally, delete the old package.

or Look into this post

How to tackle daylight savings using TimeZone in Java

public static float calculateTimeZone(String deviceTimeZone) {
    float ONE_HOUR_MILLIS = 60 * 60 * 1000;

    // Current timezone and date
    TimeZone timeZone = TimeZone.getTimeZone(deviceTimeZone);
    Date nowDate = new Date();
    float offsetFromUtc = timeZone.getOffset(nowDate.getTime()) / ONE_HOUR_MILLIS;

    // Daylight Saving time
    if (timeZone.useDaylightTime()) {
        // DST is used
        // I'm saving this is preferences for later use

        // save the offset value to use it later
        float dstOffset = timeZone.getDSTSavings() / ONE_HOUR_MILLIS;
        // DstOffsetValue = dstOffset
        // I'm saving this is preferences for later use
        // save that now we are in DST mode
        if (timeZone.inDaylightTime(nowDate)) {
            Log.e(Utility.class.getName(), "in Daylight Time");
            return -(ONE_HOUR_MILLIS * dstOffset);
        } else {
            Log.e(Utility.class.getName(), "not in Daylight Time");
            return 0;
        }
    } else
        return 0;
}

Quickly getting to YYYY-mm-dd HH:MM:SS in Perl

Use strftime in the standard POSIX module. The arguments to strftime in Perl’s binding were designed to align with the return values from localtime and gmtime. Compare

strftime(fmt, sec, min, hour, mday, mon, year, wday = -1, yday = -1, isdst = -1)

with

my          ($sec,$min,$hour,$mday,$mon,$year,$wday,     $yday,     $isdst) = gmtime(time);

Example command-line use is

$ perl -MPOSIX -le 'print strftime "%F %T", localtime $^T'

or from a source file as in

use POSIX;

print strftime "%F %T", localtime time;

Some systems do not support the %F and %T shorthands, so you will have to be explicit with

print strftime "%Y-%m-%d %H:%M:%S", localtime time;

or

print strftime "%Y-%m-%d %H:%M:%S", gmtime time;

Note that time returns the current time when called whereas $^T is fixed to the time when your program started. With gmtime, the return value is the current time in GMT. Retrieve time in your local timezone with localtime.

concatenate two database columns into one resultset column

Use ISNULL to overcome it.

Example:

SELECT (ISNULL(field1, '') + '' + ISNULL(field2, '')+ '' + ISNULL(field3, '')) FROM table1

This will then replace your NULL content with an empty string which will preserve the concatentation operation from evaluating as an overall NULL result.

How to simulate a real mouse click using java?

it works in Linux. perhaps there are system settings which can be changed in Windows to allow it.

jcomeau@aspire:/tmp$ cat test.java; javac test.java; java test
import java.awt.event.*;
import java.awt.Robot;
public class test {
 public static void main(String args[]) {
  Robot bot = null;
  try {
   bot = new Robot();
  } catch (Exception failed) {
   System.err.println("Failed instantiating Robot: " + failed);
  }
  int mask = InputEvent.BUTTON1_DOWN_MASK;
  bot.mouseMove(100, 100);
  bot.mousePress(mask);
  bot.mouseRelease(mask);
 }
}

I'm assuming InputEvent.MOUSE_BUTTON1_DOWN in your version of Java is the same thing as InputEvent.BUTTON1_DOWN_MASK in mine; I'm using 1.6.

otherwise, that could be your problem. I can tell it worked because my Chrome browser was open to http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html when I ran the program, and it changed to Debian.org because that was the link in the bookmarks bar at (100, 100).

[added later after cogitating on it today] it might be necessary to trick the listening program by simulating a smoother mouse movement. see the answer here: How to move a mouse smoothly throughout the screen by using java?

Error: Could not find gradle wrapper within Android SDK. Might need to update your Android SDK - Android

After cordova upgrade to 7.0.x, the gradle path has been changed as discussed above. To get it working before official fix comes out, just manually install the gradle and set it in your Environment.

  1. Go https://gradle.org/install download the Binary packages
  2. Unzip it,remember the path, eg., My one at: E:\Gradle
  3. Set the environment variables, like on Windows add E:\Gradle\bin

That's it.

How to return data from promise

I also don't like using a function to handle a property which has been resolved again and again in every controller and service. Seem I'm not alone :D

Don't tried to get result with a promise as a variable, of course no way. But I found and use a solution below to access to the result as a property.

Firstly, write result to a property of your service:

app.factory('your_factory',function(){
    var theParentIdResult = null;
    var factoryReturn = {  
        theParentId: theParentIdResult,
        addSiteParentId : addSiteParentId
    };
    return factoryReturn;
    function addSiteParentId(nodeId) {   
         var theParentId = 'a';
         var parentId = relationsManagerResource.GetParentId(nodeId)
             .then(function(response){                               
                 factoryReturn.theParentIdResult = response.data;
                 console.log(theParentId);  // #1
             });                    
    }        
})

Now, we just need to ensure that method addSiteParentId always be resolved before we accessed to property theParentId. We can achieve this by using some ways.

  • Use resolve in router method:

    resolve: {
        parentId: function (your_factory) {
             your_factory.addSiteParentId();
        }
    }
    

then in controller and other services used in your router, just call your_factory.theParentId to get your property. Referce here for more information: http://odetocode.com/blogs/scott/archive/2014/05/20/using-resolve-in-angularjs-routes.aspx

  • Use run method of app to resolve your service.

    app.run(function (your_factory) { your_factory.addSiteParentId(); })
    
  • Inject it in the first controller or services of the controller. In the controller we can call all required init services. Then all remain controllers as children of main controller can be accessed to this property normally as you want.

Chose your ways depend on your context depend on scope of your variable and reading frequency of your variable.

Calculating the sum of two variables in a batch script

According to this helpful list of operators [an operator can be thought of as a mathematical expression] found here, you can tell the batch compiler that you are manipulating variables instead of fixed numbers by using the += operator instead of the + operator.

Hope I Helped!

HTML Input="file" Accept Attribute File Type (CSV)

In addition to the top-answer, CSV files, for example, are reported as text/plain under macOS but as application/vnd.ms-excel under Windows. So I use this:

<input type="file" accept="text/plain, .csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />

Python naming conventions for modules

I would call it nib.py. And I would also name the class Nib.

In a larger python project I'm working on, we have lots of modules defining basically one important class. Classes are named beginning with a capital letter. The modules are named like the class in lowercase. This leads to imports like the following:

from nib import Nib
from foo import Foo
from spam.eggs import Eggs, FriedEggs

It's a bit like emulating the Java way. One class per file. But with the added flexibility, that you can allways add another class to a single file if it makes sense.

Not able to start Genymotion device

I had this same issue and here are the specific configuration that I needed to get this to work.

First, go to the VirtualBox preferences -> Network.

enter image description here

enter image description here

enter image description here

For the "Host-only Networks" tab, focus on the vboxnet0.

enter image description here

Click the icon on the left that looks like a screwdriver. For the Adapter tab, fill in the IPv4 Network Address as 192.168.56.1 Fill in the IPv4 Network Mask as 255.255.255.0

enter image description here

For the DHCP Server tab, select the check box for Enable Server to enable the server Fill in the Server Address as 192.168.56.100 Fill in the Server Mask as 255.255.255.0 Fill in the Lower Address Bound as 192.168.56.101 Fill in the Upper Address Bound as 192.168.56.254

enter image description here

The DHCP server part is what was not correct for me and it fixed my problem.

SQL: sum 3 columns when one column has a null value?

The previous answers using the ISNULL function are correct only for MS Sql Server. The COALESCE function will also work in SQL Server. But will also work in standard SQL database systems. In the given example:

SELECT sum(COALESCE(TotalHoursM,0))
          + COALESCE(TotalHoursT,0)
          + COALESCE(TotalHoursW,0)
          + COALESCE(TotalHoursTH,0)
          + COALESCE(TotalHoursF,0) AS TOTAL FROM LeaveRequest

This is identical to the ISNULL solution with the only difference being the name of the function. Both work in SQL Server but, COALESCE is ANSI standard and ISNULL is not. Also, COALESCE is more flexible. ISNULL will only work with two parameters. If the first parameter is NULL then the value of the second parameter is returned, else the value of the first is returned. COALESCE will take 2 to 'n' (I don't know the limit of 'n') parameters and return the value of the first parameter that is not NULL. When there are only two parameters the effect is the same as ISNULL.

How to print exact sql query in zend framework ?

The query returned from the profiler or query object will have placeholders if you're using those.

To see the exact query run by mysql you can use the general query log.

This will list all the queries which have run since it was enabled. Don't forget to disable this once you've collected your sample. On an active server; this log can fill up very fast.

From a mysql terminal or query tool like MySQL Workbench run:

SET GLOBAL log_output = 'table';
SET GLOBAL general_log = 1;

then run your query. The results are stored in the "mysql.general_log" table.

SELECT * FROM mysql.general_log

To disable the query log:

SET GLOBAL general_log = 0;

To verify it's turned off:

SHOW VARIABLES LIKE 'general%';

This helped me locate a query where the placeholder wasn't being replaced by zend db. Couldn't see that with the profiler.

Android checkbox style

The correct way to do it for Material design is :

Style :

<style name="MyCheckBox" parent="Theme.AppCompat.Light">  
    <item name="colorControlNormal">@color/foo</item>
    <item name="colorControlActivated">@color/bar</item>
</style>  

Layout :

<CheckBox  
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:checked="true"
    android:text="Check Box"
    android:theme="@style/MyCheckBox"/>

It will preserve Material animations on Lollipop+.

How can I change the image displayed in a UIImageView programmatically?

For the purpose of people who may be googling this to try to solve their problem, remember to properly declare the property in your header file and to synthesize the UIImageView in your implementation file... It'll be tough to set the image programmatically without getter and setter methods.

#import <UIKit/UIKit.h>

@interface YOURCONTROLLERNAME : UIViewController {
    IBOutlet UIImageView *imageToDisplay;
}

@property (nonatomic, retain) IBOutlet UIImageView *imageToDisplay;

@end

and then in your .m :

@implementation YOURCONTROLLERNAME

@synthesize imageToDisplay;
//etc, rest of code goes here

From there you should be fine using something like the following to set your image.

[YOURCONTROLLER.imageToDisplay setImage:[UIImage imageNamed:value]];

Convert integer value to matching Java Enum

static final PcapLinkType[] values  = { DLT_NULL, DLT_EN10MB, DLT_EN3MB, null ...}    

...

public static PcapLinkType  getPcapLinkTypeForInt(int num){    
    try{    
       return values[int];    
    }catch(ArrayIndexOutOfBoundsException e){    
       return DLT_UKNOWN;    
    }    
}    

How to display length of filtered ng-repeat data

You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:

<ul>
  <li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
 ....
<span>{{ usersList.length | number }}</span>

If you need examples, see the AngularJs filtered count examples/demos

Setting TIME_WAIT TCP

Pax is correct about the reasons for TIME_WAIT, and why you should be careful about lowering the default setting.

A better solution is to vary the port numbers used for the originating end of your sockets. Once you do this, you won't really care about time wait for individual sockets.

For listening sockets, you can use SO_REUSEADDR to allow the listening socket to bind despite the TIME_WAIT sockets sitting around.