Programs & Examples On #Email formats

How to align a div to the top of its parent but keeping its inline-block behaviour?

As others have said, vertical-align: top is your friend.

As a bonus here is a forked fiddle with added enhancements that make it work in Internet Explorer 6 and Internet Explorer 7 too ;)

Example: here

How can I install a local gem?

if you download the project file from github or other scm host site, use gem build to build the project first, so you can get a whatever.gem file in current directory. Then gem install it!

How to identify if a webpage is being loaded inside an iframe or directly into the browser window?

function amiLoadedInIFrame() {
    try {
         // Introduce a new propery in window.top
         window.top.dummyAttribute = true;
         // If window.dummyAttribute is there.. then window and window.top are same intances
         return !window.dummyAttribute;
    } catch(e) {
         // Exception will be raised when the top is in different domain
         return true;
    }
}

How to close the current fragment by using Button like the back button?

From Fragment A, to go to B, replace A with B and use addToBackstack() before commit().

Now From Fragment B, to go to C, first use popBackStackImmediate(), this will bring back A. Now replace A with C, just like the first transaction.

Hadoop "Unable to load native-hadoop library for your platform" warning

For installing Hadoop it is soooooo much easier installing the free version from Cloudera. It comes with a nice GUI that makes it simple to add nodes, there is no compiling or stuffing around with dependencies, it comes with stuff like hive, pig etc.

http://www.cloudera.com/content/support/en/downloads.html

Steps are: 1) Download 2) Run it 3) Go to web GUI (1.2.3.4:7180) 4) Add extra nodes in the web gui (do NOT install the cloudera software on other nodes, it does it all for you) 5) Within the web GUI go to Home, click Hue and Hue Web UI. This gives you access to Hive, Pig, Sqoop etc.

How to convert datetime to integer in python

It depends on what the integer is supposed to encode. You could convert the date to a number of milliseconds from some previous time. People often do this affixed to 12:00 am January 1 1970, or 1900, etc., and measure time as an integer number of milliseconds from that point. The datetime module (or others like it) will have functions that do this for you: for example, you can use int(datetime.datetime.utcnow().timestamp()).

If you want to semantically encode the year, month, and day, one way to do it is to multiply those components by order-of-magnitude values large enough to juxtapose them within the integer digits:

2012-06-13 --> 20120613 = 10,000 * (2012) + 100 * (6) + 1*(13)

def to_integer(dt_time):
    return 10000*dt_time.year + 100*dt_time.month + dt_time.day

E.g.

In [1]: import datetime

In [2]: %cpaste
Pasting code; enter '--' alone on the line to stop or use Ctrl-D.
:def to_integer(dt_time):
:    return 10000*dt_time.year + 100*dt_time.month + dt_time.day
:    # Or take the appropriate chars from a string date representation.
:--

In [3]: to_integer(datetime.date(2012, 6, 13))
Out[3]: 20120613

If you also want minutes and seconds, then just include further orders of magnitude as needed to display the digits.

I've encountered this second method very often in legacy systems, especially systems that pull date-based data out of legacy SQL databases.

It is very bad. You end up writing a lot of hacky code for aligning dates, computing month or day offsets as they would appear in the integer format (e.g. resetting the month back to 1 as you pass December, then incrementing the year value), and boiler plate for converting to and from the integer format all over.

Unless such a convention lives in a deep, low-level, and thoroughly tested section of the API you're working on, such that everyone who ever consumes the data really can count on this integer representation and all of its helper functions, then you end up with lots of people re-writing basic date-handling routines all over the place.

It's generally much better to leave the value in a date context, like datetime.date, for as long as you possibly can, so that the operations upon it are expressed in a natural, date-based context, and not some lone developer's personal hack into an integer.

Clear variable in python

I used a few options mentioned above :

del self.left

or setting value to None using

self.left = None

It's important to know the differences and put a few exception handlers in place when you use set the value to None. If you're printing the value of the conditional statements using a template, say,

print("The value of the variable is {}".format(self.left))

you might see the value of the variable printing "The value of the variable is None". Thus, you'd have to put a few exception handlers there :

if self.left:
    #Then only print stuff

The above command will only print values if self.left is not None

Update Multiple Rows in Entity Framework from a list of ids

I think you are looking for below method:

var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
    var friends= db.Friends.Where(f=>idList.Contains(f.ID));
    friends.ForEachAsync(a=>a.msgSentBy='1234');
    await db.SaveChangesAsync();
}

This should be the efficient way of handling this.

403 Forbidden vs 401 Unauthorized HTTP responses

This question was asked some time ago, but people's thinking moves on.

Section 6.5.3 in this draft (authored by Fielding and Reschke) gives status code 403 a slightly different meaning to the one documented in RFC 2616.

It reflects what happens in authentication & authorization schemes employed by a number of popular web-servers and frameworks.

I've emphasized the bit I think is most salient.

6.5.3. 403 Forbidden

The 403 (Forbidden) status code indicates that the server understood the request but refuses to authorize it. A server that wishes to make public why the request has been forbidden can describe that reason in the response payload (if any).

If authentication credentials were provided in the request, the server considers them insufficient to grant access. The client SHOULD NOT repeat the request with the same credentials. The client MAY repeat the request with new or different credentials. However, a request might be forbidden for reasons unrelated to the credentials.

An origin server that wishes to "hide" the current existence of a forbidden target resource MAY instead respond with a status code of 404 (Not Found).

Whatever convention you use, the important thing is to provide uniformity across your site / API.

Calculate a MD5 hash from a string

public static string Md5(string input, bool isLowercase = false)
        {
            using (MD5 md5 = MD5.Create())
            {
                byte[] byteHash = md5.ComputeHash(Encoding.UTF8.GetBytes(input));
                string hash = BitConverter.ToString(byteHash).Replace("-", "");
                return (isLowercase) ? hash.ToLower() : hash;
            }
        }

How to call a function, PostgreSQL

if your function does not want to return anything you should declare it to "return void" and then you can call it like this "perform functionName(parameter...);"

How to specify the download location with wget?

From the manual page:

-P prefix
--directory-prefix=prefix
           Set directory prefix to prefix.  The directory prefix is the
           directory where all other files and sub-directories will be
           saved to, i.e. the top of the retrieval tree.  The default
           is . (the current directory).

So you need to add -P /tmp/cron_test/ (short form) or --directory-prefix=/tmp/cron_test/ (long form) to your command. Also note that if the directory does not exist it will get created.

Cannot find firefox binary in PATH. Make sure firefox is installed

System.setProperty("webdriver.gecko.driver", "D:\\Katalon_Studio_Windows_64-5.10.1\\configuration\\resources\\drivers\\firefox_win64\\geckodriver.exe");
        DesiredCapabilities capabilities = DesiredCapabilities.firefox();
        capabilities.setCapability("marionette", true);
        WebDriver driver = new FirefoxDriver(capabilities);
        DriverFactory.changeWebDriver(driver)

How can I echo a newline in a batch file?

Here you go, create a .bat file with the following in it :

@echo off
REM Creating a Newline variable (the two blank lines are required!)
set NLM=^


set NL=^^^%NLM%%NLM%^%NLM%%NLM%
REM Example Usage:
echo There should be a newline%NL%inserted here.

echo.
pause

You should see output like the following:

There should be a newline
inserted here.

Press any key to continue . . .

You only need the code between the REM statements, obviously.

Embed Google Map code in HTML with marker

Learning Google's JavaScript library is a good option. If you don't feel like getting into coding you might find Maps Engine Lite useful.

It is a tool recently published by Google where you can create your personal maps (create markers, draw geometries and adapt the colors and styles).

Here is an useful tutorial I found: Quick Tip: Embedding New Google Maps

Hide horizontal scrollbar on an iframe?

If you are allowed to change the code of the document inside your iframe and that content is visible only using its parent window, simply add the following CSS in your iframe:

body {
    overflow:hidden;
}

Here a very simple example:

http://jsfiddle.net/u5gLoav9/

This solution allow you to:

  • Keep you HTML5 valid as it does not need scrolling="no" attribute on the iframe (this attribute in HTML5 has been deprecated).

  • Works on the majority of browsers using CSS overflow:hidden

  • No JS or jQuery necessary.

Notes:

To disallow scroll-bars horizontally, use this CSS instead:

overflow-x: hidden;

Move UIView up when the keyboard appears in iOS

Bind a view to keyboard is also an option (see GIF at the bottom of the answer)

Swift 4

Use an extension: (Wasn't fully tested)

extension UIView{
    func bindToKeyboard(){
        NotificationCenter.default.addObserver(self, selector: #selector(UIView.keyboardWillChange(notification:)), name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
    }

    func unbindToKeyboard(){
        NotificationCenter.default.removeObserver(self, name: Notification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    @objc
    func keyboardWillChange(notification: Notification) {
        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).cgRectValue
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue
        let deltaY = targetFrame.origin.y - curFrame.origin.y

        UIView.animateKeyframes(withDuration: duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
            self.frame.origin.y+=deltaY

        },completion: nil)

    }
}

Swift 2 + 3

Use an extension:

extension UIView{
    func bindToKeyboard(){
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UIView.keyboardWillChange(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
    }


    func keyboardWillChange(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
        let curve = notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! UInt
        let curFrame = (notification.userInfo![UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
        let targetFrame = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        let deltaY = targetFrame.origin.y - curFrame.origin.y


        UIView.animateKeyframesWithDuration(duration, delay: 0.0, options: UIViewKeyframeAnimationOptions(rawValue: curve), animations: {
                self.frame.origin.y+=deltaY

        },completion: nil)

    }  
}

Usage:

// view did load...
textField.bindToKeyboard()

...

// view unload
textField.unbindToKeyboard()

result:
enter image description here

important
Don't forget to remove the observer when view is unloading

Getting full-size profile picture

With Javascript you can get full size profile images like this

pass your accessToken to the getface() function from your FB.init call

function getface(accessToken){
  FB.api('/me/friends', function (response) {
    for (id in response.data) { 
        var homie=response.data[id].id         
        FB.api(homie+'/albums?access_token='+accessToken, function (aresponse) {
          for (album in aresponse.data) {
            if (aresponse.data[album].name == "Profile Pictures") {                      
              FB.api(aresponse.data[album].id + "/photos", function(aresponse) {
                console.log(aresponse.data[0].images[0].source); 
              });                  
            }
          }   
        });
    }
  });
}

What data type to use for hashed password field and what length?

It really depends on the hashing algorithm you're using. The length of the password has little to do with the length of the hash, if I remember correctly. Look up the specs on the hashing algorithm you are using, run a few tests, and truncate just above that.

Comparing Dates in Oracle SQL

from your query:

Select employee_id, count(*) From Employee 
Where to_char(employee_date_hired, 'DD-MON-YY') > '31-DEC-95' 

i think its not to display the number of employees that are hired after June 20, 1994. if you want show number of employees, you can use:

Select count(*) From Employee 
Where to_char(employee_date_hired, 'YYYMMMDDD') > 19940620 

I think for best practice to compare dates you can use:

employee_date_hired > TO_DATE('20-06-1994', 'DD-MM-YYYY');
or
to_char(employee_date_hired, 'YYYMMMDDD') > 19940620;

How do I find out what is hammering my SQL Server?

You can find some useful query here:

Investigating the Cause of SQL Server High CPU

For me this helped a lot:

SELECT s.session_id,
    r.status,
    r.blocking_session_id 'Blk by',
    r.wait_type,
    wait_resource,
    r.wait_time / (1000 * 60) 'Wait M',
    r.cpu_time,
    r.logical_reads,
    r.reads,
    r.writes,
    r.total_elapsed_time / (1000 * 60) 'Elaps M',
    Substring(st.TEXT,(r.statement_start_offset / 2) + 1,
    ((CASE r.statement_end_offset
WHEN -1
THEN Datalength(st.TEXT)
ELSE r.statement_end_offset
END - r.statement_start_offset) / 2) + 1) AS statement_text,
    Coalesce(Quotename(Db_name(st.dbid)) + N'.' + Quotename(Object_schema_name(st.objectid, st.dbid)) + N'.' +
    Quotename(Object_name(st.objectid, st.dbid)), '') AS command_text,
    r.command,
    s.login_name,
    s.host_name,
    s.program_name,
    s.last_request_end_time,
    s.login_time,
    r.open_transaction_count
FROM sys.dm_exec_sessions AS s
    JOIN sys.dm_exec_requests AS r
ON r.session_id = s.session_id
    CROSS APPLY sys.Dm_exec_sql_text(r.sql_handle) AS st
WHERE r.session_id != @@SPID
ORDER BY r.cpu_time desc

In the fields of status, wait_type and cpu_time you can find the most cpu consuming task that is running right now.

Adding an assets folder in Android Studio

According to new Gradle based build system. We have to put assets under main folder.

Or simply right click on your project and create it like

File > New > folder > assets Folder

How to get first N number of elements from an array

With lodash, take function, you can achieve this by following:

_.take([1, 2, 3]);
// => [1]
 
_.take([1, 2, 3], 2);
// => [1, 2]
 
_.take([1, 2, 3], 5);
// => [1, 2, 3]
 
_.take([1, 2, 3], 0);
// => []

Execute a large SQL script (with GO commands)

Use SQL Server Management Objects (SMO) which understands GO separators. See my blog post here: http://weblogs.asp.net/jongalloway/Handling-_2200_GO_2200_-Separators-in-SQL-Scripts-2D00-the-easy-way

Sample code:

public static void Main()    
{        
  string scriptDirectory = "c:\\temp\\sqltest\\";
  string sqlConnectionString = "Integrated Security=SSPI;" +
  "Persist Security Info=True;Initial Catalog=Northwind;Data Source=(local)";
  DirectoryInfo di = new DirectoryInfo(scriptDirectory);
  FileInfo[] rgFiles = di.GetFiles("*.sql");
  foreach (FileInfo fi in rgFiles)
  {
        FileInfo fileInfo = new FileInfo(fi.FullName);
        string script = fileInfo.OpenText().ReadToEnd();
        using (SqlConnection connection = new SqlConnection(sqlConnectionString))
        {
            Server server = new Server(new ServerConnection(connection));
            server.ConnectionContext.ExecuteNonQuery(script);
        }
   }
}

If that won't work for you, see Phil Haack's library which handles that: http://haacked.com/archive/2007/11/04/a-library-for-executing-sql-scripts-with-go-separators-and.aspx

Removing a non empty directory programmatically in C or C++

You want to write a function (a recursive function is easiest, but can easily run out of stack space on deep directories) that will enumerate the children of a directory. If you find a child that is a directory, you recurse on that. Otherwise, you delete the files inside. When you are done, the directory is empty and you can remove it via the syscall.

To enumerate directories on Unix, you can use opendir(), readdir(), and closedir(). To remove you use rmdir() on an empty directory (i.e. at the end of your function, after deleting the children) and unlink() on a file. Note that on many systems the d_type member in struct dirent is not supported; on these platforms, you will have to use stat() and S_ISDIR(stat.st_mode) to determine if a given path is a directory.

On Windows, you will use FindFirstFile()/FindNextFile() to enumerate, RemoveDirectory() on empty directories, and DeleteFile() to remove files.

Here's an example that might work on Unix (completely untested):

int remove_directory(const char *path) {
   DIR *d = opendir(path);
   size_t path_len = strlen(path);
   int r = -1;

   if (d) {
      struct dirent *p;

      r = 0;
      while (!r && (p=readdir(d))) {
          int r2 = -1;
          char *buf;
          size_t len;

          /* Skip the names "." and ".." as we don't want to recurse on them. */
          if (!strcmp(p->d_name, ".") || !strcmp(p->d_name, ".."))
             continue;

          len = path_len + strlen(p->d_name) + 2; 
          buf = malloc(len);

          if (buf) {
             struct stat statbuf;

             snprintf(buf, len, "%s/%s", path, p->d_name);
             if (!stat(buf, &statbuf)) {
                if (S_ISDIR(statbuf.st_mode))
                   r2 = remove_directory(buf);
                else
                   r2 = unlink(buf);
             }
             free(buf);
          }
          r = r2;
      }
      closedir(d);
   }

   if (!r)
      r = rmdir(path);

   return r;
}

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

.crx file install in chrome

I arrived to this question looking for the same but for Chromium (actually I'm using https://ungoogled-software.github.io). So in case anyone else is looking for the same:

  1. Go to chrome://flags/
  2. Search for Handling of extension MIME type requests
  3. Select Always prompt for install
  4. Search for an extension and copy its URL (something like https://chrome.google.com/webstore/detail/...)
  5. Paste the URL in https://crxextractor.com/ and download the .CRX
  6. Voilà, Chromium will prompt for installation

How do I UPDATE from a SELECT in SQL Server?

The below solution works for a MySQL database:

UPDATE table1 a , table2 b 
SET a.columname = 'some value' 
WHERE b.columnname IS NULL ;

Flash CS4 refuses to let go

Try deleting your ASO files.

ASO files are cached compiled versions of your class files. Although the IDE is a lot better at letting go of old caches when changes are made, sometimes you have to manually delete them. To delete ASO files: Control>Delete ASO Files.

This is also the cause of the "I-am-not-seeing-my-changes-so-let-me-add-a-trace-now-everything-works" bug that was introduced in CS3.

Registering for Push Notifications in Xcode 8/Swift 3.0?

Well this work for me. First in AppDelegate

import UserNotifications

Then:

   func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        registerForRemoteNotification()
        return true
    }

    func registerForRemoteNotification() {
        if #available(iOS 10.0, *) {
            let center  = UNUserNotificationCenter.current()
            center.delegate = self
            center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
                if error == nil{
                    UIApplication.shared.registerForRemoteNotifications()
                }
            }
        }
        else {
            UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
            UIApplication.shared.registerForRemoteNotifications()
        }
    }

To get devicetoken:

  func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

       let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})

}

How do I write a RGB color value in JavaScript?

dec2hex = function (d) {
  if (d > 15)
    { return d.toString(16) } else
    { return "0" + d.toString(16) }
}
rgb = function (r, g, b) { return "#" + dec2hex(r) + dec2hex(g) + dec2hex(b) };

and:

parent.childNodes[1].style.color = rgb(155, 102, 102);

How to view the Folder and Files in GAC?

To view the files just browse them from the command prompt (cmd), eg.:

c:\>cd \Windows\assembly\GAC_32
c:\Windows\assembly\GAC_32> dir

To add and remove files from the GAC use the tool gacutil

jquery .on() method with load event

I'm not sure what you're going for here--by the time jQuery(document).ready() has executed, it has already loaded, and thus document's load event will already have been called. Attaching the load event handler at this point will have no effect and it will never be called. If you're attempting to alert "started" once the document has loaded, just put it right in the (document).ready() call, like this:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
    });

    alert('started');

});?

If, as your code also appears to insinuate, you want to fire the alert when .abc has loaded, put it in an individual .load handler:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
    });

    $(".abc").on("load", function() {
        alert('started');
    }
});?

Finally, I see little point in using jQuery in one place and $ in another. It's generally better to keep your code consistent, and either use jQuery everywhere or $ everywhere, as the two are generally interchangeable.

How to fetch all Git branches

$ git remote update
$ git pull --all

This assumes all branches are tracked.

If they aren't you can fire this in Bash:

for remote in `git branch -r `; do git branch --track $remote; done

Then run the command.

Find nginx version?

If you don't know where it is, locate nginx first.

ps -ef | grep nginx

Then you will see something like this:

root      4801     1  0 May23 ?        00:00:00 nginx: master process /opt/nginx/sbin/nginx -c /opt/nginx/conf/nginx.conf
root     12427 11747  0 03:53 pts/1    00:00:00 grep --color=auto nginx
nginx    24012  4801  0 02:30 ?        00:00:00 nginx: worker process                              
nginx    24013  4801  0 02:30 ?        00:00:00 nginx: worker process

So now you already know where nginx is. You can use the -v or -V. Something like:

/opt/nginx/sbin/nginx -v

How to select a node of treeview programmatically in c#?

yourNode.Toggle(); //use that function on your node, it toggles it

syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING

I stumbled on this question as I had the same error. Mine was due to a slightly different problem and since I resolved it on my own I thought it useful to share here. Original code with issue:

$comment = "$_POST['comment']";

Because of the enclosing double-quotes, the index is not dereferenced properly leading to the assignment error. In my case I chose to fix it like this:

$comment = "$_POST[comment]";

but dropping either pair of quotes works; it's a matter of style I suppose :)

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

yo need create the user "pma" in mysql or change this lines(user and password for mysql):

/* User for advanced features */
$cfg['Servers'][$i]['controluser'] = 'pma'; 
$cfg['Servers'][$i]['controlpass'] = '';

Linux: /etc/phpmyadmin/config.inc.php

How to get source code of a Windows executable?

I would (and have) used IDA Pro to decompile executables. It creates semi-complete code, you can decompile to assembly or C.

If you have a copy of the debug symbols around, load those into IDA before decompiling and it will be able to name many of the functions, parameters, etc.

How can you undo the last git add?

So the real answer to

Can this programmer now unstage his last changes with some magical git command?

is actually: No, you cannot unstage just the last git add.

That is if we interpret the question as in the following situation:

Initial file:

void foo() {

}

main() {
    foo();
}

First change followed by git add:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

Second change followed by git add:

void foo(int bar, String baz) {
    print("$bar $baz");
}

main() {
    foo(1337, "h4x0r");
}

In this case, git reset -p will not help, since its smallest granularity is lines. git doesn't know that about the intermediate state of:

void foo(int bar) {
    print("$bar");
}

main() {
    foo(1337);
}

any more.

How to delete last character from a string using jQuery?

@skajfes and @GolezTrol provided the best methods to use. Personally, I prefer using "slice()". It's less code, and you don't have to know how long a string is. Just use:

//-----------------------------------------
// @param begin  Required. The index where 
//               to begin the extraction. 
//               1st character is at index 0
//
// @param end    Optional. Where to end the
//               extraction. If omitted, 
//               slice() selects all 
//               characters from the begin 
//               position to the end of 
//               the string.
var str = '123-4';
alert(str.slice(0, -1));

How do I get the selected element by name and then get the selected value from a dropdown using jQuery?

To add to the answers here, ensure there's no space between the select and [name...

Wrong:

'select [name=' + name + ']'
       ^

Right:

'select[name=' + name + ']'

Class method decorator with self arguments?

from re import search
from functools import wraps

def is_match(_lambda, pattern):
    def wrapper(f):
        @wraps(f)
        def wrapped(self, *f_args, **f_kwargs):
            if callable(_lambda) and search(pattern, (_lambda(self) or '')): 
                f(self, *f_args, **f_kwargs)
        return wrapped
    return wrapper

class MyTest(object):

    def __init__(self):
        self.name = 'foo'
        self.surname = 'bar'

    @is_match(lambda x: x.name, 'foo')
    @is_match(lambda x: x.surname, 'foo')
    def my_rule(self):
        print 'my_rule : ok'

    @is_match(lambda x: x.name, 'foo')
    @is_match(lambda x: x.surname, 'bar')
    def my_rule2(self):
        print 'my_rule2 : ok'



test = MyTest()
test.my_rule()
test.my_rule2()

ouput: my_rule2 : ok

How do I use Wget to download all images into a single folder, from a URL?

I wrote a shellscript that solves this problem for multiple websites: https://github.com/eduardschaeli/wget-image-scraper

(Scrapes images from a list of urls with wget)

What is the Java equivalent of PHP var_dump?

The apache commons lang package provides such a class which can be used to build up a default toString() method using reflection to get the values of fields. Just have a look at this.

Verify if file exists or not in C#

Can't comment yet, but I just wanted to disagree/clarify with erikkallen.

You should not just catch the exception in the situation you've described. If you KNEW that the file should be there and due to some exceptional case, it wasn't, then it would be acceptable to just attempt to access the file and catch any exception that occurs.

In this case, however, you are receiving input from a user and have little reason to believe that the file exists. Here you should always use File.Exists().

I know it is cliché, but you should only use Exceptions for an exceptional event, not as part as the normal flow of your application. It is expensive and makes code more difficult to read/follow.

Determine file creation date in Java

Java nio has options to access creationTime and other meta-data as long as the filesystem provides it. Check this link out

For example(Provided based on @ydaetskcoR's comment):

Path file = ...;
BasicFileAttributes attr = Files.readAttributes(file, BasicFileAttributes.class);

System.out.println("creationTime: " + attr.creationTime());
System.out.println("lastAccessTime: " + attr.lastAccessTime());
System.out.println("lastModifiedTime: " + attr.lastModifiedTime());

Algorithm for Determining Tic Tac Toe Game Over

Ultra-efficient Bit-boarding

Let's store the game in a binary integer, and evaluate everything using just one step!

  • We know that X's moves occupy 9 bits: xxx xxx xxx
  • We know that O's moves occupy 9 bits: ooo ooo ooo

So, a board position could be represented in just 18 bits: xoxoxo xoxoxo xoxoxo

But, whilst this might look efficient, it doesn't help us with determining a win. We need a more useful bit pattern... one that not only encodes the moves, but also encodes the rows, columns and diagonals in a reasonable way.

I would do this by using a clever integer value for each board position.

Choosing a more useful representation

First, we need a board notation, just so that we can discuss this. So, similar to Chess, lets number the rows with letters and the columns with numbers - so we know which square we're talking about

1 2 3
A a1 a2 a3
B b1 b2 b3
C c1 c2 c3

And let's give each a binary value.

a1 = 100 000 000 100 000 000 100 000 ; Row A Col 1 (top left corner)
a2 = 010 000 000 000 100 000 000 000 ; Row A Col 2 (top edge)
a3 = 001 000 000 000 000 100 000 100 ; Row A Col 3 (top right corner)
b1 = 000 100 000 010 000 000 000 000 ; Row B Col 1 (left edge)
b2 = 000 010 000 000 010 000 010 010 ; Row B Col 2 (middle square)
b3 = 000 001 000 000 000 010 000 000 ; Row B Col 4 (right edge)
c1 = 000 000 100 001 000 000 000 001 ; Row C Col 1 (bottom left corner)
c2 = 000 000 010 000 001 000 000 000 ; Row C Col 2 (bottom edge)
c3 = 000 000 001 000 000 001 001 000 ; Row C Col 3 (bottom right corner)

... where, the binary values encode which rows, columns and diagonals the position appears in. (we'll look at how this works this later)

We will use these values to build two representations of the game, one for X and one for O

  • X starts with an empty board : 000 000 000 000 000 000 000 000
  • O starts with an empty board : 000 000 000 000 000 000 000 000

Let's follow X's moves (O would be the same principle)

  • X plays A1... so we OR (the X board) with value A1
  • X plays A2... so we OR with value A2
  • X plays A3... so we OR with value A3

What does that do to X's board value :

  1. a1 = 100 000 000 100 000 000 100 000 ... ORed with
  2. a2 = 010 000 000 000 100 000 000 000 ... ORed with
  3. a3 = 001 000 000 000 000 100 000 100 ... equals :

XB = 111 000 000 100 100 100 100 100

Reading from left to right we see that X has :

  • 111 (All positions) in Row 1 (\o/ A win, Yay!)
  • 000 (No positions) in Row 2
  • 000 (No positions) in Row 3
  • 100 (One position) Only the first position of Column 1
  • 100 (One position) Only the first position of Column 1
  • 100 (One position) Only the first position of Column 1
  • 100 (One position) Only the first position of Diagonal 1
  • 100 (One position) Only the first position of Diagonal 2

You'll notice that whenever X (or O) has a winning line, then there will also be three consecutive bits in his board value. Precisely Where those three bits are, dictates which row/column/diagonal he won on.

So, the trick now is to find a way to check for this (three consecutive bits set) condition in a single operation.

Modifying the values to make detection easier

To assist with this, let's change our bit representation so that there are always ZEROs between the groups of three (Because 001 110 is also three consecutive bits - but they are NOT a valid win ... so, a fixed zero spacer would break these up: 0 001 0 110)

So, after adding some spacing ZEROes, we can be confident that ANY three consecutive set bits in X's or O's board value indicates a win!

So, our new binary values (with zero-padding) look like this :

  • a1 = 100 0 000 0 000 0 100 0 000 0 000 0 100 0 000 0 ; 0x80080080 (hex)
  • a2 = 010 0 000 0 000 0 000 0 100 0 000 0 000 0 000 0 ; 0x40008000
  • a3 = 001 0 000 0 000 0 000 0 000 0 100 0 000 0 100 0 ; 0x20000808
  • b1 = 000 0 100 0 000 0 010 0 000 0 000 0 000 0 000 0 ; 0x08040000
  • b2 = 000 0 010 0 000 0 000 0 010 0 000 0 010 0 010 0 ; 0x04004044
  • b3 = 000 0 001 0 000 0 000 0 000 0 010 0 000 0 000 0 ; 0x02000400
  • c1 = 000 0 000 0 100 0 001 0 000 0 000 0 000 0 001 0 ; 0x00820002
  • c2 = 000 0 000 0 010 0 000 0 001 0 000 0 000 0 000 0 ; 0x00402000
  • c3 = 000 0 000 0 001 0 000 0 000 0 001 0 001 0 000 0 ; 0x00200220

You'll notice that each "winline" of the board now requires 4 bits.

8 winlines x 4 bits each = 32 bits! Isn't that convenient : )))))

Parsing

We could shift through all the bits looking for three consecutive bits, but that will take 32 shifts x 2 players... and a counter to keep track. It's slow!

We could AND with 0xF, looking for the value 8+4+2=14. And this would allow us to check 4 bits at a time. Cutting the number of shifts by a quarter. But again, this is slow!

So, instead, let's check ALL of the possibilities at once...

Ultra-efficient win detection

Imagine we wanted to evaluate the A3+A1+B2+C3 case (a win on the diagonal)

a1 = 100 0 000 0 000 0 100 0 000 0 000 0 100 0 000 0, OR
a3 = 001 0 000 0 000 0 000 0 000 0 100 0 000 0 100 0, OR
b2 = 000 0 010 0 000 0 000 0 010 0 000 0 010 0 010 0, OR
c3 = 000 0 000 0 001 0 000 0 000 0 001 0 001 0 000 0, =

XB = 101 0 010 0 001 0 100 0 010 0 101 0 111 0 110 0  (See the win, on Diagonal 1?)

Now, let's check it for a win, by efficiently merging three bits into one...

Simply use : XB AND (XB << 1) AND (XB >> 1) in other words: XB ANDed with (XB shifted left) AND (XB shiftted right)

Let's try an example...

10100100001010000100101011101100 ; whitespaces removed for easy shifting
(AND)
01001000010100001001010111011000 ; XB shifted left
(AND)
01010010000101000010010101110110 ; XB shifted left
(Equals)
00000000000000000000000001000000

See that? Any non-zero result means a win!

But, where did they win

Want to know where they won? Well, you could just use a second table :

0x40000000 = RowA
0x04000000 = RowB
0x00400000 = RowC
0x00040000 = Col1
0x00004000 = Col2
0x00000400 = Col3
0x00000040 = Diag1
0x00000004 = Diag2

However, we can be smarter than that, as the pattern is VERY regular!

For example, in assembly you can use BSF (Bit Scan Forward) to find the number of leading zeros. Then subtract 2 and then /4 (Shift Right 2) - to get a number between 0 and 8... which you can use as an index to look up into an array of win strings :

{"wins the top row", "takes the middle row!", ... "steals the diagonal!" }

This makes the whole game logic... from move checking, to board updating and right through to win/loss detection and an appropriate success message, all fit in a handful of ASM instructions.

... it's tiny, efficient and ultrafast!

Checking whether a move is playable

Obviously, ORing "X's board" with "O's board" = ALL POSITIONS

So, you can check if a move is valid quite easily. If user chooses UpperLeft, this position has an integer value. Just check the 'AND' of this Value with (XB OR OB)...

... if the result is nonzero, then the position is already in use.

Conclusion

If you're looking for efficient ways to process a board, don't start with a board object. Try to discover some useful abstraction.

See if the states fit within an integer, and think about what an 'easy' bitmask to process would look like. With some clever choice of integers to represent moves, positions or boards... you might find that the entire game can be played, evaluated and scored VERY efficiently - using simply bitwise logic.

Closing apologies

BTW I'm not a regular here on StackOverflow, so I hope this post wasn't too chaotic to follow. Also, please be kind... "Human" is my second language and I'm not quite fluent yet ;)

Anyway, I hope this helps someone.

ValueError: max() arg is an empty sequence

I realized that I was iterating over a list of lists where some of them were empty. I fixed this by adding this preprocessing step:

tfidfLsNew = [x for x in tfidfLs if x != []]

the len() of the original was 3105, and the len() of the latter was 3101, implying that four of my lists were completely empty. After this preprocess my max() min() etc. were functioning again.

CMake is not able to find BOOST libraries

Long answer to short, if you install boost in custom path, all header files must in ${path}/boost/.

if you want to konw why cmake can't find the requested Boost libraries after you have set BOOST_ROOT/BOOST_INCLUDEDIR, you can check cmake install location path_to_cmake/share/cmake-xxx/Modules/FindBoost.

cmake which will find Boost_INCLUDE_DIR in boost/config.hpp in BOOST_ROOT. That means your boost header file must in ${path}/boost/, any other format (such as ${path}/boost-x.y.z) will not be suitable for find_package in CMakeLists.txt.

Getting error: Peer authentication failed for user "postgres", when trying to get pgsql working with rails

Use host=localhost in connection.

PGconn *conn = PQconnectdb(
    "host=localhost user=postgres dbname=postgres password=123"
);

Passing Multiple route params in Angular2

Two Methods for Passing Multiple route params in Angular

Method-1

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2/:id1/:id2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', "id1","id2"]);
 }
}

Method-2

In app.module.ts

Set path as component2.

imports: [
 RouterModule.forRoot(
 [ {path: 'component2', component: MyComp2}])
]

Call router to naviagte to MyComp2 with multiple params id1 and id2.

export class MyComp1 {
onClick(){
    this._router.navigate( ['component2', {id1: "id1 Value", id2: 
    "id2  Value"}]);
 }
}

Why do I need 'b' to encode a string with Base64?

If the string is Unicode the easiest way is:

import base64                                                        

a = base64.b64encode(bytes(u'complex string: ñáéíóúÑ', "utf-8"))

# a: b'Y29tcGxleCBzdHJpbmc6IMOxw6HDqcOtw7PDusOR'

b = base64.b64decode(a).decode("utf-8", "ignore")                    

print(b)
# b :complex string: ñáéíóúÑ

How to create cross-domain request?

@RestController
@RequestMapping(value = "/profile")
@CrossOrigin(origins="*")
public class UserProfileController {

SpringREST provides @CrossOrigin annotations where (origins="*") allow access to REST APIS from any source.

We can add it to respective API or entire RestController.

If table exists drop table then create it, if it does not exist just create it

Just use DROP TABLE IF EXISTS:

DROP TABLE IF EXISTS `foo`;
CREATE TABLE `foo` ( ... );

Try searching the MySQL documentation first if you have any other problems.

How do I partially update an object in MongoDB so the new object will overlay / merge with the existing one

Make an update object with the property names including the necessary dot path. ("somekey."+ from OP's example), and then use that do the update.

//the modification that's requested
updateReq = { 
   param2 : "val2_new",
   param3 : "val3_new"   
}

//build a renamed version of the update request
var update = {};
for(var field in updateReq){
    update["somekey."+field] = updateReq[field];
}

//apply the update without modifying fields not originally in the update
db.collection.update({._id:...},{$set:update},{upsert:true},function(err,result){...});

Spring + Web MVC: dispatcher-servlet.xml vs. applicationContext.xml (plus shared security)

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>TestPOC</display-name>

  <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
    </context-param>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

List all column except for one in R

You can index and use a negative sign to drop the 3rd column:

data[,-3]

Or you can list only the first 2 columns:

data[,c("c1", "c2")]
data[,1:2]

Don't forget the comma and referencing data frames works like this: data[row,column]

What is the difference between static func and class func in Swift?

Both the static and class keywords allow us to attach methods to a class rather than to instances of a class. For example, you might create a Student class with properties such as name and age, then create a static method numberOfStudents that is owned by the Student class itself rather than individual instances.

Where static and class differ is how they support inheritance. When you make a static method it becomes owned by the class and can't be changed by subclasses, whereas when you use class it may be overridden if needed.

Here is an Example code:

  class Vehicle {
    static func getCurrentSpeed() -> Int {
        return 0
    }

    class func getCurrentNumberOfPassengers() -> Int {
        return 0
    } 

  }

  class Bicycle: Vehicle {
    //This is not allowed
    //Compiler error: "Cannot override static method"
  //  static override func getCurrentSpeed() -> Int {
  //        return 15
  //  }

      class override func getCurrentNumberOfPassengers() -> Int {
        return 1
      }
  }

Rendering HTML elements to <canvas>

Take a look on MDN

It will render html element using creating SVG images.

For Example: There is <em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span> HTML element. And I want to add it into <canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas> Canvas Element.

Here is Javascript Code to add HTML element to canvas.

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
_x000D_
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +_x000D_
  '<foreignObject width="100%" height="100%">' +_x000D_
  '<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +_x000D_
  '<em>I</em> like <span style="color:white; text-shadow:0 0 2px blue;">cheese</span>' +_x000D_
  '</div>' +_x000D_
  '</foreignObject>' +_x000D_
  '</svg>';_x000D_
_x000D_
var DOMURL = window.URL || window.webkitURL || window;_x000D_
_x000D_
var img = new Image();_x000D_
var svg = new Blob([data], {_x000D_
  type: 'image/svg+xml;charset=utf-8'_x000D_
});_x000D_
var url = DOMURL.createObjectURL(svg);_x000D_
_x000D_
img.onload = function() {_x000D_
  ctx.drawImage(img, 0, 0);_x000D_
  DOMURL.revokeObjectURL(url);_x000D_
}_x000D_
_x000D_
img.src = url;
_x000D_
<canvas id="canvas" style="border:2px solid black;" width="200" height="200"></canvas>
_x000D_
_x000D_
_x000D_

How to concatenate strings with padding in sqlite

The || operator is "concatenate" - it joins together the two strings of its operands.

From http://www.sqlite.org/lang_expr.html

For padding, the seemingly-cheater way I've used is to start with your target string, say '0000', concatenate '0000423', then substr(result, -4, 4) for '0423'.

Update: Looks like there is no native implementation of "lpad" or "rpad" in SQLite, but you can follow along (basically what I proposed) here: http://verysimple.com/2010/01/12/sqlite-lpad-rpad-function/

-- the statement below is almost the same as
-- select lpad(mycolumn,'0',10) from mytable

select substr('0000000000' || mycolumn, -10, 10) from mytable

-- the statement below is almost the same as
-- select rpad(mycolumn,'0',10) from mytable

select substr(mycolumn || '0000000000', 1, 10) from mytable

Here's how it looks:

SELECT col1 || '-' || substr('00'||col2, -2, 2) || '-' || substr('0000'||col3, -4, 4)

it yields

"A-01-0001"
"A-01-0002"
"A-12-0002"
"C-13-0002"
"B-11-0002"

Why doesn't RecyclerView have onItemClickListener()?

After reading @MLProgrammer-CiM's answer, here is my code:

class NormalViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

    @Bind(R.id.card_item_normal)
    CardView cardView;

    public NormalViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
        cardView.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        if(v instanceof CardView) {
            // use getAdapterPosition() instead of getLayoutPosition()
            int itemPosition = getAdapterPosition();
            removeItem(itemPosition);
        }
    }
}

POST data in JSON format

Not sure if you want jQuery.

var form;

form.onsubmit = function (e) {
  // stop the regular form submission
  e.preventDefault();

  // collect the form data while iterating over the inputs
  var data = {};
  for (var i = 0, ii = form.length; i < ii; ++i) {
    var input = form[i];
    if (input.name) {
      data[input.name] = input.value;
    }
  }

  // construct an HTTP request
  var xhr = new XMLHttpRequest();
  xhr.open(form.method, form.action, true);
  xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');

  // send the collected data as JSON
  xhr.send(JSON.stringify(data));

  xhr.onloadend = function () {
    // done
  };
};

gnuplot plotting multiple line graphs

Whatever your separator is in your ls.dat, you can specify it to gnuplot:

set datafile separator "\t"

Connect with SSH through a proxy

@rogerdpack for windows platform it is really hard to find a nc.exe with -X(http_proxy), however, I have found nc can be replaced by ncat, full example as follows:

Host github.com
     HostName github.com
         #ProxyCommand nc -X connect -x 127.0.0.1:1080 %h %p
         ProxyCommand ncat --proxy 127.0.0.1:1080 %h %p
     User git
     Port 22
     IdentityFile D:\Users\Administrator\.ssh\github_key

and ncat with --proxy can do a perfect work

How to resize Image in Android?

Following is the function to resize bitmap by keeping the same Aspect Ratio. Here I have also written a detailed blog post on the topic to explain this method. Resize a Bitmap by Keeping the Same Aspect Ratio.

   public static Bitmap resizeBitmap(Bitmap source, int maxLength) {
       try {
           if (source.getHeight() >= source.getWidth()) {
               int targetHeight = maxLength;
               if (source.getHeight() <= targetHeight) { // if image already smaller than the required height
                   return source;
               }

               double aspectRatio = (double) source.getWidth() / (double) source.getHeight();
               int targetWidth = (int) (targetHeight * aspectRatio);

               Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
               if (result != source) {
               }
               return result;
           } else {
               int targetWidth = maxLength;

               if (source.getWidth() <= targetWidth) { // if image already smaller than the required height
                   return source;
               }

               double aspectRatio = ((double) source.getHeight()) / ((double) source.getWidth());
               int targetHeight = (int) (targetWidth * aspectRatio);

               Bitmap result = Bitmap.createScaledBitmap(source, targetWidth, targetHeight, false);
               if (result != source) {
               }
               return result;

           }
       }
       catch (Exception e)
       {
           return source;
       }
   }

How to make a div 100% height of the browser window

You can use the following CSS to make a div 100% of the height of the browser window:

display: block;
position: relative;
bottom: 0;
height: 100%;

"RuntimeError: Make sure the Graphviz executables are on your system's path" after installing Graphviz 2.38

You should install the graphviz package in your system (not just the python package). On Ubuntu you should try:

sudo apt-get install graphviz

How to disable <br> tags inside <div> by css?

<p style="color:black">Shop our collection of beautiful women's <br> <span> wedding ring in classic &amp; modern design.</span></p>

Remove <br> effect using CSS.

<style> p br{ display:none; } </style>

How to read a file into vector in C++?

#include <iostream>
#include <fstream>
#include <vector>
using namespace std;

int main()
{
fstream dataFile;
string name , word , new_word;
vector<string> test;
char fileName[80];
cout<<"Please enter the file name : ";
cin >> fileName;
dataFile.open(fileName);
if(dataFile.fail())
{
     cout<<"File can not open.\n";
     return 0;
}
cout<<"File opened.\n";
cout<<"Please enter the word : ";
cin>>word;
cout<<"Please enter the new word : ";
cin >> new_word;
while (!dataFile.fail() && !dataFile.eof())
{
      dataFile >> name;
      test.push_back(name);
}
dataFile.close();

}

How to return a struct from a function in C++?

You can now (C++14) return a locally-defined (i.e. defined inside the function) as follows:

auto f()
{
    struct S
    {
      int a;
      double b;
    } s;
    s.a = 42;
    s.b = 42.0;
    return s;
}

auto x = f();
a = x.a;
b = x.b;

Styling of Select2 dropdown select boxes

Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....

.select2-dropdown.select2-dropdown--below{
    width: 148px !important;
}

.select2-container--default .select2-selection--single{
    padding:6px;
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
}

Location Services not working in iOS 8

A little helper for all of you that have more than one Info.plist file...

find . -name Info.plist | xargs -I {} /usr/libexec/PlistBuddy -c 'Add NSLocationWhenInUseUsageDescription string' {} 

It will add the needed tag to all of the Info.plist files in the current directory (and subfolders).

Another is:

find . -name Info.plist | xargs -I {} /usr/libexec/PlistBuddy -c 'Set NSLocationWhenInUseUsageDescription $YOURDESCRIPTION' {} 

It will add your description to all files.

How to make a variable accessible outside a function?

Your variable declarations and their scope are correct. The problem you are facing is that the first AJAX request may take a little bit time to finish. Therefore, the second URL will be filled with the value of sID before the its content has been set. You have to remember that AJAX request are normally asynchronous, i.e. the code execution goes on while the data is being fetched in the background.

You have to nest the requests:

$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   obj = name;   // sID is only now available!   sID = obj.id;   console.log(sID); }); 


Clean up your code!

  • Put the second request into a function
  • and let it accept sID as a parameter, so you don't have to declare it globally anymore! (Global variables are almost always evil!)
  • Remove sID and obj variables - name.id is sufficient unless you really need the other variables outside the function.


$.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.1/summoner/by-name/"+input+"?api_key=API_KEY_HERE"  , function(name){   // We don't need sID or obj here - name.id is sufficient   console.log(name.id);    doSecondRequest(name.id); });  /// TODO Choose a better name function doSecondRequest(sID) {   $.getJSON("https://prod.api.pvp.net/api/lol/eune/v1.2/stats/by-summoner/" + sID + "/summary?api_key=API_KEY_HERE", function(stats){         console.log(stats);   }); } 

Hapy New Year :)

FromBody string parameter is giving null

Finally got it working after 1 hour struggle.

This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .

For a new WebApi 2 application example:

Postman (looks exactly, like below):

POST    http://localhost:61402/api/values   [Send]
Body
     (*) raw             JSON (application/json) v
         "{  \"key1\": \"value1\" }"

The port 61402 or url /api/values above, may be different for you.

ValuesController.cs

using Newtonsoft.Json;
// ..

// POST api/values
[HttpPost]
public object Post([FromBody]string jsonString)
{
    // add reference to Newtonsoft.Json
    //  using Newtonsoft.Json;

    // jsonString to myJsonObj
    var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);

    // value1 is myJsonObj[key1]
    var valueOfkey1 = myJsonObj["key1"];

    return myJsonObj;
}

All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.

Selenium WebDriver.get(url) does not open the URL

I have resolved this issue.

If your jar files are older than the latest version and the browser has updated to latest version, then download:

Sorting an ArrayList of objects using a custom sorting order

I did it by the following way. number and name are two arraylist. I have to sort name .If any change happen to name arralist order then the number arraylist also change its order.

public void sortval(){

        String tempname="",tempnum="";

         if (name.size()>1) // check if the number of orders is larger than 1
            {
                for (int x=0; x<name.size(); x++) // bubble sort outer loop
                {
                    for (int i=0; i < name.size()-x-1; i++) {
                        if (name.get(i).compareTo(name.get(i+1)) > 0)
                        {

                            tempname = name.get(i);

                            tempnum=number.get(i);


                           name.set(i,name.get(i+1) );
                           name.set(i+1, tempname);

                            number.set(i,number.get(i+1) );
                            number.set(i+1, tempnum);


                        }
                    }
                }
            }



}

Getting number of elements in an iterator in Python

No, any method will require you to resolve every result. You can do

iter_length = len(list(iterable))

but running that on an infinite iterator will of course never return. It also will consume the iterator and it will need to be reset if you want to use the contents.

Telling us what real problem you're trying to solve might help us find you a better way to accomplish your actual goal.

Edit: Using list() will read the whole iterable into memory at once, which may be undesirable. Another way is to do

sum(1 for _ in iterable)

as another person posted. That will avoid keeping it in memory.

You have not concluded your merge (MERGE_HEAD exists)

If you are sure that you already resolved all merge conflicts:

rm -rf .git/MERGE*

And the error will disappear.

Splitting a list into N parts of approximately equal length

say you want to split into 5 parts:

p1, p2, p3, p4, p5 = np.split(df, 5)

JAVA_HOME directory in Linux

If $JAVA_HOME is defined in your environment...

$ echo $JAVA_HOME
$ # I am not lucky...

You can guess it from the classes that are loaded.

$ java -showversion -verbose 2>&1 | head -1
[Opened /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/jre/lib/rt.jar]

This method ensures you find the correct jdk/jre used in case there are multiple installations.

Or using strace:

$ strace -e open java -showversion 2>&1 | grep -m1 /jre/
open("/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/jre/bin/../lib/amd64/jli/tls/x86_64/libpthread.so.0", O_RDONLY) = -1 ENOENT (No such file or directory)

How to combine two vectors into a data frame

Alt simplification of https://stackoverflow.com/users/1969435/gx1sptdtda above:

cond <-c(1,2,3)
rating <-c(100,200,300)
df <- data.frame(cond, rating)
df
  cond rating
1    1    100
2    2    200
3    3    300

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How to make a owl carousel with arrows instead of next previous

If you using latest Owl Carousel 2 version. You can replace the Navigation text by fontawesome icon. Code is below.

$('.your-class').owlCarousel({
        loop: true,
        items: 1, // Select Item Number
        autoplay:true,
        dots: false,
        nav: true,
        navText: ["<i class='fa fa-long-arrow-left'></i>","<i class='fa fa-long-arrow-right'></i>"],

    });

Using union and count(*) together in SQL query

Is your goal...

  1. To count all the instances of "Bob Jones" in both tables (for example)
  2. To count all the instances of "Bob Jones" in Results in one row and all the instances of "Bob Jones" in Archive_Results in a separate row?

Assuming it's #1 you'd want something like...

SELECT name, COUNT(*) FROM
(SELECT name FROM Results UNION ALL SELECT name FROM Archive_Results)
GROUP BY name
ORDER BY name

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

How do I print bytes as hexadecimal?

Yet another answer, in case the byte array is defined as char[], uppercase and separated by spaces.

void debugArray(const unsigned char* data, size_t len) {
    std::ios_base::fmtflags f( std::cout.flags() );
    for (size_t i = 0; i < len; ++i)
        std::cout << std::uppercase << std::hex << std::setfill('0') << std::setw(2) << (((int)data[i]) & 0xFF) << " ";
    std::cout << std::endl;
    std::cout.flags( f );
}

Example:

unsigned char test[]={0x01, 0x02, 0x03, 0x04, 0x05, 0x06};
debugArray(test, sizeof(test));

Output:

01 02 03 04 05 06

Java - How to access an ArrayList of another class?

Put them in an arrayList in your first class like:

import java.util.ArrayList;
    public class numbers {

    private int number1 = 50;
    private int number2 = 100;

    public ArrayList<int> getNumberList() {
        ArrayList<int> numbersList= new ArrayList<int>();
        numbersList.add(number1);
        numberList.add(number2);
        ....
        return numberList;
    }
}

Then, in your test class you can call numbers.getNumberList() to get your arrayList. In addition, you might want to create methods like addToList / removeFromList in your numbers class so you can handle it the way you need it.

You can also access a variable declared in one class from another simply like

numbers.numberList;

if you have it declared there as public.

But it isn't such a good practice in my opinion, since you probably need to modify this list in your code later. Note that you have to add your class to the import list.

If you can tell me what your app requirements are, i'll be able tell you more precise what i think it's best to do.

How do I convert seconds to hours, minutes and seconds?

You can divide seconds by 60 to get the minutes

import time
seconds = time.time()
minutes = seconds / 60
print(minutes)

When you divide it by 60 again, you will get the hours

invalid new-expression of abstract class type

Another possible cause for future Googlers

I had this issue because a method I was trying to implement required a std::unique_ptr<Queue>(myQueue) as a parameter, but the Queue class is abstract. I solved that by using a QueuePtr(myQueue) constructor like so:

using QueuePtr = std::unique_ptr<Queue>;

and used that in the parameter list instead. This fixes it because the initializer tries to create a copy of Queue when you make a std::unique_ptr of its type, which can't happen.

Saving binary data as file using JavaScript from a browser

Use FileSaver.js. It supports Chrome, Edge, Firefox, and IE 10+ (and probably IE < 10 with a few "polyfills" - see Note 4). FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it:
     https://github.com/eligrey/FileSaver.js

Minified version is really small at < 2.5KB, gzipped < 1.2KB.

Usage:

/* TODO: replace the blob content with your byte[] */
var blob = new Blob([yourBinaryDataAsAnArrayOrAsAString], {type: "application/octet-stream"});
var fileName = "myFileName.myExtension";
saveAs(blob, fileName);

You might need Blob.js in some browsers (see Note 3). Blob.js implements the W3C Blob interface in browsers that do not natively support it. It is a cross-browser implementation:
     https://github.com/eligrey/Blob.js

Consider StreamSaver.js if you have files larger than blob's size limitations.

Complete example:

_x000D_
_x000D_
/* Two options_x000D_
 * 1. Get FileSaver.js from here_x000D_
 *     https://github.com/eligrey/FileSaver.js/blob/master/FileSaver.min.js -->_x000D_
 *     <script src="FileSaver.min.js" />_x000D_
 *_x000D_
 * Or_x000D_
 *_x000D_
 * 2. If you want to support only modern browsers like Chrome, Edge, Firefox, etc., _x000D_
 *    then a simple implementation of saveAs function can be:_x000D_
 */_x000D_
function saveAs(blob, fileName) {_x000D_
    var url = window.URL.createObjectURL(blob);_x000D_
_x000D_
    var anchorElem = document.createElement("a");_x000D_
    anchorElem.style = "display: none";_x000D_
    anchorElem.href = url;_x000D_
    anchorElem.download = fileName;_x000D_
_x000D_
    document.body.appendChild(anchorElem);_x000D_
    anchorElem.click();_x000D_
_x000D_
    document.body.removeChild(anchorElem);_x000D_
_x000D_
    // On Edge, revokeObjectURL should be called only after_x000D_
    // a.click() has completed, atleast on EdgeHTML 15.15048_x000D_
    setTimeout(function() {_x000D_
        window.URL.revokeObjectURL(url);_x000D_
    }, 1000);_x000D_
}_x000D_
_x000D_
(function() {_x000D_
    // convert base64 string to byte array_x000D_
    var byteCharacters = atob("R0lGODlhkwBYAPcAAAAAAAABGRMAAxUAFQAAJwAANAgwJSUAACQfDzIoFSMoLQIAQAAcQwAEYAAHfAARYwEQfhkPfxwXfQA9aigTezchdABBckAaAFwpAUIZflAre3pGHFpWVFBIf1ZbYWNcXGdnYnl3dAQXhwAXowkgigIllgIxnhkjhxktkRo4mwYzrC0Tgi4tiSQzpwBIkBJIsyxCmylQtDVivglSxBZu0SlYwS9vzDp94EcUg0wziWY0iFROlElcqkxrtW5OjWlKo31kmXp9hG9xrkty0ziG2jqQ42qek3CPqn6Qvk6I2FOZ41qn7mWNz2qZzGaV1nGOzHWY1Gqp3Wy93XOkx3W1x3i33G6z73nD+ZZIHL14KLB4N4FyWOsECesJFu0VCewUGvALCvACEfEcDfAcEusKJuoINuwYIuoXN+4jFPEjCvAgEPM3CfI5GfAxKuoRR+oaYustTus2cPRLE/NFJ/RMO/dfJ/VXNPVkNvFPTu5KcfdmQ/VuVvl5SPd4V/Nub4hVj49ol5RxoqZfl6x0mKp5q8Z+pu5NhuxXiu1YlvBdk/BZpu5pmvBsjfBilvR/jvF3lO5nq+1yre98ufBoqvBrtfB6p/B+uPF2yJiEc9aQMsSKQOibUvqKSPmEWPyfVfiQaOqkSfaqTfyhXvqwU+u7dfykZvqkdv+/bfy1fpGvvbiFnL+fjLGJqqekuYmTx4SqzJ2+2Yy36rGawrSwzpjG3YjB6ojG9YrU/5XI853U75bV/J3l/6PB6aDU76TZ+LHH6LHX7rDd+7Lh3KPl/bTo/bry/MGJm82VqsmkjtSptfWMj/KLsfu0je6vsNW1x/GIxPKXx/KX1ea8w/Wnx/Oo1/a3yPW42/S45fvFiv3IlP/anvzLp/fGu/3Xo/zZt//knP7iqP7qt//xpf/0uMTE3MPd1NXI3MXL5crS6cfe99fV6cXp/cj5/tbq+9j5/vbQy+bY5/bH6vbJ8vfV6ffY+f7px/3n2f/4yP742OPm8ef9//zp5vjn/f775/7+/gAAACwAAAAAkwBYAAAI/wD9CRxIsKDBgwgTKlzIsKHDhxAjSpxIsaLFixgzatzIsaPHjxD7YQrSyp09TCFSrQrxCqTLlzD9bUAAAMADfVkYwCIFoErMn0AvnlpAxR82A+tGWWgnLoCvoFCjOsxEopzRAUYwBFCQgEAvqWDDFgTVQJhRAVI2TUj3LUAusXDB4jsQxZ8WAMNCrW37NK7foN4u1HThD0sBWpoANPnL+GG/OV2gSUT24Yi/eltAcPAAooO+xqAVbkPT5VDo0zGzfemyqLE3a6hhmurSpRLjcGDI0ItdsROXSAn5dCGzTOC+d8j3gbzX5ky8g+BoTzq4706XL1/KzONdEBWXL3AS3v/5YubavU9fuKg/44jfQmbK4hdn+Jj2/ILRv0wv+MnLdezpweEed/i0YcYXkCQkB3h+tPEfgF3AsdtBzLSxGm1ftCHJQqhc54Y8B9UzxheJ8NfFgWakSF6EA57WTDN9kPdFJS+2ONAaKq6Whx88enFgeAYx892FJ66GyEHvvGggeMs0M01B9ajRRYkD1WMgF60JpAx5ZEgGWjZ44MHFdSkeSBsceIAoED5gqFgGbAMxQx4XlxjESRdcnFENcmmcGBlBfuDh4Ikq0kYGHoxUKSWVApmCnRsFCddlaEPSVuaFED7pDz5F5nGQJ9cJWFA/d1hSUCfYlSFQfdgRaqal6UH/epmUjRDUx3VHEtTPHp5SOuYyn5x4xiMv3jEmlgKNI+w1B/WTxhdnwLnQY2ZwEY1AeqgHRzN0/PiiMmh8x8Vu9YjRxX4CjYcgdwhhE6qNn8DBrD/5AXnQeF3ct1Ap1/VakB3YbThQgXEIVG4X1w7UyXUFs2tnvwq5+0XDBy38RZYMKQuejf7Yw4YZXVCjEHwFyQmyyA4TBPAXhiiUDcMJzfaFvwXdgWYbz/jTjxjgTTiQN2qYQca8DxV44KQpC7SyIi7DjJCcExeET7YAplcGNQvC8RxB3qS6XUTacHEgF7mmvHTTUT+Nnb06Ozi2emOWYeEZRAvUdXZfR/SJ2AdS/8zuymUf9HLaFGLnt3DkPTIQqTLSXRDQ2W0tETbYHSgru3eyjLbfJa9dpYEIG6QHdo4T5LHQdUfUjduas9vhxglJzLaJhKtGOEHdhKrm4gB3YapFdlznHLvhiB1tQtqEmpDFFL9umkH3hNGzQTF+8YZjzGi6uBgg58yuHH0nFM67CIH/xfP+OH9Q9LAXRHn3Du1NhuQCgY80dyZ/4caee58xocYSOgg+uOe7gWzDcwaRWMsOQocVLQI5bOBCggzSDzx8wQsTFEg4RnQ8h1nnVdchA8rucZ02+Iwg4xOaly4DOu8tbg4HogRC6uGfVx3oege5FbQ0VQ8Yts9hnxiUpf9qtapntYF+AxFFqE54qwPlYR772Mc2xpAiLqSOIPiwIG3OJC0ooQFAOVrNFbnTj/jEJ3U4MgPK/oUdmumMDUWCm6u6wDGDbMOMylhINli3IjO4MGkLqcMX7rc4B1nRIPboXdVUdLmNvExFGAMkQxZGHAHmYYXQ4xGPogGO1QBHkn/ZhhfIsDuL3IMLbjghKDECj3O40pWrjIk6XvkZj9hDCEKggAh26QAR9IAJsfzILXkpghj0RSPOYAEJdikCEjjTmczURTA3cgxmQlMEJbBFRlixAms+85vL3KUVpomRQOwSnMtUwTos8g4WnBOd8BTBCNxBzooA4p3oFAENKLL/Dx/g85neRCcEblDPifjzm/+UJz0jkgx35tMBSWDFCZqZTxWwo6AQYQVFwzkFh17zChG550YBKoJx9iMHIwVoCY6J0YVUk6K7TII/UEpSJRQNpSkNZy1WRdN8lgAXLWXIOyYKUIv2o5sklWlD7EHUfIrApsbxKDixqc2gJqQfOBipA4qwqRVMdQgNaWdOw2kD00kVodm0akL+MNJdfuYdbRWBUhVy1LGmc6ECEWs8S0AMtR4kGfjcJREEAliEPnUh9uipU1nqD8COVQQqwKtfBWIPXSJUBcEQCFsNO06F3BOe4ZzrQDQKWhHMYLIFEURKRVCDz5w0rlVFiEbtCtla/xLks/B0wBImAo98iJSZIrDBRTPSjqECd5c7hUgzElpSyjb1msNF0j+nCtJRaeCxIoiuQ2YhhF4el5cquIg9kJAD735Xt47RwWqzS9iEhjch/qTtaQ0C18fO1yHvQAFzmflTiwBiohv97n0bstzV3pcQCR0sQlQxXZLGliDVjGdzwxrfADvgBULo60WSEQHm8uAJE8EHUqfaWX8clKSMHViDAfoC2xJksxWVbEKSMWKSOgGvhOCBjlO8kPgi1AEqAMbifqDjsjLkpVNVZ15rvMwWI4SttBXBLQR41muWWCFQnuoLhquOCoNXxggRa1yVuo9Z6PK4okVklZdpZH8YY//MYWZykhFS4Io2JMsIjQE97cED814TstpFkgSY29lk4DTAMZ1xTncJVX+oF60aNgiMS8vVg4h0qiJ4MEJ8jNAX0FPMpR2wQaRRZUYLZBArDueVCXJdn0rzMgmttEHwYddr8riy603zQfBM0uE6o5u0dcCqB/IOyxq2zeasNWTBvNx4OtkfSL4mmE9d6yZPm8EVdfFBZovpRm/qzBJ+tq7WvEvtclvCw540QvepsxOH09u6UqxTdd3V1UZ2IY7FdAy0/drSrtQg7ibpsJsd6oLoNZ+vdsY7d9nmUT/XqcP2RyGYy+NxL9oB1TX4isVZkHxredq4zec8CXJuhI5guCH/L3dCLu3vYtD3rCpfCKoXPQJFl7bh/TC2YendbuwOg9WPZXd9ba2QgNtZ0ohWQaQTYo81L5PdzZI3QBse4XyS4NV/bfAusQ7X0ioVxrvUdEHsIeepQn0gdQ6nqBOCagmLneRah3rTH6sCbeuq7LvMeNUxPU69hn0hBAft0w0ycxEAORYI2YcrWJoBuq8zIdLQeps9PtWG73rRUh6I0aHZ3wqrAKiArzYJ0FsQbjjAASWIRTtkywIH3Hfo+RQ3ksjd5pCDU9gyx/zPN+V0EZiAGM3o5YVXP5Bk1OAgbxa8M3EfEXNUgJltnnk8bWB3i+dztzprfGkzTmfMDzftH8fH/w9igHWBBF8EuzBI8pUvAu43JNnLL7G6EWp5Na8X9GQXvAjKf5DAF3Ug0fZxCPFaIrB7BOF/8fR2COFYMFV3q7IDtFV/Y1dqniYQ3KBs/GcQhXV72OcPtpdn1eeBzBRo/tB1ysd8C+EMELhwIqBg/rAPUjd1IZhXMBdcaKdsCjgQbWdYx7R50KRn28ZM71UQ+6B9+gdvFMRp16RklOV01qYQARhOWLd3AoWEBfFoJCVuPrhM+6aB52SDllZt+pQQswAE3jVVpPeAUZaBBGF0pkUQJuhsCgF714R4mkdbTDhavRROoGcQUThVJQBmrLADZ4hpQzgQ87duCUGH4fRgIuOmfyXAhgLBctDkgHfob+UHf00Wgv1WWpDFC+qADuZwaNiVhwCYarvEY1gFZwURg9fUhV4YV0vnD+bkiS+ADurACoW4dQoBfk71XcFmA9NWD6mWTozVD+oVYBAge9SmfyIgAwbhDINmWEhIeZh2XNckgQVBicrHfrvkBFgmhsW0UC+FaMxIg8qGTZ3FD0r4bgfBVKKnbzM4EP1UjN64Sz1AgmOHU854eoUYTg4gjIqGirx0eoGFTVbYjN0IUMs4bc1yXfFoWIZHA/ngEGRnjxImVwwxWxFpWCPgclfVagtpeC9AfKIPwY3eGAM94JCehZGGFQOzuIj8uJDLhHrgKFRlh2k8xxCz8HwBFU4FaQOzwJIMQQ5mCFzXaHg28AsRUWbA9pNA2UtQ8HgNAQ8QuV6HdxHvkALudFwpAAMtEJMWMQgsAAPAyJVgxU47AANdCVwlAJaSuJEsAGDMBJYGiBH94Ap6uZdEiRGysJd7OY8S8Q6AqZe8kBHOUJiCiVqM2ZiO+ZgxERAAOw==");_x000D_
    var byteNumbers = new Array(byteCharacters.length);_x000D_
    for (var i = 0; i < byteCharacters.length; i++) {_x000D_
        byteNumbers[i] = byteCharacters.charCodeAt(i);_x000D_
    }_x000D_
    var byteArray = new Uint8Array(byteNumbers);_x000D_
    _x000D_
    // now that we have the byte array, construct the blob from it_x000D_
    var blob1 = new Blob([byteArray], {type: "application/octet-stream"});_x000D_
_x000D_
    var fileName1 = "cool.gif";_x000D_
    saveAs(blob1, fileName1);_x000D_
_x000D_
    // saving text file_x000D_
    var blob2 = new Blob(["cool"], {type: "text/plain"});_x000D_
    var fileName2 = "cool.txt";_x000D_
    saveAs(blob2, fileName2);_x000D_
})();
_x000D_
_x000D_
_x000D_


Tested on Chrome, Edge, Firefox, and IE 11 (use FileSaver.js for supporting IE 11).
You can also save from a canvas element. See https://github.com/eligrey/FileSaver.js#saving-a-canvas.

Demos: https://eligrey.com/demos/FileSaver.js/

Blog post by author of FileSaver.js: http://eligrey.com/blog/post/saving-generated-files-on-the-client-side

Note 1: Browser support: https://github.com/eligrey/FileSaver.js#supported-browsers

Note 2: Failed to execute 'atob' on 'Window'

Note 3: Polyfill for browsers not supporting Blob: https://github.com/eligrey/Blob.js
                See http://caniuse.com/#search=blob

Note 4: IE < 10 support (I've not tested this part):
                https://github.com/eligrey/FileSaver.js#ie--10
                https://github.com/eligrey/FileSaver.js/issues/56#issuecomment-30917476

Downloadify is a Flash-based polyfill for supporting IE6-9: https://github.com/dcneiner/downloadify (I don't recommend Flash-based solutions in general, though.)
Demo using Downloadify and FileSaver.js for supporting IE6-9 also: http://sheetjs.com/demos/table.html

Note 5: Creating a BLOB from a Base64 string in JavaScript

Note 6: FileSaver.js examples: https://github.com/eligrey/FileSaver.js#examples

How can I add shadow to the widget in flutter?

Use Material with shadowColor inside Container like this:

Container(
  decoration: BoxDecoration(
      borderRadius: BorderRadius.only(
          bottomLeft: Radius.circular(10),
          bottomRight: Radius.circular(10)),
      boxShadow: [
        BoxShadow(
            color: Color(0xffA22447).withOpacity(.05),
            offset: Offset(0, 0),
            blurRadius: 20,
            spreadRadius: 3)
      ]),
  child: Material(
    borderRadius: BorderRadius.only(
        bottomLeft: Radius.circular(10),
        bottomRight: Radius.circular(10)),
    elevation: 5,
    shadowColor: Color(0xffA22447).withOpacity(.05),
    color: Color(0xFFF7F7F7),
    child: SizedBox(
      height: MediaQuery.of(context).size.height / 3,
    ),
  ),
)

How to read a Parquet file into Pandas DataFrame?

pandas 0.21 introduces new functions for Parquet:

pd.read_parquet('example_pa.parquet', engine='pyarrow')

or

pd.read_parquet('example_fp.parquet', engine='fastparquet')

The above link explains:

These engines are very similar and should read/write nearly identical parquet format files. These libraries differ by having different underlying dependencies (fastparquet by using numba, while pyarrow uses a c-library).

Get to UIViewController from UIView?

To get the controller of a given view, one can use UIFirstResponder chain.

customView.target(forAction: Selector("viewDidLoad"), withSender: nil)

List<Object> and List<?>

Why cant I do this:

List<Object> object = new List<Object>();

You can't do this because List is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List include ArrayList, LinkedList etc.

Here is how one would create an instance of ArrayList:

List<Object> object = new ArrayList<Object>();

I have a method that returns a List<?>, how would I turn that into a List<Object>

Show us the relevant code and I'll update the answer.

How to identify all stored procedures referring a particular table

Try This

   SELECT DISTINCT so.name
    FROM syscomments sc
    INNER JOIN sysobjects so ON sc.id=so.id
    WHERE sc.TEXT LIKE '%your table name%'

Export data from Chrome developer tool

In more modern versions of Chrome you can just drag a .har file into the network tab of Chrome Dev Tools to load it.

How to efficiently calculate a running standard deviation?

Perhaps not what you were asking, but ... If you use a numpy array, it will do the work for you, efficiently:

from numpy import array

nums = array(((0.01, 0.01, 0.02, 0.04, 0.03),
              (0.00, 0.02, 0.02, 0.03, 0.02),
              (0.01, 0.02, 0.02, 0.03, 0.02),
              (0.01, 0.00, 0.01, 0.05, 0.03)))

print nums.std(axis=1)
# [ 0.0116619   0.00979796  0.00632456  0.01788854]

print nums.mean(axis=1)
# [ 0.022  0.018  0.02   0.02 ]

By the way, there's some interesting discussion in this blog post and comments on one-pass methods for computing means and variances:

How to parse XML in Bash?

You can do that very easily using only bash. You only have to add this function:

rdom () { local IFS=\> ; read -d \< E C ;}

Now you can use rdom like read but for html documents. When called rdom will assign the element to variable E and the content to var C.

For example, to do what you wanted to do:

while rdom; do
    if [[ $E = title ]]; then
        echo $C
        exit
    fi
done < xhtmlfile.xhtml > titleOfXHTMLPage.txt

How to make link not change color after visited?

For application on all the anchor tags, use

CSS

a:visited{
    color:blue;
}

For application on only some of the anchor tags, use

CSS

.linkcolor a:visited{
    color:blue;
}

HTML

<span class="linkcolor"><a href="http://stackoverflow.com/" target="_blank">Go to Home</a></span>

An invalid XML character (Unicode: 0xc) was found

Whenever invalid xml character comes xml, it gives such error. When u open it in notepad++ it look like VT, SOH,FF like these are invalid xml chars. I m using xml version 1.0 and i validate text data before entering it in database by pattern

Pattern p = Pattern.compile("[^\u0009\u000A\u000D\u0020-\uD7FF\uE000-\uFFFD\u10000-\u10FFF]+"); 
retunContent = p.matcher(retunContent).replaceAll("");

It will ensure that no invalid special char will enter in xml

Is there any sed like utility for cmd.exe?

There is a helper batch file for Windows called repl.bat which has much of the ability of SED but doesn't require any additional download or installation. It is a hybrid batch file that uses Jscript to implement the features and so is swift, and doesn't suffer from the usual poison characters of batch processing and handles blank lines with ease.

Download repl from - https://www.dropbox.com/s/qidqwztmetbvklt/repl.bat

The author is @dbenham from stack overflow and dostips.com

Another helper batch file called findrepl.bat gives the Windows user much of the capabilty of GREP and is also based on Jscript and is likewise a hybrid batch file. It shares the benefits of repl.bat

Download findrepl from - https://www.dropbox.com/s/rfdldmcb6vwi9xc/findrepl.bat

The author is @aacini from stack overflow and dostips.com

Cannot add or update a child row: a foreign key constraint fails

That error occurs when you want to add a foreign key with values that don't exist in the primary key of the parent table. You must be sure that the new foreign key UserID in table2 has values that exist in the table1 primary key, sometimes by default it is null or equal to 0.

You could first update all the fields of the foreign key in table2 with a value that exists in the primary key of table1.

update table2 set UserID = 1 where UserID is null

If you want to add different UserIDs you must modify each row with the values you want.

How to speed up insertion performance in PostgreSQL

If you happend to insert colums with UUIDs (which is not exactly your case) and to add to @Dennis answer (I can't comment yet), be advise than using gen_random_uuid() (requires PG 9.4 and pgcrypto module) is (a lot) faster than uuid_generate_v4()

=# explain analyze select uuid_generate_v4(),* from generate_series(1,10000);
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=11.674..10304.959 rows=10000 loops=1)
 Planning time: 0.157 ms
 Execution time: 13353.098 ms
(3 filas)

vs


=# explain analyze select gen_random_uuid(),* from generate_series(1,10000);
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=252.274..418.137 rows=10000 loops=1)
 Planning time: 0.064 ms
 Execution time: 503.818 ms
(3 filas)

Also, it's the suggested official way to do it

Note

If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.

This droped insert time from ~2 hours to ~10 minutes for 3.7M of rows.

How to convert a const char * to std::string

What you want is this constructor: std::string ( const string& str, size_t pos, size_t n = npos ), passing pos as 0. Your const char* c-style string will get implicitly cast to const string for the first parameter.

const char *c_style = "012abd";
std::string cpp_style = new std::string(c_style, 0, 10);

How to append strings using sprintf?

I write a function support dynamic variable string append, like PHP str append: str . str . ... etc.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>

int str_append(char **json, const char *format, ...)
{
    char *str = NULL;
    char *old_json = NULL, *new_json = NULL;

    va_list arg_ptr;
    va_start(arg_ptr, format);
    vasprintf(&str, format, arg_ptr);

    // save old json
    asprintf(&old_json, "%s", (*json == NULL ? "" : *json));

    // calloc new json memory
    new_json = (char *)calloc(strlen(old_json) + strlen(str) + 1, sizeof(char));

    strcat(new_json, old_json);
    strcat(new_json, str);

    if (*json) free(*json);
    *json = new_json;

    free(old_json);
    free(str);

    return 0;
}

int main(int argc, char *argv[])
{
    char *json = NULL;

    /*
    str_append(&json, "name: %d, %d, %d", 1, 2, 3);
    str_append(&json, "sex: %s", "male");
    str_append(&json, "end");
    str_append(&json, "");
    str_append(&json, "{\"ret\":true}");
    */

    int i;
    for (i = 0; i < 100; i++) {
        str_append(&json, "id-%d", i);
    }

    printf("%s\n", json);

    if (json) free(json);

    return 0;
}

How can I run a PHP script in the background after a form is submitted?

The simpler way to run a PHP script in background is

php script.php >/dev/null &

The script will run in background and the page will also reach the action page faster.

vagrant primary box defined but commands still run against all boxes

The primary flag seems to only work for vagrant ssh for me.

In the past I have used the following method to hack around the issue.

# stage box intended for configuration closely matching production if ARGV[1] == 'stage'     config.vm.define "stage" do |stage|         box_setup stage, \         "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml"     end end 

Get records of current month

This query should work for you:

SELECT *
FROM table
WHERE MONTH(columnName) = MONTH(CURRENT_DATE())
AND YEAR(columnName) = YEAR(CURRENT_DATE())

How to Compare two strings using a if in a stored procedure in sql server 2008?

You can also try this for match string.

DECLARE @temp1 VARCHAR(1000)
    SET @temp1 = '<li>Error in connecting server.</li>'
DECLARE @temp2 VARCHAR(1000)
    SET @temp2 = '<li>Error in connecting server. connection timeout.</li>'

IF @temp1 like '%Error in connecting server.%' OR @temp1 like '%Error in connecting server. connection timeout.%'
  SELECT 'yes'
ELSE
  SELECT 'no'

How to get image height and width using java?

So unfortunately, after trying all the answers from above, I did not get them to work after tireless times of trying. So I decided to do the real hack myself and I go this to work for me. I trust it would work perfectly for you too.

I am using this simple method to get the width of an image generated by the app and yet to be upload later for verification :

Pls. take note : you would have to enable permissions in manifest for access storage.

/I made it static and put in my Global class so I can reference or access it from just one source and if there is any modification, it would all have to be done at just one place. Just maintaining a DRY concept in java. (anyway) :)/

public static int getImageWidthOrHeight(String imgFilePath) {

            Log.d("img path : "+imgFilePath);

            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(imgFilePath, o);

            int width_tmp = o.outWidth, height_tmp = o.outHeight;

            Log.d("Image width : ", Integer.toString(width_tmp) );

            //you can decide to rather return height_tmp to get the height.

            return width_tmp;

}

Swift Beta performance: sorting arrays

Swift Array performance revisited:

I wrote my own benchmark comparing Swift with C/Objective-C. My benchmark calculates prime numbers. It uses the array of previous prime numbers to look for prime factors in each new candidate, so it is quite fast. However, it does TONS of array reading, and less writing to arrays.

I originally did this benchmark against Swift 1.2. I decided to update the project and run it against Swift 2.0.

The project lets you select between using normal swift arrays and using Swift unsafe memory buffers using array semantics.

For C/Objective-C, you can either opt to use NSArrays, or C malloc'ed arrays.

The test results seem to be pretty similar with fastest, smallest code optimization ([-0s]) or fastest, aggressive ([-0fast]) optimization.

Swift 2.0 performance is still horrible with code optimization turned off, whereas C/Objective-C performance is only moderately slower.

The bottom line is that C malloc'd array-based calculations are the fastest, by a modest margin

Swift with unsafe buffers takes around 1.19X - 1.20X longer than C malloc'd arrays when using fastest, smallest code optimization. the difference seems slightly less with fast, aggressive optimization (Swift takes more like 1.18x to 1.16x longer than C.

If you use regular Swift arrays, the difference with C is slightly greater. (Swift takes ~1.22 to 1.23 longer.)

Regular Swift arrays are DRAMATICALLY faster than they were in Swift 1.2/Xcode 6. Their performance is so close to Swift unsafe buffer based arrays that using unsafe memory buffers does not really seem worth the trouble any more, which is big.

BTW, Objective-C NSArray performance stinks. If you're going to use the native container objects in both languages, Swift is DRAMATICALLY faster.

You can check out my project on github at SwiftPerformanceBenchmark

It has a simple UI that makes collecting stats pretty easy.

It's interesting that sorting seems to be slightly faster in Swift than in C now, but that this prime number algorithm is still faster in Swift.

Looking for simple Java in-memory cache

If you're needing something simple, would this fit the bill?

Map<K, V> myCache = Collections.synchronizedMap(new WeakHashMap<K, V>());

It wont save to disk, but you said you wanted simple...

Links:

(As Adam commented, synchronising a map has a performance hit. Not saying the idea doesn't have hairs on it, but would suffice as a quick and dirty solution.)

select into in mysql

In MySQL, It should be like this

INSERT INTO this_table_archive (col1, col2, ..., coln)
SELECT col1, col2, ..., coln
FROM this_table
WHERE entry_date < '2011-01-01 00:00:00';

MySQL Documentation

Merge DLL into EXE?

I answered a similar question for VB.NET. It shouldn't however be too hard to convert. You embedd the DLL's into your Ressource folder and on the first usage, the AppDomain.CurrentDomain.AssemblyResolve event gets fired.

If you want to reference it during development, just add a normal DLL reference to your project.

Embedd a DLL into a project

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

postgresql COUNT(DISTINCT ...) very slow

If your count(distinct(x)) is significantly slower than count(x) then you can speed up this query by maintaining x value counts in different table, for example table_name_x_counts (x integer not null, x_count int not null), using triggers. But your write performance will suffer and if you update multiple x values in single transaction then you'd need to do this in some explicit order to avoid possible deadlock.

Taking inputs with BufferedReader in Java

The problem id because of inp.read(); method. Its return single character at a time and because you are storing it into int type of array so that is just storing ascii value of that.

What you can do simply

for(int i=0;i<T;i++) {
    String s= inp.readLine();
    String[] intValues = inp.readLine().split(" ");
    int[] m= new int[2];
    m[0]=Integer.parseInt(intValues[0]);
    m[1]=Integer.parseInt(intValues[1]);

    // Checking whether I am taking the inputs correctly
    System.out.println(s);
    System.out.println(m[0]);
    System.out.println(m[1]);
}

Python get current time in right timezone

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

from datetime import datetime
naive_dt = datetime.now()

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

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

naive_utc_dt = datetime.utcnow()

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

from datetime import datetime, timezone

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

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

import pytz

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

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

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

The error message says what You should do.

// TEXTVIEW
if(tv.getParent() != null) {
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

jQuery Call to WebService returns "No Transport" error

None of the proposed answers completely worked for me. My use case is slightly different (doing an ajax get to an S3 .json file in IE9). Setting jQuery.support.cors = true; got rid of the No Transport error but I was still getting Permission denied errors.

What did work for me was to use the jQuery-ajaxTransport-XDomainRequest to force IE9 to use XDomainRequest. Using this did not require setting jQuery.support.cors = true;

If my interface must return Task what is the best way to have a no-operation implementation?

If you are using generics, all answer will give us compile error. You can use return default(T);. Sample below to explain further.

public async Task<T> GetItemAsync<T>(string id)
            {
                try
                {
                    var response = await this._container.ReadItemAsync<T>(id, new PartitionKey(id));
                    return response.Resource;
                }
                catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {

                    return default(T);
                }

            }

VBA for clear value in specific range of cell and protected cell from being wash away formula

Try this

Sheets("your sheetname").range("A5:X50").Value = ""

You can also use

ActiveSheet.range

Select all elements with a "data-xxx" attribute without using jQuery

Try it ? here

    <!DOCTYPE html>
    <html>
        <head></head>
        <body>
            <p data-foo="0"></p>
            <h6 data-foo="1"></h6>
            <script>
                var a = document.querySelectorAll('[data-foo]');

                for (var i in a) if (a.hasOwnProperty(i)) {
                    alert(a[i].getAttribute('data-foo'));
                }
            </script>
        </body>
    </html>

How to create image slideshow in html?

  1. Set var step=1 as global variable by putting it above the function call
  2. put semicolons

It will look like this

<head>
<script type="text/javascript">
var image1 = new Image()
image1.src = "images/pentagg.jpg"
var image2 = new Image()
image2.src = "images/promo.jpg"
</script>
</head>
<body>
<p><img src="images/pentagg.jpg" width="500" height="300" name="slide" /></p>
<script type="text/javascript">
        var step=1;
        function slideit()
        {
            document.images.slide.src = eval("image"+step+".src");
            if(step<2)
                step++;
            else
                step=1;
            setTimeout("slideit()",2500);
        }
        slideit();
</script>
</body>

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

Java Date - Insert into database

You should be using java.sql.Timestamp instead of java.util.Date. Also using a PreparedStatement will save you worrying about the formatting.

What is the result of % in Python?

% Modulo operator can be also used for printing strings (Just like in C) as defined on Google https://developers.google.com/edu/python/strings.

      # % operator
  text = "%d little pigs come out or I'll %s and %s and %s" % (3, 'huff', 'puff', 'blow down')

This seems to bit off topic but It will certainly help someone.

mySQL convert varchar to date

As gratitude to the timely help I got from here - a minor update to above.

$query = "UPDATE `db`.`table` SET `fieldname`=  str_to_date(  fieldname, '%d/%m/%Y')";

Recursive query in SQL Server

Sample of the Recursive Level:

enter image description here

DECLARE @VALUE_CODE AS VARCHAR(5);

--SET @VALUE_CODE = 'A' -- Specify a level

WITH ViewValue AS
(
    SELECT ValueCode
    , ValueDesc
    , PrecedingValueCode
    FROM ValuesTable
    WHERE PrecedingValueCode IS NULL
    UNION ALL
    SELECT A.ValueCode
    , A.ValueDesc
    , A.PrecedingValueCode 
    FROM ValuesTable A
    INNER JOIN ViewValue V ON
        V.ValueCode = A.PrecedingValueCode
)

SELECT ValueCode, ValueDesc, PrecedingValueCode

FROM ViewValue

--WHERE PrecedingValueCode  = @VALUE_CODE -- Specific level

--WHERE PrecedingValueCode  IS NULL -- Root

Vertical Text Direction

To display text in vertical (Bottom-top) we can simply use:

writing-mode: vertical-lr; 

transform: rotate(180deg);

_x000D_
_x000D_
#myDiv{_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
#mySpan{_x000D_
writing-mode: vertical-lr; _x000D_
transform: rotate(180deg);_x000D_
}
_x000D_
<div id="myDiv"> _x000D_
_x000D_
<span id="mySpan"> Here We gooooo !!! </span>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Note we can add this to ensure Browser Compatibility:

-webkit-transform: rotate(180deg);   
-moz-transform: rotate(180deg);
-ms-transform: rotate(180deg);
-o-transform: rotate(180deg);
transform: rotate(180deg);

we can also read more about writing-mode property here on Mozilla docs.

Determine the path of the executing BASH script

For the relative path (i.e. the direct equivalent of Windows' %~dp0):

MY_PATH="`dirname \"$0\"`"
echo "$MY_PATH"

For the absolute, normalized path:

MY_PATH="`dirname \"$0\"`"              # relative
MY_PATH="`( cd \"$MY_PATH\" && pwd )`"  # absolutized and normalized
if [ -z "$MY_PATH" ] ; then
  # error; for some reason, the path is not accessible
  # to the script (e.g. permissions re-evaled after suid)
  exit 1  # fail
fi
echo "$MY_PATH"

Creating a blocking Queue<T> in .NET?

You can use the BlockingCollection and ConcurrentQueue in the System.Collections.Concurrent Namespace

 public class ProducerConsumerQueue<T> : BlockingCollection<T>
{
    /// <summary>
    /// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
    /// </summary>
    public ProducerConsumerQueue()  
        : base(new ConcurrentQueue<T>())
    {
    }

  /// <summary>
  /// Initializes a new instance of the ProducerConsumerQueue, Use Add and TryAdd for Enqueue and TryEnqueue and Take and TryTake for Dequeue and TryDequeue functionality
  /// </summary>
  /// <param name="maxSize"></param>
    public ProducerConsumerQueue(int maxSize)
        : base(new ConcurrentQueue<T>(), maxSize)
    {
    }



}

jquery $(window).width() and $(window).height() return different values when viewport has not been resized

I think what you're seeing is the hiding and showing of scrollbars. Here's a quick demo showing the width change.

As an aside: do you need to poll constantly? You might be able to optimize your code to run on the resize event, like this:

$(window).resize(function() {
  //update stuff
});

How do I add the contents of an iterable to a set?

For the benefit of anyone who might believe e.g. that doing aset.add() in a loop would have performance competitive with doing aset.update(), here's an example of how you can test your beliefs quickly before going public:

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 294 usec per loop

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 950 usec per loop

>\python27\python -mtimeit -s"it=xrange(10000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 458 usec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a.update(it)"
1000 loops, best of 3: 598 usec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "for i in it:a.add(i)"
1000 loops, best of 3: 1.89 msec per loop

>\python27\python -mtimeit -s"it=xrange(20000);a=set(xrange(100))" "a |= set(it)"
1000 loops, best of 3: 891 usec per loop

Looks like the cost per item of the loop approach is over THREE times that of the update approach.

Using |= set() costs about 1.5x what update does but half of what adding each individual item in a loop does.

How to reduce the image size without losing quality in PHP

You can resize and then use imagejpeg()

Don't pass 100 as the quality for imagejpeg() - anything over 90 is generally overkill and just gets you a bigger JPEG. For a thumbnail, try 75 and work downwards until the quality/size tradeoff is acceptable.

imagejpeg($tn, $save, 75);

Remove all line breaks from a long string of text

The problem with rstrip is that it does not work in all cases (as I myself have seen few). Instead you can use - text= text.replace("\n"," ") this will remove all new line \n with a space.

Thanks in advance guys for your upvotes.

How do I parse command line arguments in Java?

If you are already using Spring Boot, argument parsing comes out of the box.

If you want to run something after startup, implement the ApplicationRunner interface:

@SpringBootApplication
public class Application implements ApplicationRunner {

  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }

  @Override
  public void run(ApplicationArguments args) {
    args.containsOption("my-flag-option"); // test if --my-flag-option was set
    args.getOptionValues("my-option");     // returns values of --my-option=value1 --my-option=value2 
    args.getOptionNames();                 // returns a list of all available options
    // do something with your args
  }
}

Your run method will be invoked after the context has started up successfully.

If you need access to the arguments before you fire up your application context, you can just simply parse the application arguments manually:

@SpringBootApplication
public class Application implements ApplicationRunner {

  public static void main(String[] args) {
    ApplicationArguments arguments = new DefaultApplicationArguments(args);
    // do whatever you like with your arguments
    // see above ...
    SpringApplication.run(Application.class, args);
  }

}

And finally, if you need access to your arguments in a bean, just inject the ApplicationArguments:

@Component
public class MyBean {

   @Autowired
   private ApplicationArguments arguments;

   // ...
}

SQL Server format decimal places with commas

Thankfully(?), in SQL Server 2012+, you can now use FORMAT() to achieve this:

FORMAT(@s,'#,0.0000')


In prior versions, at the risk of looking real ugly

[Query]:

declare @s decimal(18,10);
set @s = 1234.1234567;
select replace(convert(varchar,cast(floor(@s) as money),1),'.00',
    '.'+right(cast(@s * 10000 +10000.5 as int),4))

In the first part, we use MONEY->VARCHAR to produce the commas, but FLOOR() is used to ensure the decimals go to .00. This is easily identifiable and replaced with the 4 digits after the decimal place using a mixture of shifting (*10000) and CAST as INT (truncation) to derive the digits.

[Results]:

|   COLUMN_0 |
--------------
| 1,234.1235 |

But unless you have to deliver business reports using SQL Server Management Studio or SQLCMD, this is NEVER the correct solution, even if it can be done. Any front-end or reporting environment has proper functions to handle display formatting.

How to change the font on the TextView?

Android uses the Roboto font, which is a really nice looking font, with several different weights (regular, light, thin, condensed) that look great on high density screens.

Check below link to check roboto fonts:

How to use Roboto in xml layout

Back to your question, if you want to change the font for all of the TextView/Button in your app, try adding below code into your styles.xml to use Roboto-light font:

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    ......
    <item name="android:buttonStyle">@style/MyButton</item>
    <item name="android:textViewStyle">@style/MyTextView</item>
</style>

<style name="MyButton" parent="@style/Widget.AppCompat.Button">
    <item name="android:textAllCaps">false</item>
    <item name="android:fontFamily">sans-serif-light</item>
</style>

<style name="MyTextView" parent="@style/TextAppearance.AppCompat">
    <item name="android:fontFamily">sans-serif-light</item>
</style>

And don't forget to use 'AppTheme' in your AndroidManifest.xml

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    ......
</application>

What is the difference between atan and atan2 in C++?

Consider a right angled triangle. We label the hypotenuse r, the horizontal side y and the vertical side x. The angle of interest α is the angle between x and r.

C++ atan2(y, x) will give us the value of angle α in radians. atan is used if we only know or are interested in y/x not y and x individually. So if p = y/x then to get α we'd use atan(p).

You cannot use atan2 to determine the quadrant, you can use atan2 only if you already know which quadrant your in! In particular positive x and y imply the first quadrant, positive y and negative x, the second and so on. atan or atan2 themselves simply return a positive or a negative number, nothing more.

How do I open a new fragment from another fragment?

Adding to @Narendra solution...

IMPORTANT: When working with fragments, navigations is closely related to host acivity so, you can't justo jump from fragment to fragment without implement that fragment class in host Activity.

Sample:

public class MyHostActivity extends AppCompatActivity implements MyFragmentOne.OnFragmentInteractionListener {

Also, check your host activity has the next override function:

@Override public void onFragmentInteraction(Uri uri) {} Hope this helps...

SQL: Return "true" if list of records exists?

DECLARE @values TABLE (ProductId int)
INSERT @values (1)
INSERT @values (10)
INSERT @values (100)

SELECT CASE WHEN (SELECT COUNT(*) FROM @values v) = 
                 (SELECT COUNT(*) FROM Products p WHERE p.ProductId IN
                       (SELECT v.ProductId FROM @values v))
            THEN CAST(1 AS bit)
            ELSE CAST(0 AS bit)
       END [AreAllFound]

Type or namespace name does not exist

FOR ANYONE WITH LINKED FILES: I had this problem and was using silverlight and the offending file that was throwing this error was a linked file.

The error from the compiler told me the error was happening in the project that the file lived in. It ended up that the error was NOT in that project, it was occurring in the project that contained the linked file. That project was missing a reference.

Is it a good idea to index datetime field in mysql?

Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.

How can I make a list of lists in R?

If you are trying to keep a list of lists (similar to python's list.append()) then this might work:

a <- list(1,2,3)
b <- list(4,5,6)
c <- append(list(a), list(b))

> c
[[1]]
[[1]][[1]]
[1] 1

[[1]][[2]]
[1] 2

[[1]][[3]]
[1] 3


[[2]]
[[2]][[1]]
[1] 4

[[2]][[2]]
[1] 5

[[2]][[3]]
[1] 6

Conditional HTML Attributes using Razor MVC3

Note you can do something like this(at least in MVC3):

<td align="left" @(isOddRow ? "class=TopBorder" : "style=border:0px") >

What I believed was razor adding quotes was actually the browser. As Rism pointed out when testing with MVC 4(I haven't tested with MVC 3 but I assume behavior hasn't changed), this actually produces class=TopBorder but browsers are able to parse this fine. The HTML parsers are somewhat forgiving on missing attribute quotes, but this can break if you have spaces or certain characters.

<td align="left" class="TopBorder" >

OR

<td align="left" style="border:0px" >

What goes wrong with providing your own quotes

If you try to use some of the usual C# conventions for nested quotes, you'll end up with more quotes than you bargained for because Razor is trying to safely escape them. For example:

<button type="button" @(true ? "style=\"border:0px\"" : string.Empty)>

This should evaluate to <button type="button" style="border:0px"> but Razor escapes all output from C# and thus produces:

style=&quot;border:0px&quot;

You will only see this if you view the response over the network. If you use an HTML inspector, often you are actually seeing the DOM, not the raw HTML. Browsers parse HTML into the DOM, and the after-parsing DOM representation already has some niceties applied. In this case the Browser sees there aren't quotes around the attribute value, adds them:

style="&quot;border:0px&quot;"

But in the DOM inspector HTML character codes display properly so you actually see:

style=""border:0px""

In Chrome, if you right-click and select Edit HTML, it switch back so you can see those nasty HTML character codes, making it clear you have real outer quotes, and HTML encoded inner quotes.

So the problem with trying to do the quoting yourself is Razor escapes these.

If you want complete control of quotes

Use Html.Raw to prevent quote escaping:

<td @Html.Raw( someBoolean ? "rel='tooltip' data-container='.drillDown a'" : "" )>

Renders as:

<td rel='tooltip' title='Drilldown' data-container='.drillDown a'>

The above is perfectly safe because I'm not outputting any HTML from a variable. The only variable involved is the ternary condition. However, beware that this last technique might expose you to certain security problems if building strings from user supplied data. E.g. if you built an attribute from data fields that originated from user supplied data, use of Html.Raw means that string could contain a premature ending of the attribute and tag, then begin a script tag that does something on behalf of the currently logged in user(possibly different than the logged in user). Maybe you have a page with a list of all users pictures and you are setting a tooltip to be the username of each person, and one users named himself '/><script>$.post('changepassword.php?password=123')</script> and now any other user who views this page has their password instantly changed to a password that the malicious user knows.

Open an image using URI in Android's default gallery image viewer

I use this it works for me

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent,
"Select Picture"), 1);

Forgot Oracle username and password, how to retrieve?

if you are on Windows

  1. Start the Oracle service if it is not started (most probably it starts automatically when Windows starts)
  2. Start CMD.exe
  3. in the cmd (black window) type: sqlplus / as sysdba

Now you are logged with SYS user and you can do anything you want (query DBA_USERS to find out your username, or change any user password). You can not see the old password, you can only change it.

How do I create a HTTP Client Request with a cookie?

This answer is deprecated, please see @ankitjaininfo's answer below for a more modern solution


Here's how I think you make a POST request with data and a cookie using just the node http library. This example is posting JSON, set your content-type and content-length accordingly if you post different data.

// NB:- node's http client API has changed since this was written
// this code is for 0.4.x
// for 0.6.5+ see http://nodejs.org/docs/v0.6.5/api/http.html#http.request

var http = require('http');

var data = JSON.stringify({ 'important': 'data' });
var cookie = 'something=anything'

var client = http.createClient(80, 'www.example.com');

var headers = {
    'Host': 'www.example.com',
    'Cookie': cookie,
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(data,'utf8')
};

var request = client.request('POST', '/', headers);

// listening to the response is optional, I suppose
request.on('response', function(response) {
  response.on('data', function(chunk) {
    // do what you do
  });
  response.on('end', function() {
    // do what you do
  });
});
// you'd also want to listen for errors in production

request.write(data);

request.end();

What you send in the Cookie value should really depend on what you received from the server. Wikipedia's write-up of this stuff is pretty good: http://en.wikipedia.org/wiki/HTTP_cookie#Cookie_attributes

Convert integer to binary in C#

class Program
{
    static void Main(string[] args)
    {
        var @decimal = 42;
        var binaryVal = ToBinary(@decimal, 2);

        var binary = "101010";
        var decimalVal = ToDecimal(binary, 2);

        Console.WriteLine("Binary value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of binary '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        @decimal = 6;
        binaryVal = ToBinary(@decimal, 3);

        binary = "20";
        decimalVal = ToDecimal(binary, 3);

        Console.WriteLine("Base3 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base3 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();


        @decimal = 47;
        binaryVal = ToBinary(@decimal, 4);

        binary = "233";
        decimalVal = ToDecimal(binary, 4);

        Console.WriteLine("Base4 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base4 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        @decimal = 99;
        binaryVal = ToBinary(@decimal, 5);

        binary = "344";
        decimalVal = ToDecimal(binary, 5);

        Console.WriteLine("Base5 value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of base5 '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();

        Console.WriteLine("And so forth.. excluding after base 10 (decimal) though :)");
        Console.WriteLine();


        @decimal = 16;
        binaryVal = ToBinary(@decimal, 11);

        binary = "b";
        decimalVal = ToDecimal(binary, 11);

        Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);
        Console.WriteLine();
        Console.WriteLine("Uh oh.. this aint right :( ... but let's cheat :P");
        Console.WriteLine();

        @decimal = 11;
        binaryVal = Convert.ToString(@decimal, 16);

        binary = "b";
        decimalVal = Convert.ToInt32(binary, 16);

        Console.WriteLine("Hexidecimal value of decimal {0} is '{1}'", @decimal, binaryVal);
        Console.WriteLine("Decimal value of Hexidecimal '{0}' is {1}", binary, decimalVal);

        Console.ReadLine();
    }


    static string ToBinary(decimal number, int @base)
    {
        var round = 0;
        var reverseBinary = string.Empty;

        while (number > 0)
        {
            var remainder = number % @base;
            reverseBinary += remainder;

            round = (int)(number / @base);
            number = round;
        }

        var binaryArray = reverseBinary.ToCharArray();
        Array.Reverse(binaryArray);

        var binary = new string(binaryArray);
        return binary;
    }

    static double ToDecimal(string binary, int @base)
    {
        var val = 0d;

        if (!binary.All(char.IsNumber))
            return 0d;

        for (int i = 0; i < binary.Length; i++)
        {
            var @char = Convert.ToDouble(binary[i].ToString());

            var pow = (binary.Length - 1) - i;
            val += Math.Pow(@base, pow) * @char;
        }

        return val;
    }
}

Learning sources:

Everything you need to know about binary

including algorithm to convert decimal to binary

Define global constants

All solutions seems to be complicated. I'm looking for the simplest solution for this case and I just want to use constants. Constants are simple. Is there anything which speaks against the following solution?

app.const.ts

'use strict';

export const dist = '../path/to/dist/';

app.service.ts

import * as AppConst from '../app.const'; 

@Injectable()
export class AppService {

    constructor (
    ) {
        console.log('dist path', AppConst.dist );
    }

}

How do I replace a character in a string in Java?

Just create a string that contains all of the data in question and then use String.replaceAll() like below.

String result = yourString.replaceAll("&", "&amp;");

Appending to an existing string

Can I ask why this is important?

I know that this is not a direct answer to your question, but the fact that you are trying to preserve the object ID of a string might indicate that you should look again at what you are trying to do.

You might find, for instance, that relying on the object ID of a string will lead to bugs that are quite hard to track down.

Use Font Awesome Icon in Placeholder

If you're using FontAwesome 4.7 this should be enough:

_x000D_
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<input type="text" placeholder="&#xF002; Search" style="font-family:Arial, FontAwesome" />
_x000D_
_x000D_
_x000D_

A list of hex codes can be found in the Font Awesome cheatsheet. However, in the lastest FontAwesome 5.0 this method does not work (even if you use the CSS approach combined with the updated font-family).

How to get public directory?

Use public_path()

For reference:

// Path to the project's root folder    
echo base_path();

// Path to the 'app' folder    
echo app_path();        

// Path to the 'public' folder    
echo public_path();

// Path to the 'storage' folder    
echo storage_path();

// Path to the 'storage/app' folder    
echo storage_path('app');

Writing html form data to a txt file without the use of a webserver

I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.

https://jsfiddle.net/cgeiser/m0j7Lwyt/1/

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
  var filename = window.document.myform.docname.value;
  var name =  window.document.myform.name.value;
  var text =  window.document.myform.text.value;
  var problem =  window.document.myform.problem.value;
  
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    "Your Name: " + encodeURIComponent(name) + "\n\n" +
    "Problem: " + encodeURIComponent(problem) + "\n\n" +
    encodeURIComponent(text)); 

  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
  <input type="text" id="docname" value="test.txt" />
  <input type="text" id="name" placeholder="Your Name" />
  <div style="display:unblock">
    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
    <input type="text" id="problem" />
  </div>
  <textarea rows=3 cols=50 id="text" />Please type in this box. 
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
  
  <input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
  
</form>
</body>
</html>

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

if(document.readyState === 'complete') {
    DoStuffFunction();
} else {
    if (window.addEventListener) {  
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload', DoStuffFunction);
    }
}

Xcopy Command excluding files and folders

It is same as above answers, but is simple in steps

c:\SRC\folder1

c:\SRC\folder2

c:\SRC\folder3

c:\SRC\folder4

to copy all above folders to c:\DST\ except folder1 and folder2.

Step1: create a file c:\list.txt with below content, one folder name per one line

folder1\

folder2\

Step2: Go to command pompt and run as below xcopy c:\SRC*.* c:\DST*.* /EXCLUDE:c:\list.txt

Generating a drop down list of timezones with PHP

I know this has an answer already but I saw an opportunity to improve upon one of the answers here. Toland H posted some very good code that does exactly what the question was asking for. Below is a shortened and expand version of Toland H's code:

  • The function places everything in option tags for you. Just echo out whats return between your select tags.
  • Major Improvement: The list is sorted first by continent and organized in option groups based on continents. Makes it very user friendly for visitors picking their timezone.

function generate_timezone_list() {
static $allRegions = array(
DateTimeZone::AFRICA,
DateTimeZone::AMERICA,
DateTimeZone::ANTARCTICA,
DateTimeZone::ASIA,
DateTimeZone::ATLANTIC,
DateTimeZone::AUSTRALIA,
DateTimeZone::EUROPE,
DateTimeZone::INDIAN,
DateTimeZone::PACIFIC
);
// Makes it easier to create option groups next
$list = array ('AFRICA','AMERICA','ANTARCTICA','ASIA','ATLANTIC','AUSTRALIA','EUROPE','INDIAN','PACIFIC');
// Make array holding the regions (continents), they are arrays w/ all their cities
$region = array();
foreach ($allRegions as $area){
array_push ($region,DateTimeZone::listIdentifiers( $area ));
}   
$count = count ($region); $i = 0; $holder = '';
// Go through each region one by one, sorting and formatting it's cities
while ($i < $count){
$chunck = $region[$i];
// Create the region (continents) option group
$holder .= '<optgroup label="---------- '.$list[$i].' ----------">';
$timezone_offsets = array();
foreach( $chunck as $timezone ){
$tz = new DateTimeZone($timezone);
$timezone_offsets[$timezone] = $tz->getOffset(new DateTime);
}
asort ($timezone_offsets);
$timezone_list = array();
foreach ($timezone_offsets as $timezone => $offset){
$offset_prefix = $offset < 0 ? '-' : '+';
$offset_formatted = gmdate( 'H:i', abs($offset) );
$pretty_offset = "UTC ${offset_prefix}${offset_formatted}";
$timezone_list[$timezone] = "(${pretty_offset}) $timezone";     
}
// All the formatting is done, finish and move on to next region
foreach ($timezone_list as $key => $val){
$holder .= '<option value="'.$key.'">'.$val.'</option>';
}
$holder .= '</optgroup>';
++$i;
}
return $holder;
}
echo "<select>".generate_timezone_list()."</select>";

Then all you need to do is echo out what is returned between your html select tags. You'll get a select list something like this:

----- AFRICA -----
(UTC +00:00) Africa/ city name
(UTC +01:00) Africa/ city name
(UTC +02:00) Africa/ city name
(UTC +02:00) Africa/ city name
----- AMERICA -----
(UTC -09:00) America/ city name
(UTC -07:00) America/ city name
(UTC +02:00) America/ city name
(UTC +05:00) America/ city name

And so on...

Check if URL has certain string with PHP

$url = 'http://' . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI'];


if (!strpos($url,'car')) {
    echo 'Car exists.';
} else {
    echo 'No cars.';
}

This seems to work.

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

I had the same issue but in this case microsoft-ace-oledb-12-0-provider was already installed on my machine and working fine for other application developed.

The difference between those application and the one with I had the problem was the Old Applications were running on "Local IIS" whereas the one with error was on "IIS Express(running from Visual Studio"). So what I did was-

  1. Right Click on Project Name.
  2. Go to Properties
  3. Go to Web Tab on the right.
  4. Under Servers select Local IIS and click on Create Virtual Directory button.
  5. Run the application again and it worked.

How do I compare two Integers?

I would go with x.equals(y) because that's consistent way to check equality for all classes.

As far as performance goes, equals is actually more expensive because it ends up calling intValue().

EDIT: You should avoid autoboxing in most cases. It can get really confusing, especially the author doesn't know what he was doing. You can try this code and you will be surprised by the result;

Integer a = 128;
Integer b = 128;

System.out.println(a==b);

horizontal line and right way to code it in html, css

I'd go for semantic markup, use an <hr/>.

Unless it's just a border what you want, then you can use a combination of padding, border and margin, to get the desired bound.

[ :Unexpected operator in shell programming

There is no mistake in your bash script. But you are executing it with sh which has a less extensive syntax ;)

So, run bash ./choose.sh instead :)

How do I get a decimal value when using the division operator in Python?

Make one or both of the terms a floating point number, like so:

4.0/100.0

Alternatively, turn on the feature that will be default in Python 3.0, 'true division', that does what you want. At the top of your module or script, do:

from __future__ import division

CSS image overlay with color and transparency

JSFiddle Demo

HTML:

<div class="image-holder">
    <img src="http://codemancers.com/img/who-we-are-bg.png" />
</div>

CSS:

.image-holder {
    display:inline-block;
    position: relative;
}
.image-holder:after {
    content:'';
    top: 0;
    left: 0;
    z-index: 10;
    width: 100%;
    height: 100%;
    display: block;
    position: absolute;
    background: blue;
    opacity: 0.1;
}
.image-holder:hover:after {
    opacity: 0;
}

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

I'm guessing this is what you want...

When the form is submitted, check if the value is empty and if so, send a value = empty.

If so, you could do the following with jQuery.

$('form').submit(function(){
    var input = $('#test').val();
    if(input == ''){
         $('#test').val('empty');
    }    
});

HTML

<form> 
    <input id="test" type="text" />
</form>

http://jsfiddle.net/jasongennaro/NS6Ca/

Click your cursor in the box and then hit enter to see the form submit the value.

How to get numbers after decimal point?

You may want to try this:

your_num = 5.55
n = len(str(int(your_num)))
float('0' + str(your_num)[n:])

It will return 0.55.

How to create circular ProgressBar in android?

You can try this Circle Progress library

enter image description here

enter image description here

NB: please always use same width and height for progress views

DonutProgress:

 <com.github.lzyzsd.circleprogress.DonutProgress
        android:id="@+id/donut_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

CircleProgress:

  <com.github.lzyzsd.circleprogress.CircleProgress
        android:id="@+id/circle_progress"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:circle_progress="20"/>

ArcProgress:

<com.github.lzyzsd.circleprogress.ArcProgress
        android:id="@+id/arc_progress"
        android:background="#214193"
        android:layout_marginLeft="50dp"
        android:layout_width="100dp"
        android:layout_height="100dp"
        custom:arc_progress="55"
        custom:arc_bottom_text="MEMORY"/>

How do you clone an Array of Objects in Javascript?

I was pretty frustrated by this problem. Apparently the problem arises when you send in a generic Array to the $.extend method. So, to fix it, I added a little check, and it works perfectly with generic arrays, jQuery arrays, and any objects.

jQuery.extend({
    deepclone: function(objThing) {
        // return jQuery.extend(true, {}, objThing);
        /// Fix for arrays, without this, arrays passed in are returned as OBJECTS! WTF?!?!
        if ( jQuery.isArray(objThing) ) {
            return jQuery.makeArray( jQuery.deepclone($(objThing)) );
        }
        return jQuery.extend(true, {}, objThing);
    },
});

Invoke using:

var arrNewArrayClone = jQuery.deepclone(arrOriginalArray);
// Or more simply/commonly
var arrNewArrayClone = $.deepclone(arrOriginalArray);

How to get C# Enum description from value?

To make this easier to use, I wrote a generic extension:

public static string ToDescription<TEnum>(this TEnum EnumValue) where TEnum : struct
{
    return Enumerations.GetEnumDescription((Enum)(object)((TEnum)EnumValue));
}

now I can write:

        MyEnum my = MyEnum.HereIsAnother;
        string description = my.ToDescription();
        System.Diagnostics.Debug.Print(description);

Note: replace "Enumerations" above with your class name

Adding iOS UITableView HeaderView (not section header)

In Swift:

override func viewDidLoad() {
    super.viewDidLoad()

    // We set the table view header.
    let cellTableViewHeader = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewHeaderCustomCellIdentifier) as! UITableViewCell
    cellTableViewHeader.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewHeaderCustomCellIdentifier]!)
    self.tableView.tableHeaderView = cellTableViewHeader

    // We set the table view footer, just know that it will also remove extra cells from tableview.
    let cellTableViewFooter = tableView.dequeueReusableCellWithIdentifier(TableViewController.tableViewFooterCustomCellIdentifier) as! UITableViewCell
    cellTableViewFooter.frame = CGRectMake(0, 0, self.tableView.bounds.width, self.heightCache[TableViewController.tableViewFooterCustomCellIdentifier]!)
    self.tableView.tableFooterView = cellTableViewFooter
}

How to sort a Ruby Hash by number value?

Since value is the last entry, you can do:

metrics.sort_by(&:last)

The Use of Multiple JFrames: Good or Bad Practice?

I think using multiple Jframes is not a good idea.

Instead we can use JPanels more than one or more JPanel in the same JFrame.

Also we can switch between this JPanels. So it gives us freedom to display more than on thing in the JFrame.

For each JPanel we can design different things and all this JPanel can be displayed on the single JFrameone at a time.

To switch between this JPanels use JMenuBar with JMenuItems for each JPanelor 'JButtonfor eachJPanel`.

More than one JFrame is not a good practice, but there is nothing wrong if we want more than one JFrame.

But its better to change one JFrame for our different needs rather than having multiple JFrames.

for each inside a for each - Java

So you really want:

for each tweet
    unless tweet is in db
        insert tweet

If so, just write it down in your programming language. Hint: The loop over the array is to be done before the insert, which is done depending on the outcome.

What you want to test is that all array elements are not equal to the current one. But your for loop does not do that.

How do I run a batch file from my Java Application?

Sometimes the thread execution process time is higher than JVM thread waiting process time, it use to happen when the process you're invoking takes some time to be processed, use the waitFor() command as follows:

try{    
    Process p = Runtime.getRuntime().exec("file location here, don't forget using / instead of \\ to make it interoperable");
    p.waitFor();

}catch( IOException ex ){
    //Validate the case the file can't be accesed (not enought permissions)

}catch( InterruptedException ex ){
    //Validate the case the process is being stopped by some external situation     

}

This way the JVM will stop until the process you're invoking is done before it continue with the thread execution stack.

C compiling - "undefined reference to"?

seems you need to link with the obj file that implements tolayer5()

Update: your function declaration doesn't match the implementation:

      void tolayer5(int AorB, struct msg msgReceived)
      void tolayer5(int, char data[])

So compiler would treat them as two different functions (you are using c++). and it cannot find the implementation for the one you called in main().

Icons missing in jQuery UI

I found icons were not displaying due to a difference in the casing (ie upper case vs lower case). The CSS file was using "FFFFFF" while the actual file was using "ffffff". Icons displayed for me once I changed the case to match.

Extract the last substring from a cell

Simpler would be: =TRIM(RIGHT(SUBSTITUTE(TRIM(A2)," ",REPT(" ",99)),99))

You can use A2 in place of TRIM(A2) if you are sure that your data doesn't contain any unwanted spaces.

Based on concept explained by Rick Rothstein: http://www.excelfox.com/forum/showthread.php/333-Get-Field-from-Delimited-Text-String

Sorry for being necroposter!

How to split a string of space separated numbers into integers?

Of course you can call split, but it will return strings, not integers. Do

>>> x, y = "42 0".split()
>>> [int(x), int(y)]
[42, 0]

or

[int(x) for x in "42 0".split()]

In-place type conversion of a NumPy array

You can change the array type without converting like this:

a.dtype = numpy.float32

but first you have to change all the integers to something that will be interpreted as the corresponding float. A very slow way to do this would be to use python's struct module like this:

def toi(i):
    return struct.unpack('i',struct.pack('f',float(i)))[0]

...applied to each member of your array.

But perhaps a faster way would be to utilize numpy's ctypeslib tools (which I am unfamiliar with)

- edit -

Since ctypeslib doesnt seem to work, then I would proceed with the conversion with the typical numpy.astype method, but proceed in block sizes that are within your memory limits:

a[0:10000] = a[0:10000].astype('float32').view('int32')

...then change the dtype when done.

Here is a function that accomplishes the task for any compatible dtypes (only works for dtypes with same-sized items) and handles arbitrarily-shaped arrays with user-control over block size:

import numpy

def astype_inplace(a, dtype, blocksize=10000):
    oldtype = a.dtype
    newtype = numpy.dtype(dtype)
    assert oldtype.itemsize is newtype.itemsize
    for idx in xrange(0, a.size, blocksize):
        a.flat[idx:idx + blocksize] = \
            a.flat[idx:idx + blocksize].astype(newtype).view(oldtype)
    a.dtype = newtype

a = numpy.random.randint(100,size=100).reshape((10,10))
print a
astype_inplace(a, 'float32')
print a

How to install a private NPM module without my own registry?

This was what I was looking for:

# Get the latest from GitHub, public repo:
$ npm install username/my-new-project --save-dev
# Bitbucket, private repo:
$ npm install git+https://token:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master

# … or from Bitbucket, public repo:
$ npm install git+ssh://[email protected]/username/my-new-project.git#master --save-dev
# Bitbucket, private repo:
$ npm install git+https://username:[email protected]/username/my-new-project.git#master
$ npm install git+ssh://[email protected]/username/my-new-project.git#master
# Or, if you published as npm package:
$ npm install my-new-project --save-dev

ReactJS lifecycle method inside a function Component

You can make use of create-react-class module. Official documentation

Of course you must first install it

npm install create-react-class

Here is a working example

import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')


let Clock = createReactClass({
    getInitialState:function(){
        return {date:new Date()}
    },

    render:function(){
        return (
            <h1>{this.state.date.toLocaleTimeString()}</h1>
        )
    },

    componentDidMount:function(){
        this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
    },

    componentWillUnmount:function(){
        clearInterval(this.timerId)
    }

})

ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
)

Language Books/Tutorials for popular languages

Head First Javascript is a good intro to JS for beginning programmers - it creatively explains basic programming concepts using JS syntax. The Head First series is based on researched techniques for helping you learn and remember new information. They have you do a lot of exercises and puzzles which might seem juvenile, but really help cement the knowledge in your brain.

One exercise I really liked was after they explained data types, they show a picture of a city street and say "label all the data types you can find in this picture." So the blinker on a car is a boolean, the sign on the store is a string, and the address is a number. That helped me get the idea of how to translate real information into a program.

Based only on this book, I'd say the Head First series is a great way to learn something the first time, but the story-like format they have would make them difficult to use as references.

Convert LocalDateTime to LocalDateTime in UTC

There is an even simpler way

LocalDateTime.now(Clock.systemUTC())

Search all the occurrences of a string in the entire project in Android Studio

Android Studio 3.3 seems to have changed the shortcut to search for all references (find in path) on macOS.

In order to do that you should use Ctrl + Shift + F now (instead of Command + Shift + F as wrote on the previous answers):

UPDATE

To replace in path just use Ctrl + Shift + R.

enter image description here

In Firebase, is there a way to get the number of children of a node without loading all the node data?

Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).

The 'trick' here is to use the node priority to as the vote count...

The data is:

vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote

,"vote": {
  ".read" : true
  ,".write" : true
  ,"$issue" : {
    "user" : {
      "$user" : {
        ".validate" : "!data.exists() && 
             newData.val()==data.parent().parent().child('count').getPriority()+1 &&
             newData.val()==newData.GetPriority()" 

user can only vote once && count must be one higher than current count && data value must be same as priority.

      }
    }
    ,"count" : {
      ".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
             newData.getPriority()==data.getPriority()+1 "
    }

count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.

  }
}

Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.

<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
  window.fb = new Firebase('https:...vote/iss1/');
  window.fb.child('count').once('value', function (dss) {
    votes = dss.getPriority();
    for (var i=1;i<10;i++) vote(dss,i+votes);
  } );

function vote(dss,count)
{
  var user='user/zz' + count; // replace with auth.id or whatever
  window.fb.child(user).setWithPriority(count,count);
  window.fb.child('count').setWithPriority(user,count);
}
</script>

The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)

The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).

Create a GUID in Java

Have a look at the UUID class bundled with Java 5 and later.

For example:

How to center a component in Material-UI and make it responsive?

Since you are going to use this in a login page. Here is a code I used in a Login page using Material-UI

<Grid
  container
  spacing={0}
  direction="column"
  alignItems="center"
  justify="center"
  style={{ minHeight: '100vh' }}
>

  <Grid item xs={3}>
    <LoginForm />
  </Grid>   

</Grid> 

this will make this login form at the center of the screen.

But still IE doesn't support the Material-UI Grid and you will see some misplaced content in IE.

Hope this will help you.

Remove element from JSON Object

To iterate through the keys of an object, use a for .. in loop:

for (var key in json_obj) {
    if (json_obj.hasOwnProperty(key)) {
        // do something with `key'
    }
}

To test all elements for empty children, you can use a recursive approach: iterate through all elements and recursively test their children too.

Removing a property of an object can be done by using the delete keyword:

var someObj = {
    "one": 123,
    "two": 345
};
var key = "one";
delete someObj[key];
console.log(someObj); // prints { "two": 345 }

Documentation:

Refresh DataGridView when updating data source

You are setting the datasource inside of the loop and sleeping 500 after each add. Why not just add to itemstates and then set your datasource AFTER you have added everything. If you want the thread sleep after that fine. The first block of code here is yours the second block I modified.

for (int i = 0; i < 10; i++) { 
    itemStates.Add(new ItemState { Id = i.ToString() });
    dataGridView1.DataSource = null;
    dataGridView1.DataSource = itemStates;
    System.Threading.Thread.Sleep(500);
}

Change your Code As follows: this is much faster.

for (int i = 0; i < 10; i++) { 
    itemStates.Add(new ItemState { Id = i.ToString() });

}
    dataGridView1.DataSource = typeof(List); 
    dataGridView1.DataSource = itemStates;
    System.Threading.Thread.Sleep(500);

Error In PHP5 ..Unable to load dynamic library

(For Ubuntu users)

I had the same problem, but none of the answers above solved that. Here is how I solved the problem.

Open your php.ini file (mine was in /etc/php/7.3/cli/php.ini).

You may have something like this:

extension=pdo_mysql

Or maybe:

extension=/here/is/the/path/to/your/file/pdo_mysql.so

Add the following line before extension=pdo_mysql

extension=pdo

So, you will have:

extension=pdo
extension=pdo_mysql

It seems that the problem is (at least in my case) that we need to load pdo extension first to load the pdo_mysql extension.

Hope that helps!

How to change a css class style through Javascript?

use the className property:

document.getElementById('your_element_s_id').className = 'cssClass';

Pip install Matplotlib error with virtualenv

As I have struggled with this issue twice (even after fresh kubuntu 15.04 install) and installing freetype did not solve anything, I investigated further.

The solution:
From github issue:

This bug only occurs if pkg-config is not installed;
a simple
sudo apt-get install pkg-config
will shore up the include paths for now.

After this installation proceeds smoothly.

libclntsh.so.11.1: cannot open shared object file.

The libs are located in /u01/app/oracle/product/11.2.0/xe/lib (For Oracle XE) or similar.

You should add this path to /etc/ld.so.conf or if this file shows only an include location, as in a separate file in the /etc/ld.so.conf.d directory

I have oracle.conf in /etc/ld.so.conf.d, just one file with the path. Nothing else.

Of course don't forget to run ldconfig as a last step.

Node JS Promise.all and forEach

Here's a simple example using reduce. It runs serially, maintains insertion order, and does not require Bluebird.

/**
 * 
 * @param items An array of items.
 * @param fn A function that accepts an item from the array and returns a promise.
 * @returns {Promise}
 */
function forEachPromise(items, fn) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item);
        });
    }, Promise.resolve());
}

And use it like this:

var items = ['a', 'b', 'c'];

function logItem(item) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            resolve();
        })
    });
}

forEachPromise(items, logItem).then(() => {
    console.log('done');
});

We have found it useful to send an optional context into loop. The context is optional and shared by all iterations.

function forEachPromise(items, fn, context) {
    return items.reduce(function (promise, item) {
        return promise.then(function () {
            return fn(item, context);
        });
    }, Promise.resolve());
}

Your promise function would look like this:

function logItem(item, context) {
    return new Promise((resolve, reject) => {
        process.nextTick(() => {
            console.log(item);
            context.itemCount++;
            resolve();
        })
    });
}

Ansible: Set variable to file content

You can use the slurp module to fetch a file from the remote host: (Thanks to @mlissner for suggesting it)

vars:
  amazon_linux_ami: "ami-fb8e9292"
  user_data_file: "base-ami-userdata.sh"
tasks:
- name: Load data
  slurp:
    src: "{{ user_data_file }}"
  register: slurped_user_data
- name: Decode data and store as fact # You can skip this if you want to use the right hand side directly...
  set_fact:
    user_data: "{{ slurped_user_data.content | b64decode }}"