Programs & Examples On #Geotiff

GeoTIFF is a public domain metadata standard which allows georeferencing information to be embedded within a TIFF file.

R - Markdown avoiding package loading messages

My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.

{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)

#data wrangling
library(dplyr)

#text processing
library(stringi)

Create Hyperlink in Slack

Recently it became possible (but with an odd workaround).

To do this you must first create text with the desired hyperlink in an editor that supports rich text formatting. This can be an advanced text editor, web browser, email client, web-development IDE, etc.). Then copypaste the text from the editor or rendered HTML from browser (or other). E.g. in the example below I copypasted the head of this StackOverflow page. As you may see, the hyperlink have been copied correctly and is clickable in the message (checked on Mac Desktop, browser, and iOS apps).

Message in Slack

On Mac

I was able to compose the desired link in the native Pages app as shown below. When you are done, copypaste your text into Slack app. This is the probably easiest way on Mac OS.

Link creation in Pages

On Windows

I have a strong suspicion that MS Word will do the same trick, but unfortunately I don't have an installed instance to check.

Universal

Create text in an online editor, such as Google Documents. Use Insert -> Link, modify the text and web URL, then copypaste into Slack.

enter image description here

How to hide reference counts in VS2013?

Workaround....

In VS 2015 Professional (and probably other versions). Go to Tools / Options / Environment / Fonts and Colours. In the "Show Settings For" drop-down, select "CodeLens" Choose the smallest font you can find e.g. Calibri 6. Change the foreground colour to your editor foreground colour (say "White") Click OK.

How to avoid "RuntimeError: dictionary changed size during iteration" error?

Python 3 does not allow deletion while iterating (using for loop above) dictionary. There are various alternatives to do; one simple way is the to change following line

for i in x.keys():

With

for i in list(x)

Cookie blocked/not saved in IFRAME in Internet Explorer

I got it to work, but the solution is a bit complex, so bear with me.

What's happening

As it is, Internet Explorer gives lower level of trust to IFRAME pages (IE calls this "third-party" content). If the page inside the IFRAME doesn't have a Privacy Policy, its cookies are blocked (which is indicated by the eye icon in status bar, when you click on it, it shows you a list of blocked URLs).

the evil eye
(source: piskvor.org)

In this case, when cookies are blocked, session identifier is not sent, and the target script throws a 'session not found' error.

(I've tried setting the session identifier into the form and loading it from POST variables. This would have worked, but for political reasons I couldn't do that.)

It is possible to make the page inside the IFRAME more trusted: if the inner page sends a P3P header with a privacy policy that is acceptable to IE, the cookies will be accepted.

How to solve it

Create a p3p policy

A good starting point is the W3C tutorial. I've gone through it, downloaded the IBM Privacy Policy Editor and there I created a representation of the privacy policy and gave it a name to reference it by (here it was policy1).

NOTE: at this point, you actually need to find out if your site has a privacy policy, and if not, create it - whether it collects user data, what kind of data, what it does with it, who has access to it, etc. You need to find this information and think about it. Just slapping together a few tags will not cut it. This step cannot be done purely in software, and may be highly political (e.g. "should we sell our click statistics?").

(e.g. "the site is operated by ACME Ltd., it uses anonymous per-session identifiers for its operation, collects user data only if explicitly permitted and only for the following purposes, the data is stored only as long as necessary, only our company has access to it, etc. etc.").

(When editing with this tool, it's possible to view errors/omissions in the policy. Also very useful is the tab "HTML Policy": at the bottom, it has a "Policy Evaluation" - a quick check if the policy will be blocked by IE's default settings)

The Editor exports to a .p3p file, which is an XML representation of the above policy. Also, it can export a "compact version" of this policy.

Link to the policy

Then a Policy Reference file (http://example.com/w3c/p3p.xml) was needed (an index of privacy policies the site uses):

<META>
  <POLICY-REFERENCES>
    <POLICY-REF about="/w3c/example-com.p3p#policy1">
      <INCLUDE>/</INCLUDE>
      <COOKIE-INCLUDE/>
    </POLICY-REF>
  </POLICY-REFERENCES>
</META>

The <INCLUDE> shows all URIs that will use this policy (in my case, the whole site). The policy file I've exported from the Editor was uploaded to http://example.com/w3c/example-com.p3p

Send the compact header with responses

I've set the webserver at example.com to send the compact header with responses, like this:

HTTP/1.1 200 OK 
P3P: policyref="/w3c/p3p.xml", CP="IDC DSP COR IVAi IVDi OUR TST"
// ... other headers and content

policyref is a relative URI to the Policy Reference file (which in turn references the privacy policies), CP is the compact policy representation. Note that the combination of P3P headers in the example may not be applicable on your specific website; your P3P headers MUST truthfully represent your own privacy policy!

Profit!

In this configuration, the Evil Eye does not appear, the cookies are saved even in the IFRAME, and the application works.

Edit: What NOT to do, unless you like defending from lawsuits

Several people have suggested "just slap some tags into your P3P header, until the Evil Eye gives up".

The tags are not only a bunch of bits, they have real world meanings, and their use gives you real world responsibilities!

For example, pretending that you never collect user data might make the browser happy, but if you actually collect user data, the P3P is conflicting with reality. Plain and simple, you are purposefully lying to your users, and that might be criminal behavior in some countries. As in, "go to jail, do not collect $200".

A few examples (see p3pwriter for the full set of tags):

  • NOI : "Web Site does not collected identified data." (as soon as there's any customization, a login, or any data collection (***** Analytics, anyone?), you must acknowledge it in your P3P)
  • STP: Information is retained to meet the stated purpose. This requires information to be discarded at the earliest time possible. Sites MUST have a retention policy that establishes a destruction time table. The retention policy MUST be included in or linked from the site's human-readable privacy policy." (so if you send STP but don't have a retention policy, you may be committing fraud. How cool is that? Not at all.)

I'm not a lawyer, but I'm not willing to go to court to see if the P3P header is really legally binding or if you can promise your users anything without actually willing to honor your promises.

Open Facebook Page in Facebook App (if installed) on Android

Here's a solution that mixes the code by Jared Rummler and AndroidMechanic.

Note: fb://facewebmodal/f?href= redirects to a weird facebook page that doesn't have the like and other important buttons, which is why I try fb://page/. It works fine with the current Facebook version (126.0.0.21.77, June 1st 2017). The catch might be useless, I left it just in case.

public static String getFacebookPageURL(Context context)
{
    final String FACEBOOK_PAGE_ID = "123456789";
    final String FACEBOOK_URL = "MyFacebookPage";

    if(appInstalledOrNot(context, "com.facebook.katana"))
    {
        try
        {
            return "fb://page/" + FACEBOOK_PAGE_ID;
            // previous version, maybe relevant for old android APIs ?
            // return "fb://facewebmodal/f?href=" + FACEBOOK_URL;
        }
        catch(Exception e) {}
    }
    else
    {
        return FACEBOOK_URL;
    }

}

Here's the appInstalledOrNot function which I took (and modified) from Aerrow's answer to this post

private static boolean appInstalledOrNot(Context context, String uri)
{
    PackageManager pm = context.getPackageManager();
    try
    {
        pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
        return true;
    }
    catch(PackageManager.NameNotFoundException e)
    {
    }

    return false;
}

How to get the Facebook ID of a page:

  1. Go to your page
  2. Right-click and View Page Source
  3. Find in page: fb://page/?id=
  4. Here you go!

SystemError: Parent module '' not loaded, cannot perform relative import

I usually use this workaround:

try:
    from .mymodule import myclass
except Exception: #ImportError
    from mymodule import myclass

Which means your IDE should pick up the right code location and the python interpreter will manage to run your code.

How to change options of <select> with jQuery?

Old school of doing things by hand has always been good for me.

  1. Clean the select and leave the first option:

        $('#your_select_id').find('option').remove()
        .end().append('<option value="0">Selec...</option>')
        .val('whatever');
    
  2. If your data comes from a Json or whatever (just Concat the data):

        var JSONObject = JSON.parse(data);
        newOptionsSelect = '';
        for (var key in JSONObject) {
            if (JSONObject.hasOwnProperty(key)) {
                var newOptionsSelect = newOptionsSelect + '<option value="'+JSONObject[key]["value"]+'">'+JSONObject[key]["text"]+'</option>';
            }
        }
    
        $('#your_select_id').append( newOptionsSelect );
    
  3. My Json Objetc:

        [{"value":1,"text":"Text 1"},{"value":2,"text":"Text 2"},{"value":3,"text":"Text 3"}]
    

This solution is ideal for working with Ajax, and answers in Json from a database.

gem install: Failed to build gem native extension (can't find header files)

This post helped me. Thanks a lot.

On Linux (Ubuntu 12.10) I needed to run

sudo apt-get install ruby
sudo apt-get install rubygems
sudo apt-get install ruby-dev

before I could succesfully run

sudo gem install jekyll

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

the error i received was:

cockpit.socket: Failed to listen on sockets: Address already in use

the fix I discovered is:

  1. I had to disable selinux
  2. in /usr/lib/systemd/system/cockpit service i changed the line :

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws --selinux-type=etc_t
    

    to:

    #ExecStartPre=/usr/sbin/remotectl certificate --ensure --user=root --group=cockpit-ws 
    

so as you can see i took out the argument about selinux then i ran:

systemctl daemon-reload
systemctl start cockpit.service

then I browsed to:

I accepted the self-signed certificate and was able to login successfully to cockpit and use it normally.

this is all on a fedora25 machine. the 9090 port had already been added using firewall-cmd

How to run Ruby code from terminal?

You can run ruby commands in one line with the -e flag:

ruby -e "puts 'hi'"

Check the man page for more information.

How to check if a string contains text from an array of substrings in JavaScript?

Drawing from T.J. Crowder's solution, I created a prototype to deal with this problem:

Array.prototype.check = function (s) {
  return this.some((v) => {
    return s.indexOf(v) >= 0;
  });
};

FirstOrDefault returns NullReferenceException if no match is found

That is because FirstOrDefaultcan return null causing your following .Value to cause the exception. You need to change it to something like:

var myThing = things.FirstOrDefault(t => t.Id == idToFind);

if(myThing == null)
    return; // we failed to find what we wanted
var displayName = myThing.DisplayName;

Safely remove migration In Laravel

I accidentally created two times create_users_table. It overrided some classes and turned rollback into ErrorException.

What you need to do is find autoload_classmap.php in vendor/composer folder and look for the specific line of code such as

'CreateUsersTable' => $baseDir . '/app/database/migrations/2013_07_04_014051_create_users_table.php',

and edit path. Then your rollback should be fine.

nodejs npm global config missing on windows

It looks like the files npm uses to edit its config files are not created on a clean install, as npm has a default option for each one. This is why you can still get options with npm config get <option>: having those files only overrides the defaults, it doesn't create the options from scratch.

I had never touched my npm config stuff before today, even though I had had it for months now. None of the files were there yet, such as ~/.npmrc (on a Windows 8.1 machine with Git Bash), yet I could run npm config get <something> and, if it was a correct npm option, it returned a value. When I ran npm config set <option> <value>, the file ~/.npmrc seemed to be created automatically, with the option & its value as the only non-commented-out line.

As for deleting options, it looks like this just sets the value back to the default value, or does nothing if that option was never set or was unset & never reset. Additionally, if that option is the only explicitly set option, it looks like ~/.npmrc is deleted, too, and recreated if you set anything else later.

In your case (assuming it is still the same over a year later), it looks like you never set the proxy option in npm. Therefore, as npm's config help page says, it is set to whatever your http_proxy (case-insensitive) environment variable is. This means there is nothing to delete, unless you want to "delete" your HTTP proxy, although you could set the option or environment variable to something else and hope neither breaks your set-up somehow.

UIAlertController custom font, size, color

To change the color of one button like CANCEL to the red color you can use this style property called UIAlertActionStyle.destructive :

let prompt = UIAlertController.init(title: "Reset Password", message: "Enter Your E-mail :", preferredStyle: .alert)
        let okAction = UIAlertAction.init(title: "Submit", style: .default) { (action) in
              //your code
}

let cancelAction = UIAlertAction.init(title: "Cancel", style: UIAlertActionStyle.destructive) { (action) in
                //your code
        }
        prompt.addTextField(configurationHandler: nil)
        prompt.addAction(okAction)
        prompt.addAction(cancelAction)
        present(prompt, animated: true, completion: nil);

What does status=canceled for a resource mean in Chrome Developer Tools?

We had this problem having tag <button> in the form, that was supposed to send ajax request from js. But this request was canceled, due to browser, that sends form automatically on any click on button inside the form.

So if you realy want to use button instead of regular div or span on the page, and you want to send form throw js - you should setup a listener with preventDefault function.

e.g.

$('button').on('click', function(e){

    e.preventDefault();

    //do ajax
    $.ajax({

     ...
    });

})

How do you check what version of SQL Server for a database using TSQL?

If all you want is the major version for T-SQL reasons, the following gives you the year of the SQL Server version for 2000 or later.

SELECT left(ltrim(replace(@@Version,'Microsoft SQL Server','')),4)

This code gracefully handles the extra spaces and tabs for various versions of SQL Server.

Make javascript alert Yes/No Instead of Ok/Cancel

You cannot do that with the native confirm() as it is the browser’s method.

You have to create a plugin for a confirm box (or try one created by someone else). And they often look better, too.

Additional Tip: Change your English sentence to something like

Really, Delete this Thing?

Python glob multiple filetypes

A one-liner, Just for the hell of it..

folder = "C:\\multi_pattern_glob_one_liner"
files = [item for sublist in [glob.glob(folder + ext) for ext in ["/*.txt", "/*.bat"]] for item in sublist]

output:

['C:\\multi_pattern_glob_one_liner\\dummy_txt.txt', 'C:\\multi_pattern_glob_one_liner\\dummy_bat.bat']

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

In my case, My principal was kafka/[email protected] I got below lines in the terminal:

>>> KrbKdcReq send: #bytes read=190
>>> KdcAccessibility: remove kerberos.niroshan.com
>>> KDCRep: init() encoding tag is 126 req type is 13
>>>KRBError:
         cTime is Thu Oct 05 03:42:15 UTC 1995 812864535000
         sTime is Fri May 31 06:43:38 UTC 2019 1559285018000
         suSec is 111309
         error code is 7
         error Message is Server not found in Kerberos database
         cname is kafka/[email protected]
         sname is kafka/[email protected]
         msgType is 30

After hours of checking, I just found the below line has a wrong value in kafka_2.12-2.2.0/server.properties

listeners=SASL_PLAINTEXT://kafka.com:9092

Also I got two entries of kafka.niroshan.com and kafka.com for same IP address.

I changed it to as listeners=SASL_PLAINTEXT://kafka.niroshan.com:9092 Then it worked!

According to the below link, the principal should contain the Fully Qualified Domain Name (FQDN) of each host and it should be matched with the principal.

https://docs.oracle.com/cd/E19253-01/816-4557/planning-25/index.html

Execute a shell script in current shell with sudo permission

What you are trying to do is impossible; your current shell is running under your regular user ID (i.e. without root the access sudo would give you), and there is no way to grant it root access. What sudo does is create a new *sub*process that runs as root. The subprocess could be just a regular program (e.g. sudo cp ... runs the cp program in a root process) or it could be a root subshell, but it cannot be the current shell.

(It's actually even more impossible than that, because the sudo command itself is executed as a subprocess of the current shell -- meaning that in a sense it's already too late for it to do anything in the "current shell", because that's not where it executes.)

What is the C# equivalent of friend?

There isn't a 'friend' keyword in C# but one option for testing private methods is to use System.Reflection to get a handle to the method. This will allow you to invoke private methods.

Given a class with this definition:

public class Class1
{
    private int CallMe()
    {
        return 1;
    }
}

You can invoke it using this code:

Class1 c = new Class1();
Type class1Type = c.GetType();
MethodInfo callMeMethod = class1Type.GetMethod("CallMe", BindingFlags.Instance | BindingFlags.NonPublic);

int result = (int)callMeMethod.Invoke(c, null);

Console.WriteLine(result);

If you are using Visual Studio Team System then you can get VS to automatically generate a proxy class with private accessors in it by right clicking the method and selecting "Create Unit Tests..."

How to print a int64_t type in C

Coming from the embedded world, where even uclibc is not always available, and code like

uint64_t myval = 0xdeadfacedeadbeef; printf("%llx", myval);

is printing you crap or not working at all -- i always use a tiny helper, that allows me to dump properly uint64_t hex:

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

char* ullx(uint64_t val)
{
    static char buf[34] = { [0 ... 33] = 0 };
    char* out = &buf[33];
    uint64_t hval = val;
    unsigned int hbase = 16;

    do {
        *out = "0123456789abcdef"[hval % hbase];
        --out;
        hval /= hbase;
    } while(hval);

    *out-- = 'x', *out = '0';

    return out;
}

Request string without GET arguments

Why so complicated? =)

$baseurl = 'http://mysite.com';
$url_without_get = $baseurl.$_SERVER['PHP_SELF'];

this should really do it man ;)

c# foreach (property in object)... Is there a simple way of doing this?

I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.

   private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
    {
        List<string> returnValue = new List<string>();
        try
        {
            int index = userPrincipalName.IndexOf("@");
            string originatingServer = userPrincipalName.Remove(0, index + 1);
            string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
            DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
            var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
            objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
            SearchResultCollection properties = objSearcher.FindAll();

            ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
            foreach (string resProperty in resPropertyCollection)
            {
                returnValue.Add(resProperty);
            }
        }
        catch (Exception ex)
        {
            returnValue.Add(ex.Message);
            throw;
        }

        return returnValue;
    }

Current Subversion revision command

Otherwise for old version, if '--show-item' is not recognize, you can use the following command :

svn log -r HEAD | grep -o -E "^r[0-9]{1,}" | sed 's/r//g'

Hope it helps.

Objective-C: Reading a file line by line

The appropriate way to read text files in Cocoa/Objective-C is documented in Apple's String programming guide. The section for reading and writing files should be just what you're after. PS: What's a "line"? Two sections of a string separated by "\n"? Or "\r"? Or "\r\n"? Or maybe you're actually after paragraphs? The previously mentioned guide also includes a section on splitting a string into lines or paragraphs. (This section is called "Paragraphs and Line Breaks", and is linked to in the left-hand-side menu of the page I pointed to above. Unfortunately this site doesn't allow me to post more than one URL as I'm not a trustworthy user yet.)

To paraphrase Knuth: premature optimisation is the root of all evil. Don't simply assume that "reading the whole file into memory" is slow. Have you benchmarked it? Do you know that it actually reads the whole file into memory? Maybe it simply returns a proxy object and keeps reading behind the scenes as you consume the string? (Disclaimer: I have no idea if NSString actually does this. It conceivably could.) The point is: first go with the documented way of doing things. Then, if benchmarks show that this doesn't have the performance you desire, optimise.

Last Run Date on a Stored Procedure in SQL Server

This works fine on 2005 (if the plan is in the cache)

USE YourDb;

SELECT qt.[text]          AS [SP Name],
       qs.last_execution_time,
       qs.execution_count AS [Execution Count]
FROM   sys.dm_exec_query_stats AS qs
       CROSS APPLY sys.dm_exec_sql_text(qs.sql_handle) AS qt
WHERE  qt.dbid = DB_ID()
       AND objectid = OBJECT_ID('YourProc') 

SQL query, store result of SELECT in local variable

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)

INSERT INTO @result1
SELECT a, b, c
FROM table1

SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1

This should be fine for what you need.

php $_POST array empty upon form submission

I just spent hours to fix a similar issue. The problem in my case, was the the

max_input_vars = "1000"

by default, in the php.ini. I had a really huge form without uploads. php.ini is set to upload_max_filesize = "100M" and post_max_size = "108M" and it was surely not the issue in my case. PHP behavior is the same for max_input_vars when it exceeds 1000 variables in the form. It returns and empty _POST array. I wish I could have found that one hours, and hours ago.

In Go's http package, how do I get the query string on a POST request?

There are two ways of getting query params:

  1. Using reqeust.URL.Query()
  2. Using request.Form

In second case one has to be careful as body parameters will take precedence over query parameters. A full description about getting query params can be found here

https://golangbyexample.com/net-http-package-get-query-params-golang

Detect Browser Language in PHP

The problem with the selected answer above is that the user may have their first choice set as a language that's not in the case structure, but one of their other language choices are set. You should loop until you find a match.

This is a super simple solution that works better. Browsers return the languages in order of preference, so that simplifies the problem. While the language designator can be more than two characters (e.g. - "EN-US"), typically the first two are sufficient. In the following code example I'm looking for a match from a list of known languages my program is aware of.

$known_langs = array('en','fr','de','es');
$user_pref_langs = explode(',', $_SERVER['HTTP_ACCEPT_LANGUAGE']);

foreach($user_pref_langs as $idx => $lang) {
    $lang = substr($lang, 0, 2);
    if (in_array($lang, $known_langs)) {
        echo "Preferred language is $lang";
        break;
    }
}

I hope you find this a quick and simple solution that you can easily use in your code. I've been using this in production for quite a while.

How to enable copy paste from between host machine and virtual machine in vmware, virtual machine is ubuntu

If your VM already came with VMware Tools pre-installed, but this still isn't working for you--or if you install and still no luck--make sure you run Workstation or Player as Administrator. That fixed the issue for me.

What is the use of "assert"?

As summarized concisely on the C2 Wiki:

An assertion is a boolean expression at a specific point in a program which will be true unless there is a bug in the program.

You can use an assert statement to document your understanding of the code at a particular program point. For example, you can document assumptions or guarantees about inputs (preconditions), program state (invariants), or outputs (postconditions).

Should your assertion ever fail, this is an alert for you (or your successor) that your understanding of the program was wrong when you wrote it, and that it likely contains a bug.

For more information, John Regehr has a wonderful blog post on the Use of Assertions, which applies to the Python assert statement as well.

Jenkins pipeline how to change to another folder

You can use the dir step, example:

dir("folder") {
    sh "pwd"
}

The folder can be relative or absolute path.

How to insert array of data into mysql using php

if(is_array($EMailArr)){
    foreach($EMailArr as $key => $value){

    $R_ID = (int) $value['R_ID'];
    $email = mysql_real_escape_string( $value['email'] );
    $name = mysql_real_escape_string( $value['name'] );

    $sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) values ('$R_ID', '$email', '$name')";
    mysql_query($sql) or exit(mysql_error()); 
    }
}

A better example solution with PDO:

 $q = $sql->prepare("INSERT INTO `email_list` 
                     SET `R_ID` = ?, `EMAIL` = ?, `NAME` = ?");

 foreach($EMailArr as $value){
   $q ->execute( array( $value['R_ID'], $value['email'], $value['name'] ));
 }

Check if an excel cell exists on another worksheet in a column - and return the contents of a different column

You can use following formulas.

For Excel 2007 or later:

=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")

For Excel 2003:

=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))

Note, that

  • I'm using List!A:C in VLOOKUP and returns value from column ? 3
  • I'm using 4th argument for VLOOKUP equals to FALSE, in that case VLOOKUP will only find an exact match, and the values in the first column of List!A:C do not need to be sorted (opposite to case when you're using TRUE).

How to display a Yes/No dialog box on Android?

Thanks. I use the API Level 2 (Android 1.1) and instead of BUTTON_POSITIVE and BUTTON_NEGATIVE i have to use BUTTON1 and BUTTON2.

PHP function ssh2_connect is not working

Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

It's a ton more portable, easier to use and more feature packed too.

jQuery UI " $("#datepicker").datepicker is not a function"

I just had this issue, and moving the JS references and code towards the bottom of the page before the </body> tag fixed it for me.

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

If you're on 32-bit machine don't allow more than 3584 MB of RAM and it will run.

Xml serialization - Hide null values

You can create a function with the pattern ShouldSerialize{PropertyName} which tells the XmlSerializer if it should serialize the member or not.

For example, if your class property is called MyNullableInt you could have

public bool ShouldSerializeMyNullableInt() 
{
  return MyNullableInt.HasValue;
}

Here is a full sample

public class Person
{
  public string Name {get;set;}
  public int? Age {get;set;}
  public bool ShouldSerializeAge()
  {
    return Age.HasValue;
  }
}

Serialized with the following code

Person thePerson = new Person(){Name="Chris"};
XmlSerializer xs = new XmlSerializer(typeof(Person));
StringWriter sw = new StringWriter();
xs.Serialize(sw, thePerson);

Results in the followng XML - Notice there is no Age

<Person xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Name>Chris</Name>
</Person>

How can I control Chromedriver open window size?

In java/groovy try:

import java.awt.Toolkit;
import org.openqa.selenium.Dimension;         
import org.openqa.selenium.Point;

...

java.awt.Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

Dimension maximizedScreenSize = new Dimension((int) screenSize.getWidth(), (int) screenSize.getHeight());
driver.manage().window().setPosition(new Point(0, 0));
driver.manage().window().setSize(maximizedScreenSize);

this will open browser in fullscreen

How to get a reference to an iframe's window object inside iframe's onload handler created from parent window

You're declaring everything in the parent page. So the references to window and document are to the parent page's. If you want to do stuff to the iframe's, use iframe || iframe.contentWindow to access its window, and iframe.contentDocument || iframe.contentWindow.document to access its document.

There's a word for what's happening, possibly "lexical scope": What is lexical scope?

The only context of a scope is this. And in your example, the owner of the method is doc, which is the iframe's document. Other than that, anything that's accessed in this function that uses known objects are the parent's (if not declared in the function). It would be a different story if the function were declared in a different place, but it's declared in the parent page.

This is how I would write it:

(function () {
  var dom, win, doc, where, iframe;

  iframe = document.createElement('iframe');
  iframe.src = "javascript:false";

  where = document.getElementsByTagName('script')[0];
  where.parentNode.insertBefore(iframe, where);

  win = iframe.contentWindow || iframe;
  doc = iframe.contentDocument || iframe.contentWindow.document;

  doc.open();
  doc._l = (function (w, d) {
    return function () {
      w.vanishing_global = new Date().getTime();

      var js = d.createElement("script");
      js.src = 'test-vanishing-global.js?' + w.vanishing_global;

      w.name = "foobar";
      d.foobar = "foobar:" + Math.random();
      d.foobar = "barfoo:" + Math.random();
      d.body.appendChild(js);
    };
  })(win, doc);
  doc.write('<body onload="document._l();"></body>');
  doc.close();
})();

The aliasing of win and doc as w and d aren't necessary, it just might make it less confusing because of the misunderstanding of scopes. This way, they are parameters and you have to reference them to access the iframe's stuff. If you want to access the parent's, you still use window and document.

I'm not sure what the implications are of adding methods to a document (doc in this case), but it might make more sense to set the _l method on win. That way, things can be run without a prefix...such as <body onload="_l();"></body>

How to use jQuery Plugin with Angular 4?

Install jquery with npm

npm install jquery --save

Add typings

npm install --save-dev @types/jquery

Add scripts to angular-cli.json

"apps": [{
  ...
  "scripts": [
    "../node_modules/jquery/dist/jquery.min.js",
  ],
  ...
}]

Build project and serve

ng build

Hope this helps! Enjoy coding

Find which version of package is installed with pip

Pip 1.3 now also has a list command:

$ pip list
argparse (1.2.1)
pip (1.5.1)
setuptools (2.1)
wsgiref (0.1.2)

"Permission Denied" trying to run Python on Windows 10

I had this to Run /execute but was not working

python3 -m http.server 8080

after reading and trying some of the solutions above and did not worked , what worked for me was

python -m http.server 8080

Could not find folder 'tools' inside SDK

I faced similar issue when the SDK tools installation was failed during the initial setup. To resolution is to download SDK tools from Android Developer Site

  • Expand "USE AN EXISTING IDE" section and download standalone SDK tools
  • Choose your destination as (%HOMEPATH%\android-sdks)
  • Now start Android-SDKs folder and run SDK manager

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

It looks like, when you try to delete the same object and then again update the same object, then it gives you this error. As after every update hibernate for safe checking fires how many rows were updated, but during the code the data must have been deleted. Over here hibernate distinguish between the objects based on the key what u have assigned or the equals method.

so, just go through once through your code for this check, or try with implementing equals & hashcode method correctly which might help.

How do I install ASP.NET MVC 5 in Visual Studio 2012?

Microsoft has provided for you on their MSDN blogs: MVC 5 for VS2012. From that blog:

We have released ASP.NET and Web Tools 2013.1 for Visual Studio 2012. This release brings a ton of great improvements, and include some fantastic enhancements to ASP.NET MVC 5, Web API 2, Scaffolding and Entity Framework to users of Visual Studio 2012 and Visual Studio 2012 Express for Web.

You can download and start using these features now.

The download link is to a Web Platform Installer that will allow you to start a new MVC5 project from VS2012.

How do I UPDATE from a SELECT in SQL Server?

UPDATE table AS a
INNER JOIN table2 AS b
ON a.col1 = b.col1
INNER JOIN ... AS ...
ON ... = ...
SET ...
WHERE ...

Changing Shell Text Color (Windows)

This is extremely simple! Rather than importing odd modules for python or trying long commands you can take advantage of windows OS commands.

In windows, commands exist to change the command prompt text color. You can use this in python by starting with a: import os

Next you need to have a line changing the text color, place it were you want in your code. os.system('color 4')

You can figure out the other colors by starting cmd.exe and typing color help.

The good part? Thats all their is to it, to simple lines of code. -Day

ConfigurationManager.AppSettings - How to modify and save?

Prefer <appSettings> to <customUserSetting> section. It is much easier to read AND write with (Web)ConfigurationManager. ConfigurationSection, ConfigurationElement and ConfigurationElementCollection require you to derive custom classes and implement custom ConfigurationProperty properties. Way too much for mere everyday mortals IMO.

Here is an example of reading and writing to web.config:

using System.Web.Configuration;
using System.Configuration;

Configuration config = WebConfigurationManager.OpenWebConfiguration("/");
string oldValue = config.AppSettings.Settings["SomeKey"].Value;
config.AppSettings.Settings["SomeKey"].Value = "NewValue";
config.Save(ConfigurationSaveMode.Modified);

Before:

<appSettings>
  <add key="SomeKey" value="oldValue" />
</appSettings>

After:

<appSettings>
  <add key="SomeKey" value="newValue" />
</appSettings>

How can I get input radio elements to horizontally align?

Here is updated Fiddle

Simply remove </br> between input radio's

<div class="clearBoth"></div>
<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change
<div class="clearBoth"></div>

Setting "checked" for a checkbox with jQuery

$(".myCheckBox").prop("checked","checked");

How to get an IFrame to be responsive in iOS Safari?

The problem, it seems, is that Mobile Safari will refuse to obey the width of your iFrame if the document it contains is wider than what you have specified. Example:

http://jsbin.com/hapituto/1

On a desktop browser, you will see an iFrame and a Div both set to 300px. The contents is wider so you can scroll the iFrame.

On mobile safari, however, you will notice that the iFrame is auto-expanded to the width of the content.

My guess is that this is a workaround for long-standing issues with scrolling content within a page. In the past, if you had a large scrolling iframe on a touch device, you'd get 'stuck' in the iframe as that would be scrolling instead of the page itself. It appears Apple has decided that the default behavior of an iFrame is 'no scroll' and expands to prevent it.

One option may be this workaround. Instead of assuming the iFrame will scroll, place the iframe in a DIV that you do have control over and let that scroll.

example: http://jsbin.com/zakedaja/1

Example markup:

<div style="overflow: scroll; -webkit-overflow-scrolling: touch; width: 300px;">
   <iframe src="http://jsbin.com/roredora/1/" style="width: 600px;"></iframe>
</div>

On mobile safari, you can now scroll the contents of the now fully-expanded iFrame via the div that is containing it.

The catch: This looks really ugly on a desktop browser, as now you have double scrollbars. So you may have to do some browser detection with JS to get around this.

How do I write JSON data to a file?

To get utf8-encoded file as opposed to ascii-encoded in the accepted answer for Python 2 use:

import io, json
with io.open('data.txt', 'w', encoding='utf-8') as f:
  f.write(json.dumps(data, ensure_ascii=False))

The code is simpler in Python 3:

import json
with open('data.txt', 'w') as f:
  json.dump(data, f, ensure_ascii=False)

On Windows, the encoding='utf-8' argument to open is still necessary.

To avoid storing an encoded copy of the data in memory (result of dumps) and to output utf8-encoded bytestrings in both Python 2 and 3, use:

import json, codecs
with open('data.txt', 'wb') as f:
    json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)

The codecs.getwriter call is redundant in Python 3 but required for Python 2


Readability and size:

The use of ensure_ascii=False gives better readability and smaller size:

>>> json.dumps({'price': '€10'})
'{"price": "\\u20ac10"}'
>>> json.dumps({'price': '€10'}, ensure_ascii=False)
'{"price": "€10"}'

>>> len(json.dumps({'?????': 1}))
37
>>> len(json.dumps({'?????': 1}, ensure_ascii=False).encode('utf8'))
17

Further improve readability by adding flags indent=4, sort_keys=True (as suggested by dinos66) to arguments of dump or dumps. This way you'll get a nicely indented sorted structure in the json file at the cost of a slightly larger file size.

jQuery If DIV Doesn't Have Class "x"

I think the author was looking for:

$(this).not('.selected')

Extract parameter value from url using regular expressions

Not tested but this should work:

/\?v=([a-z0-9\-]+)\&?/i

How to open in default browser in C#

Open dynamically

string addres= "Print/" + Id + ".htm";
           System.Diagnostics.Process.Start(Path.Combine(Environment.CurrentDirectory, addres));

Fatal error: Call to a member function fetch_assoc() on a non-object

That's because there was an error in your query. MySQli->query() will return false on error. Change it to something like::

$result = $this->database->query($query);
if (!$result) {
    throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}

That should throw an exception if there's an error...

Use JAXB to create Object from XML String

If you already have the xml, and comes more than one attribute, you can handle it as follows:

String output = "<ciudads><ciudad><idCiudad>1</idCiudad>
<nomCiudad>BOGOTA</nomCiudad></ciudad><ciudad><idCiudad>6</idCiudad>
<nomCiudad>Pereira</nomCiudad></ciudads>";
DocumentBuilder db = DocumentBuilderFactory.newInstance()
    .newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(output));

Document doc = db.parse(is);
NodeList nodes = ((org.w3c.dom.Document) doc)
    .getElementsByTagName("ciudad");

for (int i = 0; i < nodes.getLength(); i++) {           
    Ciudad ciudad = new Ciudad();
    Element element = (Element) nodes.item(i);

    NodeList name = element.getElementsByTagName("idCiudad");
    Element element2 = (Element) name.item(0);
    ciudad.setIdCiudad(Integer
        .valueOf(getCharacterDataFromElement(element2)));

    NodeList title = element.getElementsByTagName("nomCiudad");
    element2 = (Element) title.item(0);
    ciudad.setNombre(getCharacterDataFromElement(element2));

    ciudades.getPartnerAccount().add(ciudad);
}
}

for (Ciudad ciudad1 : ciudades.getPartnerAccount()) {
System.out.println(ciudad1.getIdCiudad());
System.out.println(ciudad1.getNombre());
}

the method getCharacterDataFromElement is

public static String getCharacterDataFromElement(Element e) {
Node child = e.getFirstChild();
if (child instanceof CharacterData) {
CharacterData cd = (CharacterData) child;

return cd.getData();
}
return "";
}

VBA using ubound on a multidimensional array

You need to deal with the optional Rank parameter of UBound.

Dim arr(1 To 4, 1 To 3) As Variant
Debug.Print UBound(arr, 1)  '? returns 4
Debug.Print UBound(arr, 2)  '? returns 3

More at: UBound Function (Visual Basic)

ReactJS: "Uncaught SyntaxError: Unexpected token <"

If you have something like

Uncaught SyntaxError: embedded: Unexpected token

You probably missed a comma in a place like this:

  var CommentForm = React.createClass({
  getInitialState: function() {
      return {author: '', text: ''};

  }, // <---- DON'T FORGET THE COMMA

  render: function() {
      return (
      <form className="commentForm">
          <input type="text" placeholder="Nombre" />
          <input type="text" placeholder="Qué opina" />
          <input type="submit" value="Publicar" />
      </form>
      )
  }
  });

How to pass object with NSNotificationCenter

Swift 5

func post() {
    NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"), 
        object: nil, 
        userInfo:["key0": "value", "key1": 1234])
}

func addObservers() {
    NotificationCenter.default.addObserver(self, 
        selector: #selector(someMethod), 
        name: Notification.Name("SomeNotificationName"), 
        object: nil)
}

@objc func someMethod(_ notification: Notification) {
    let info0 = notification.userInfo?["key0"]
    let info1 = notification.userInfo?["key1"]
}

Bonus (that you should definitely do!) :

Replace Notification.Name("SomeNotificationName") with .someNotificationName:

extension Notification.Name {
    static let someNotificationName = Notification.Name("SomeNotificationName")
}

Replace "key0" and "key1" with Notification.Key.key0 and Notification.Key.key1:

extension Notification {
  enum Key: String {
    case key0
    case key1
  }
}

Why should I definitely do this ? To avoid costly typo errors, enjoy renaming, enjoy find usage etc...

Fixed header table with horizontal scrollbar and vertical scrollbar on

Here's a solution which again is not a CSS only solution. It is similar to avrahamcool's solution in that it uses a few lines of jQuery, but instead of changing heights and moving the header along, all it does is changing the width of tbody based on how far its parent table is scrolled along to the right.

An added bonus with this solution is that it works with a semantically valid HTML table.

It works great on all recent browser versions (IE10, Chrome, FF) and that's it, the scrolling functionality breaks on older versions.

But then the fact that you are using a semantically valid HTML table will save the day and ensure the table is still displayed properly, it's only the scrolling functionality that won't work on older browsers.

Here's a jsFiddle for demonstration purposes.

CSS

table {
    width: 300px;
    overflow-x: scroll;
    display: block;
}
thead, tbody {
    display: block;
}
tbody {
    overflow-y: scroll;
    overflow-x: hidden;
    height: 140px;
}
td, th {
    min-width: 100px;
}

JS

$("table").on("scroll", function () {
    $("table > *").width($("table").width() + $("table").scrollLeft());
});

I needed a version which degrades nicely in IE9 (no scrolling, just a normal table). Posting the fiddle here as it is an improved version. All you need to do is set a height on the tr.

Additional CSS to make this solution degrade nicely in IE9

tr {
    height: 25px; /* This could be any value, it just needs to be set. */ 
}

Here's a jsFiddle demonstrating the nicely degrading in IE9 version of this solution.

Edit: Updated fiddle links to link to a version of the fiddle which contains fixes for issues mentioned in the comments. Just adding a snippet with the latest and greatest version while I'm at it:

_x000D_
_x000D_
$('table').on('scroll', function() {_x000D_
  $("table > *").width($("table").width() + $("table").scrollLeft());_x000D_
});
_x000D_
html {_x000D_
  font-family: verdana;_x000D_
  font-size: 10pt;_x000D_
  line-height: 25px;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
  width: 300px;_x000D_
  overflow-x: scroll;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
thead {_x000D_
  background-color: #EFEFEF;_x000D_
}_x000D_
_x000D_
thead,_x000D_
tbody {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
tbody {_x000D_
  overflow-y: scroll;_x000D_
  overflow-x: hidden;_x000D_
  height: 140px;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  min-width: 100px;_x000D_
  height: 25px;_x000D_
  border: dashed 1px lightblue;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  max-width: 100px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column 1</th>_x000D_
      <th>Column 2</th>_x000D_
      <th>Column 3</th>_x000D_
      <th>Column 4</th>_x000D_
      <th>Column 5</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>AAAAAAAAAAAAAAAAAAAAAAAAAA</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
      <td>Row 1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
      <td>Row 2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
      <td>Row 3</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
      <td>Row 4</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
      <td>Row 5</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
      <td>Row 6</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
      <td>Row 7</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
      <td>Row 8</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
      <td>Row 9</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
      <td>Row 10</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

Can't find file executable in your configured search path for gnc gcc compiler

This simple in below solution worked for me. http://forums.codeblocks.org/index.php?topic=17336.0

I had a similar problem. Please note I'm a total n00b in C++ and IDE's but heres what I did (after some research) So of course I downloaded the version that came with the compiler and it didn't work. Heres what I did: 1) go to settings in the upper part 2) click compiler 3) choose reset to defaults.

Hopefully this works

Mongoose: Find, modify, save

Why not use Model.update? After all you're not using the found user for anything else than to update it's properties:

User.update({username: oldUsername}, {
    username: newUser.username, 
    password: newUser.password, 
    rights: newUser.rights
}, function(err, numberAffected, rawResponse) {
   //handle it
})

Open Facebook page from Android app?

Answering this in October 2018. The working code is the one using the pageID. I just tested it and it is functional.

public static void openUrl(Context ctx, String url){
    Uri uri = Uri.parse(url);
    if (url.contains(("facebook"))){
        try {
            ApplicationInfo applicationInfo = ctx.getPackageManager().getApplicationInfo("com.facebook.katana", 0);
            if (applicationInfo.enabled) {
                uri = Uri.parse("fb://page/<page_id>");
                openURI(ctx, uri);
                return;
            }
        } catch (PackageManager.NameNotFoundException ignored) {
            openURI(ctx, uri);
            return;
        }
    }

TypeError: argument of type 'NoneType' is not iterable

The python error says that wordInput is not an iterable -> it is of NoneType.

If you print wordInput before the offending line, you will see that wordInput is None.

Since wordInput is None, that means that the argument passed to the function is also None. In this case word. You assign the result of pickEasy to word.

The problem is that your pickEasy function does not return anything. In Python, a method that didn't return anything returns a NoneType.

I think you wanted to return a word, so this will suffice:

def pickEasy():
    word = random.choice(easyWords)
    word = str(word)
    for i in range(1, len(word) + 1):
        wordCount.append("_")
    return word

How to find Oracle Service Name

With SQL Developer you should also find it without writing any query. Right click on your Connection/Propriety.

You should see the name on the left under something like "connection details" and should look like "Connectionname@servicename", or on the right, under the connection's details.

Java RegEx meta character (.) and ordinary dot?

If you want to end check whether your sentence ends with "." then you have to add [\.\]$ to the end of your pattern.

Make the console wait for a user input to close

A simple trick:

import java.util.Scanner;  

/* Add these codes at the end of your method ...*/

Scanner input = new Scanner(System.in);
System.out.print("Press Enter to quit...");
input.nextLine();

How do I render a Word document (.doc, .docx) in the browser using JavaScript?

There seem to be some js libraries that can handle .docx (not .doc) to html conversion client-side (in no particular order):

Note: If you are looking for the best way to convert a doc/docx file on the client side, then probably the answer is don't do it. If you really need to do it then do it server-side, i.e. with libreoffice in headless mode, apache-poi (java), pandoc or whatever other library works best for you.

Difference between HashSet and HashMap?

Differences: with respect to heirarchy: HashSet implements Set. HashMap implements Map and stores a mapping of keys and values.

A use of HashSet and HashMap with respect to database would help you understand the significance of each.
HashSet: is generally used for storing unique collection objects. E.g: It might be used as implementation class for storing many-to-one relation ship between
class Item and Class Bid where (Item has many Bids) HashMap: is used to map a key to value.the value may be null or any Object /list of Object (which is object in itself).

How do you redirect HTTPS to HTTP?

Keep in mind that the Rewrite engine only kicks in once the HTTP request has been received - which means you would still need a certificate, in order for the client to set up the connection to send the request over!

However if the backup machine will appear to have the same hostname (as far as the client is concerned), then there should be no reason you can't use the same certificate as the main production machine.

Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot

Not really a technical solution, but SQL Server 2017 flat file import is totally revamped, and imported my large-ish file with 5 clicks, handled encoding / field length issues without any input from me

enter image description here

How to add bootstrap to an angular-cli project

  1. Install bootstrap, popper.js

npm install --save bootstrap npm install --save popper.js

  1. In src/styles.css, import bootstrap's style

@import '~bootstrap/dist/css/bootstrap.min.css';

Multiple Buttons' OnClickListener() android

I created dedicated class that implements View.OnClickListener.

public class ButtonClickListener implements View.OnClickListener {

    @Override
    public void onClick(View v) {
        Toast.makeText(MainActivity.this, "Button Clicked", Toast.LENGTH_SHORT).show();
    }

}

Then, I created an instance of this class in MainActivity

private ButtonClickListener onClickBtnListener = new ButtonClickListener();

and then set onClickListener for button

btn.setOnClickListener(onClickBtnListener);

Change language of Visual Studio 2017 RC

This should solve it:

  1. Open the Visual Studio Installer.
  2. Click on the Modify Button.
  3. Choose the Language Pack tab on top left.
  4. Check the language you need and click on the Modify Button at bottom right.

How to get the current date without the time?

Well, you can get just today's date as a DateTime using the Today property:

 DateTime today = DateTime.Today;

or more generally, you can use the Date property. For example, if you wanted the UTC date you could use:

 DateTime dateTime = DateTime.UtcNow.Date;

It's not very clear whether that's what you need or not though... if you're just looking to print the date, you can use:

Console.WriteLine(dateTime.ToString("d"));

or use an explicit format:

Console.WriteLine(dateTime.ToString("dd/MM/yyyy"));

See more about standard and custom date/time format strings. Depending on your situation you may also want to specify the culture.

If you want a more expressive date/time API which allows you to talk about dates separately from times, you might want to look at the Noda Time project which I started. It's not ready for production just yet, but we'd love to hear what you'd like to do with it...

SVN checkout the contents of a folder, not the folder itself

svn co svn://path destination

To specify current directory, use a "." for your destination directory:

svn checkout file:///home/landonwinters/svn/waterproject/trunk .

iOS detect if user is on an iPad

Be Careful: If your app is targeting iPhone device only, iPad running with iphone compatible mode will return false for below statement:

#define IPAD     UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad

The right way to detect physical iPad device is:

#define IS_IPAD_DEVICE      ([(NSString *)[UIDevice currentDevice].model hasPrefix:@"iPad"])

Labels for radio buttons in rails form

<% form_for(@message) do |f| %>
  <%= f.radio_button :contactmethod, 'email', :checked => true %> 
  <%= label :contactmethod_email, 'Email' %>
  <%= f.radio_button :contactmethod, 'sms' %>
  <%= label :contactmethod_sms, 'SMS' %>
<% end %>

Java - Reading XML file

Reading xml the easy way:

http://www.mkyong.com/java/jaxb-hello-world-example/

package com.mkyong.core;

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Customer {

    String name;
    int age;
    int id;

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

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

    public int getId() {
        return id;
    }

    @XmlAttribute
    public void setId(int id) {
        this.id = id;
    }

} 

.

package com.mkyong.core;

import java.io.File;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class JAXBExample {
    public static void main(String[] args) {

      Customer customer = new Customer();
      customer.setId(100);
      customer.setName("mkyong");
      customer.setAge(29);

      try {

        File file = new File("C:\\file.xml");
        JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // output pretty printed
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        jaxbMarshaller.marshal(customer, file);
        jaxbMarshaller.marshal(customer, System.out);

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

    }
}

C++ multiline string literal

You can also do this:

const char *longString = R""""(
This is 
a very 
long 
string
)"""";

Psql could not connect to server: No such file or directory, 5432 error?

This works for me:

pg_ctl -D /usr/local/var/[email protected] stop;
brew services stop [email protected];
brew services start [email protected];

Import existing source code to GitHub

From Bitbucket:

Push up an existing repository. You already have a Git repository on your computer. Let's push it up to Bitbucket:

cd /path/to/my/repo
git remote add origin ssh://[email protected]/javacat/geo.git
git push -u origin --all   # To push up the repo for the first time

How to determine the version of the C++ standard used by the compiler?

By my knowledge there is no overall way to do this. If you look at the headers of cross platform/multiple compiler supporting libraries you'll always find a lot of defines that use compiler specific constructs to determine such things:

/*Define Microsoft Visual C++ .NET (32-bit) compiler */
#if (defined(_M_IX86) && defined(_MSC_VER) && (_MSC_VER >= 1300)
     ...
#endif

/*Define Borland 5.0 C++ (16-bit) compiler */
#if defined(__BORLANDC__) && !defined(__WIN32__)
     ...
#endif

You probably will have to do such defines yourself for all compilers you use.

Close Window from ViewModel

I know this is an old post, probably no one would scroll this far, I know I didn't. So, after hours of trying different stuff, I found this blog and dude killed it. Simplest way to do this, tried it and it works like a charm.

Blog

In the ViewModel:

...

public bool CanClose { get; set; }

private RelayCommand closeCommand;
public ICommand CloseCommand
{
    get
    {
        if(closeCommand == null)
        (
            closeCommand = new RelayCommand(param => Close(), param => CanClose);
        )
    }
}

public void Close()
{
    this.Close();
}

...

add an Action property to the ViewModel, but define it from the View’s code-behind file. This will let us dynamically define a reference on the ViewModel that points to the View.

On the ViewModel, we’ll simply add:

public Action CloseAction { get; set; }

And on the View, we’ll define it as such:

public View()
{
    InitializeComponent() // this draws the View
    ViewModel vm = new ViewModel(); // this creates an instance of the ViewModel
    this.DataContext = vm; // this sets the newly created ViewModel as the DataContext for the View
    if ( vm.CloseAction == null )
        vm.CloseAction = new Action(() => this.Close());
}

How do I loop through or enumerate a JavaScript object?

Since es2015 is getting more and more popular I am posting this answer which include usage of generator and iterator to smoothly iterate through [key, value] pairs. As it is possible in other languages for instance Ruby.

Ok here is a code:

_x000D_
_x000D_
const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
  [Symbol.iterator]: function*() {
    for (const i of Object.keys(this)) {
      yield [i, this[i]];
    }
  }
};

for (const [k, v] of MyObject) {
  console.log(`Here is key ${k} and here is value ${v}`);
}
_x000D_
_x000D_
_x000D_

All information about how can you do an iterator and generator you can find at developer Mozilla page.

Hope It helped someone.

EDIT:

ES2017 will include Object.entries which will make iterating over [key, value] pairs in objects even more easier. It is now known that it will be a part of a standard according to the ts39 stage information.

I think it is time to update my answer to let it became even more fresher than it's now.

_x000D_
_x000D_
const MyObject = {
  'a': 'Hello',
  'b': 'it\'s',
  'c': 'me',
  'd': 'you',
  'e': 'looking',
  'f': 'for',
};

for (const [k, v] of Object.entries(MyObject)) {
  console.log(`Here is key ${k} and here is value ${v}`);
}
_x000D_
_x000D_
_x000D_

You can find more about usage on MDN page

React Router with optional path parameter

As with regular parameters, declaring an optional parameter is just a matter of the path property of a Route; any parameter that ends with a question mark will be treated as optional:

<Route path="to/page/:pathParam?" component={MyPage}/>

Python dictionary: Get list of values for list of keys

Following closure of Python: efficient way to create a list from dict values with a given order

Retrieving the keys without building the list:

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import collections


class DictListProxy(collections.Sequence):
    def __init__(self, klist, kdict, *args, **kwargs):
        super(DictListProxy, self).__init__(*args, **kwargs)
        self.klist = klist
        self.kdict = kdict

    def __len__(self):
        return len(self.klist)

    def __getitem__(self, key):
        return self.kdict[self.klist[key]]


myDict = {'age': 'value1', 'size': 'value2', 'weigth': 'value3'}
order_list = ['age', 'weigth', 'size']

dlp = DictListProxy(order_list, myDict)

print(','.join(dlp))
print()
print(dlp[1])

The output:

value1,value3,value2

value3

Which matches the order given by the list

How do I determine the current operating system with Node.js

var isWin64 = process.env.hasOwnProperty('ProgramFiles(x86)');

Add numpy array as column to Pandas data frame

Here is other example:

import numpy as np
import pandas as pd

""" This just creates a list of touples, and each element of the touple is an array"""
a = [ (np.random.randint(1,10,10), np.array([0,1,2,3,4,5,6,7,8,9]))  for i in 
range(0,10) ]

""" Panda DataFrame will allocate each of the arrays , contained as a touple 
element , as column"""
df = pd.DataFrame(data =a,columns=['random_num','sequential_num'])

The secret in general is to allocate the data in the form a = [ (array_11, array_12,...,array_1n),...,(array_m1,array_m2,...,array_mn) ] and panda DataFrame will order the data in n columns of arrays. Of course , arrays of arrays could be used instead of touples, in that case the form would be : a = [ [array_11, array_12,...,array_1n],...,[array_m1,array_m2,...,array_mn] ]

This is the output if you print(df) from the code above:

                       random_num                  sequential_num
0  [7, 9, 2, 2, 5, 3, 5, 3, 1, 4]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1  [8, 7, 9, 8, 1, 2, 2, 6, 6, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2  [3, 4, 1, 2, 2, 1, 4, 2, 6, 1]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3  [3, 1, 1, 1, 6, 2, 8, 6, 7, 9]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4  [4, 2, 8, 5, 4, 1, 2, 2, 3, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5  [3, 2, 7, 4, 1, 5, 1, 4, 6, 3]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6  [5, 7, 3, 9, 7, 8, 4, 1, 3, 1]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7  [7, 4, 7, 6, 2, 6, 3, 2, 5, 6]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8  [3, 1, 6, 3, 2, 1, 5, 2, 2, 9]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9  [7, 2, 3, 9, 5, 5, 8, 6, 9, 8]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Other variation of the example above:

b = [ (i,"text",[14, 5,], np.array([0,1,2,3,4,5,6,7,8,9]))  for i in 
range(0,10) ]
df = pd.DataFrame(data=b,columns=['Number','Text','2Elemnt_array','10Element_array'])

Output of df:

   Number  Text 2Elemnt_array                 10Element_array
0       0  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
1       1  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2       2  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
3       3  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
4       4  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
5       5  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
6       6  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
7       7  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
8       8  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
9       9  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

If you want to add other columns of arrays, then:

df['3Element_array']=[([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3]),([1,2,3])]

The final output of df will be:

   Number  Text 2Elemnt_array                 10Element_array 3Element_array
0       0  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
1       1  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
2       2  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
3       3  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
4       4  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
5       5  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
6       6  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
7       7  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
8       8  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]
9       9  text       [14, 5]  [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]      [1, 2, 3]

How to set a timer in android

I used to use (Timer, TimerTask) as well as Handler to kick off (time-consuming) tasks periodically. Now I've switched the whole to RxJava. RxJava provides Observable.timer which is simpler, less error-prone, hassle-free to use.

public class BetterTimerFragment extends Fragment {
  public static final String TAG = "BetterTimer";
  private TextView timeView;
  private Subscription timerSubscription;

  @Override
  public View onCreateView(LayoutInflater inflater,
                           @Nullable ViewGroup container,
                           @Nullable Bundle savedInstanceState) {
    return inflater.inflate(R.layout.fragment_timer, container, false);
  }

  @Override
  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    timeView = (TextView) view.findViewById(R.id.timeView);
  }

  @Override
  public void onResume() {
    super.onResume();

    // Right after the app is visible to users, delay 2 seconds
    // then kick off a (heavy) task every 10 seconds.
    timerSubscription = Observable.timer(2, 10, TimeUnit.SECONDS)
        .map(new Func1<Long, String>() {
          @Override
          public String call(Long unused) {
            // TODO: Probably do time-consuming work here.
            // This runs on a different thread than the main thread.
            return "Time: " + System.currentTimeMillis();
          }
        })
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(new Action1<String>() {
          @Override
          public void call(String timeText) {
            // The result will then be propagated back to the main thread.
            timeView.setText(timeText);
          }
        }, new Action1<Throwable>() {
          @Override
          public void call(Throwable throwable) {
            Log.e(TAG, throwable.getMessage(), throwable);
          }
        });
  }

  @Override
  public void onPause() {
    super.onPause();

    // Don't kick off tasks when the app gets invisible.
    timerSubscription.unsubscribe();
  }
}

How to disable gradle 'offline mode' in android studio?

Gradle is in offline mode, which means that it won't go to the network to resolve dependencies.

Go to Preferences > Gradle and uncheck "Offline work".

Printing result of mysql query from variable

$sql = "SELECT * FROM table_name ORDER BY ID DESC LIMIT 1";
$records = mysql_query($sql);

you can change LIMIT 1 to LIMIT any number you want

This will show you the last INSERTED row first.

Eclipse interface icons very small on high resolution screen in Windows 8.1

The best way is to edit the exe manifest with something like resource tuner and add

    <application xmlns="urn:schemas-microsoft-com:asm.v3"><windowsSettings><ms_windowsSettings:dpiAware xmlns:ms_windowsSettings="http://schemas.microsoft.com/SMI/2005/WindowsSettings" xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">false</ms_windowsSettings:dpiAware></windowsSettings></application>        

after dependency to set the exe as dpi unaware. This way the program will be a little pixelated but it will be in a confortable size.

HTML - Arabic Support

Won't you need the ensure the area where you display the Arabic is Right-to-Left orientated also?

e.g.

<p dir="rtl">

Use CSS3 transitions with gradient backgrounds

As stated. Gradients aren't currently supported with CSS Transitions. But you could work around it in some cases by setting one of the colors to transparent, so that the background-color of some other wrapping element shines through, and transition that instead.

jquery .on() method with load event

As the other have mentioned, the load event does not bubble. Instead you can manually trigger a load-like event with a custom event:

$('#item').on('namespace/onload', handleOnload).trigger('namespace/onload')

If your element is already listening to a change event:

$('#item').on('change', handleChange).trigger('change')

I find this works well. Though, I stick to custom events to be more explicit and avoid side effects.

Mocking a method to throw an exception (moq), but otherwise act like the mocked object?

Here's how you can mock your FileConnection

Mock<IFileConnection> fileConnection = new Mock<IFileConnection>(
                                                           MockBehavior.Strict);
fileConnection.Setup(item => item.Get(It.IsAny<string>,It.IsAny<string>))
              .Throws(new IOException());

Then instantiate your Transfer class and use the mock in your method call

Transfer transfer = new Transfer();
transfer.GetFile(fileConnection.Object, someRemoteFilename, someLocalFileName);

Update:

First of all you have to mock your dependencies only, not the class you are testing(Transfer class in this case). Stating those dependencies in your constructor make it easy to see what services your class needs to work. It also makes it possible to replace them with fakes when you are writing your unit tests. At the moment it's impossible to replace those properties with fakes.

Since you are setting those properties using another dependency, I would write it like this:

public class Transfer
{
    public Transfer(IInternalConfig internalConfig)
    {
        source = internalConfig.GetFileConnection("source");
        destination = internalConfig.GetFileConnection("destination");
    }

    //you should consider making these private or protected fields
    public virtual IFileConnection source { get; set; }
    public virtual IFileConnection destination { get; set; }

    public virtual void GetFile(IFileConnection connection, 
        string remoteFilename, string localFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void PutFile(IFileConnection connection, 
        string localFilename, string remoteFilename)
    {
        connection.Get(remoteFilename, localFilename);
    }

    public virtual void TransferFiles(string sourceName, string destName)
    {
        var tempName = Path.GetTempFileName();
        GetFile(source, sourceName, tempName);
        PutFile(destination, tempName, destName);
    }
}

This way you can mock internalConfig and make it return IFileConnection mocks that does what you want.

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

You can use a stubbing library like sinon to mock your service. You can then return $q.when() as your promise. If your scope object's value comes from the promise result, you will need to call scope.$root.$digest().

var scope, controller, datacontextMock, customer;
  beforeEach(function () {
        module('app');
        inject(function ($rootScope, $controller,common, datacontext) {
            scope = $rootScope.$new();
            var $q = common.$q;
            datacontextMock = sinon.stub(datacontext);
            customer = {id:1};
           datacontextMock.customer.returns($q.when(customer));

            controller = $controller('Index', { $scope: scope });

        })
    });


    it('customer id to be 1.', function () {


            scope.$root.$digest();
            expect(controller.customer.id).toBe(1);


    });

Understanding dict.copy() - shallow or deep?

"new" and "original" are different dicts, that's why you can update just one of them.. The items are shallow-copied, not the dict itself.

How to use QTimer

mytimer.h:

    #ifndef MYTIMER_H
    #define MYTIMER_H

    #include <QTimer>

    class MyTimer : public QObject
    {
        Q_OBJECT
    public:
        MyTimer();
        QTimer *timer;

    public slots:
        void MyTimerSlot();
    };

    #endif // MYTIME

mytimer.cpp:

#include "mytimer.h"
#include <QDebug>

MyTimer::MyTimer()
{
    // create a timer
    timer = new QTimer(this);

    // setup signal and slot
    connect(timer, SIGNAL(timeout()),
          this, SLOT(MyTimerSlot()));

    // msec
    timer->start(1000);
}

void MyTimer::MyTimerSlot()
{
    qDebug() << "Timer...";
}

main.cpp:

#include <QCoreApplication>
#include "mytimer.h"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Create MyTimer instance
    // QTimer object will be created in the MyTimer constructor
    MyTimer timer;

    return a.exec();
}

If we run the code:

Timer...
Timer...
Timer...
Timer...
Timer...
...

resources

How to wait for the 'end' of 'resize' event and only then perform an action?

UPDATE!

Better alternative also created by me is here: https://stackoverflow.com/a/23692008/2829600 (supports "delete functions")

ORIGINAL POST:

I wrote this simple function for handling delay in execution, useful inside jQuery .scroll() and .resize() So callback_f will run only once for specific id string.

function delay_exec( id, wait_time, callback_f ){

    // IF WAIT TIME IS NOT ENTERED IN FUNCTION CALL,
    // SET IT TO DEFAULT VALUE: 0.5 SECOND
    if( typeof wait_time === "undefined" )
        wait_time = 500;

    // CREATE GLOBAL ARRAY(IF ITS NOT ALREADY CREATED)
    // WHERE WE STORE CURRENTLY RUNNING setTimeout() FUNCTION FOR THIS ID
    if( typeof window['delay_exec'] === "undefined" )
        window['delay_exec'] = [];

    // RESET CURRENTLY RUNNING setTimeout() FUNCTION FOR THIS ID,
    // SO IN THAT WAY WE ARE SURE THAT callback_f WILL RUN ONLY ONE TIME
    // ( ON LATEST CALL ON delay_exec FUNCTION WITH SAME ID  )
    if( typeof window['delay_exec'][id] !== "undefined" )
        clearTimeout( window['delay_exec'][id] );

    // SET NEW TIMEOUT AND EXECUTE callback_f WHEN wait_time EXPIRES,
    // BUT ONLY IF THERE ISNT ANY MORE FUTURE CALLS ( IN wait_time PERIOD )
    // TO delay_exec FUNCTION WITH SAME ID AS CURRENT ONE
    window['delay_exec'][id] = setTimeout( callback_f , wait_time );
}


// USAGE

jQuery(window).resize(function() {

    delay_exec('test1', 1000, function(){
        console.log('1st call to delay "test1" successfully executed!');
    });

    delay_exec('test1', 1000, function(){
        console.log('2nd call to delay "test1" successfully executed!');
    });

    delay_exec('test1', 1000, function(){
        console.log('3rd call to delay "test1" successfully executed!');
    });

    delay_exec('test2', 1000, function(){
        console.log('1st call to delay "test2" successfully executed!');
    });

    delay_exec('test3', 1000, function(){
        console.log('1st call to delay "test3" successfully executed!');
    });

});

/* RESULT
3rd call to delay "test1" successfully executed!
1st call to delay "test2" successfully executed!
1st call to delay "test3" successfully executed!
*/

Simplest way to wait some asynchronous tasks complete, in Javascript?

Expanding upon @freakish answer, async also offers a each method, which seems especially suited for your case:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    conn.collection(name).drop( callback );
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

IMHO, this makes the code both more efficient and more legible. I've taken the liberty of removing the console.log('dropped') - if you want it, use this instead:

var async = require('async');

async.each(['aaa','bbb','ccc'], function(name, callback) {
    // if you really want the console.log( 'dropped' ),
    // replace the 'callback' here with an anonymous function
    conn.collection(name).drop( function(err) {
        if( err ) { return callback(err); }
        console.log('dropped');
        callback()
    });
}, function(err) {
    if( err ) { return console.log(err); }
    console.log('all dropped');
});

Multiple commands in an alias for bash

Adding my 2 cents to the 11 year old discussion try this:

alias lock="gnome-screensaver \gnome-screensaver-command --lock"

How to scroll to top of page with JavaScript/jQuery?

var totop = $('#totop');
totop.click(function(){
 $('html, body').stop(true,true).animate({scrollTop:0}, 1000);
 return false;
});

$(window).scroll(function(){
 if ($(this).scrollTop() > 100){ 
  totop.fadeIn();
 }else{
  totop.fadeOut();
 }
});

<img id="totop" src="img/arrow_up.png" title="Click to go Up" style="display:none;position:fixed;bottom:10px;right:10px;cursor:pointer;cursor:hand;"/>

How to select the comparison of two columns as one column in Oracle

If you want to consider null values equality too, try the following

select column1, column2, 
   case
      when column1 is NULL and column2 is NULL then 'true'  
      when column1=column2 then 'true' 
      else 'false' 
   end 
from table;

How to modify a CSS display property from JavaScript?

It should be document.getElementById("hidden").style.display = "block"; not document.getElementById["hidden"].style.display = "block";


EDIT due to author edit:

Why are you using a <div> here? Just add an ID to the table element and add a hidden style to it. E.g. <td id="hidden" style="display:none" class="depot_table_left">

css transform, jagged edges in chrome

Adding the following on the div surrounding the element in question fixed this for me.

-webkit-transform-style: preserve-3d;

The jagged edges were appearing around the video window in my case.

WPF C# button style

Here's my attempt. Looks more similar to the OP's sample and provides settable properties for icon (FrameworkElement), title (string) and subtitle (string). The output looks like this:

enter image description here

Here's XAML:

<Button x:Class="Controls.FancyButton"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:local="clr-namespace:Controls"
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300" Width="300" Height="80"
          BorderBrush="{x:Null}" BorderThickness="0">
  <Button.Effect>
    <DropShadowEffect BlurRadius="12" Color="Gray" Direction="270" Opacity=".8" ShadowDepth="3" />
  </Button.Effect>

  <Button.Template>
    <ControlTemplate TargetType="Button">
      <Grid Width="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualWidth}"
        Height="{Binding RelativeSource={RelativeSource AncestorType=Button}, Path=ActualHeight}">

        <Border x:Name="MainBorder" CornerRadius="3" Grid.ColumnSpan="2" Margin="0,0,4,4" BorderBrush="Black" BorderThickness="1">
          <Border.Background>
            <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
              <GradientStop Color="#FF5E5E5E" Offset="0" />
              <GradientStop Color="#FF040404" Offset="1" />
            </LinearGradientBrush>
          </Border.Background>

          <Grid >
            <Grid.ColumnDefinitions>
              <ColumnDefinition Width="1.2*"/>
              <ColumnDefinition Width="3*"/>
            </Grid.ColumnDefinitions>

            <Border CornerRadius="2" Margin="0" BorderBrush="LightGray" BorderThickness="0,1,0,0" Grid.ColumnSpan="2" Grid.RowSpan="2" />

            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="0" HorizontalAlignment="Right" Stroke="#0C0C0C" Grid.RowSpan="2" />
            <Line X1="10" Y1="0" X2="10" Y2="10" Stretch="Fill" Grid.Column="1" HorizontalAlignment="Left" Grid.RowSpan="2">
              <Line.Stroke>
                <LinearGradientBrush StartPoint="0,0" EndPoint="0,1">
                  <GradientStop Color="#4D4D4D" Offset="0" />
                  <GradientStop Color="#2C2C2C" Offset="1" />
                </LinearGradientBrush>
              </Line.Stroke>
            </Line>

            <ContentControl HorizontalAlignment="Center" VerticalAlignment="Center" Grid.RowSpan="2">
              <ContentControl.Content>
                <Binding RelativeSource="{RelativeSource TemplatedParent}" Path="Image">
                  <Binding.FallbackValue>
                    <Path Data="M0,0 L30,15 L0,30Z">
                      <Path.Effect>
                        <DropShadowEffect Direction="50" ShadowDepth="2" />
                      </Path.Effect>
                      <Path.Fill>
                        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
                          <GradientStop Color="#4B86B2" Offset="0" />
                          <GradientStop Color="#477FA8" Offset="1" />
                        </LinearGradientBrush>
                      </Path.Fill>
                    </Path>
                  </Binding.FallbackValue>
                </Binding>
              </ContentControl.Content>
            </ContentControl>


            <Grid Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Center">
              <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="Auto" />
              </Grid.RowDefinitions>

              <TextBlock x:Name="Title" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Title, FallbackValue='Watch Now'}" Grid.Column="1" VerticalAlignment="Bottom" FontFamily="Calibri" FontWeight="Bold" FontSize="28" Foreground="White" Margin="20,0,0,0" />
              <TextBlock x:Name="SubTitle" Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=SubTitle, FallbackValue='Duration: 50 min'}" Grid.Column="1" Grid.Row="1" VerticalAlignment="top" FontFamily="Calibri" FontSize="14" Foreground="White" Margin="20,0,0,0" />
            </Grid>
          </Grid>
        </Border>
      </Grid>

      <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
          <Setter TargetName="Title" Property="TextDecorations" Value="Underline" />
          <Setter TargetName="SubTitle" Property="TextDecorations" Value="Underline" />
        </Trigger>
        <Trigger Property="IsPressed" Value="True">
          <Setter TargetName="MainBorder" Property="Background">
            <Setter.Value>
              <LinearGradientBrush StartPoint="0.5,0" EndPoint="0.5,1">
                <GradientStop Color="#FF5E5E5E" Offset="0" />
                <GradientStop Color="#FFA4A4A4" Offset="1" />
              </LinearGradientBrush>
            </Setter.Value>
          </Setter>
        </Trigger>
      </ControlTemplate.Triggers>
    </ControlTemplate>
  </Button.Template>
</Button>

Here's the code-behind:

using System.Windows;
using System.Windows.Controls;

namespace Controls
{
  public partial class FancyButton : Button
  {
    public FancyButton()
    {
      InitializeComponent();
    }

    public string Title
    {
      get { return (string)GetValue(TitleProperty); }
      set { SetValue(TitleProperty, value); }
    }

    public static readonly DependencyProperty TitleProperty =
        DependencyProperty.Register("Title", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("Title", FrameworkPropertyMetadataOptions.AffectsRender));

    public string SubTitle
    {
      get { return (string)GetValue(SubTitleProperty); }
      set { SetValue(SubTitleProperty, value); }
    }

    public static readonly DependencyProperty SubTitleProperty =
        DependencyProperty.Register("SubTitle", typeof(string), typeof(FancyButton), new FrameworkPropertyMetadata("SubTitle", FrameworkPropertyMetadataOptions.AffectsRender));

    public FrameworkElement Image
    {
      get { return (FrameworkElement)GetValue(ImageProperty); }
      set { SetValue(ImageProperty, value); }
    }

    public static readonly DependencyProperty ImageProperty =
        DependencyProperty.Register("Image", typeof(FrameworkElement), typeof(FancyButton), new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender));
  }
}

Here is how to use it:

<controls:FancyButton Grid.Row="1" HorizontalAlignment="Right" Margin="3" Title="Watch Now" SubTitle="Duration: 50 min">
  <controls:FancyButton.Image>
    <Path Data="M0,0 L30,15 L0,30Z">
      <Path.Effect>
        <DropShadowEffect Direction="50" ShadowDepth="2" />
      </Path.Effect>
      <Path.Fill>
        <LinearGradientBrush StartPoint="0,0.5" EndPoint="1,0.5">
          <GradientStop Color="#4B86B2" Offset="0" />
          <GradientStop Color="#477FA8" Offset="1" />
        </LinearGradientBrush>
      </Path.Fill>
    </Path>
  </controls:FancyButton.Image>
</controls:FancyButton>

Does Python have a toString() equivalent, and can I convert a db.Model element to String?

In python, the str() method is similar to the toString() method in other languages. It is called passing the object to convert to a string as a parameter. Internally it calls the __str__() method of the parameter object to get its string representation.

In this case, however, you are comparing a UserProperty author from the database, which is of type users.User with the nickname string. You will want to compare the nickname property of the author instead with todo.author.nickname in your template.

CSS to keep element at "fixed" position on screen

You can do like this:

#mydiv {
    position: fixed; 
    height: 30px; 
    top: 0; 
    left: 0; 
    width: 100%; 
}

This will create a div, that will be fixed on top of your screen. - fixed

Why use multiple columns as primary keys (composite primary key)

You use a compound key (a key with more than one attribute) whenever you want to ensure the uniqueness of a combination of several attributes. A single attribute key would not achieve the same thing.

Number of rows affected by an UPDATE in PL/SQL

Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows

Auto-size dynamic text to fill fixed size container

I did like

let name = "Making statements based on opinion; back them up with references or personal experience."
let originFontSize = 15;
let maxDisplayCharInLine = 50; 
let fontSize = Math.min(originFontSize, originFontSize / (name.length / maxDisplayCharInLine));

Changing the browser zoom level

as the the accepted answer mentioned, you can enlarge the fontSize css attribute of the element in DOM one by one, the following code for your reference.

 <script>
    var factor = 1.2;
    var all = document.getElementsByTagName("*");
    for (var i=0, max=all.length; i < max; i++) {
        var style = window.getComputedStyle(all[i]);
        var fontSize = style.getPropertyValue('font-size');

        if(fontSize){
            all[i].style.fontSize=(parseFloat(fontSize)*factor)+"px";
        }
        if(all[i].nodeName === "IMG"){
            var width=style.getPropertyValue('width');
            var height=style.getPropertyValue('height');
            all[i].style.height = (parseFloat(height)*factor)+"px";
            all[i].style.width = (parseFloat(width)*factor)+"px";
        }
    }
</script>

HTML img align="middle" doesn't align an image

just remove float: left and replace align with margin: 0 auto and it will be centered.

Is a URL allowed to contain a space?

Why does it have to be encoded? A request looks like this:

GET /url HTTP/1.1
(Ignoring headers)

There are 3 fields separated by a white space. If you put a space in your url:

GET /url end_url HTTP/1.1

You know have 4 fields, the HTTP server will tell you it is an invalid request.

GET /url%20end_url HTTP/1.1

3 fields => valid

Note: in the query string (after ?), a space is usually encoded as a +

GET /url?var=foo+bar HTTP/1.1 

rather than

GET /url?var=foo%20bar HTTP/1.1 

How to uninstall a package installed with pip install --user

The answer is Not possible yet. You have to remove it manually.

Failure during conversion to COFF: file invalid or corrupt

Had to install VS 2010 SP1 in order to get it to work again for myself. Lame microsoft.

How to disable compiler optimizations in gcc?

Use the command-line option -O0 (-[capital o][zero]) to disable optimization, and -S to get assembly file. Look here to see more gcc command-line options.

Detect if the device is iPhone X

I think that Apple don't want us manually check if the device has "notch" or "home indicator" but the code that works is:

-(BOOL)hasTopNotch{

    if (@available(iOS 11.0, *)) {

        float max_safe_area_inset = MAX(MAX([[[UIApplication sharedApplication] delegate] window].safeAreaInsets.top, [[[UIApplication sharedApplication] delegate] window].safeAreaInsets.right),MAX([[[UIApplication sharedApplication] delegate] window].safeAreaInsets.bottom, [[[UIApplication sharedApplication] delegate] window].safeAreaInsets.left));

        return max_safe_area_inset >= 44.0;

    }

    return  NO;

}

-(BOOL)hasHomeIndicator{

    if (@available(iOS 11.0, *)) {

        int iNumberSafeInsetsEqualZero = 0;

        if([[[UIApplication sharedApplication] delegate] window].safeAreaInsets.top == 0.0)iNumberSafeInsetsEqualZero++;
        if([[[UIApplication sharedApplication] delegate] window].safeAreaInsets.right == 0.0)iNumberSafeInsetsEqualZero++;
        if([[[UIApplication sharedApplication] delegate] window].safeAreaInsets.bottom == 0.0)iNumberSafeInsetsEqualZero++;
        if([[[UIApplication sharedApplication] delegate] window].safeAreaInsets.left == 0.0)iNumberSafeInsetsEqualZero++;

        return iNumberSafeInsetsEqualZero <= 2;

    }

    return  NO;

}

Some of the other posts doesn't work. For example, iPhone 6S with "in-call status bar" (green bar) in portrait mode has a big top safe inset. With my code all the cases are taken up (even if device starts in portrait or landscape)

How to implement a Navbar Dropdown Hover in Bootstrap v4?

1. Remove data-toggle="dropdown" attribute (so click will not open dropdown menu)

2. Add :hover pseudo-class to show dropdown-menu

_x000D_
_x000D_
.dropdown:hover .dropdown-menu {display: block;}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<nav class="navbar navbar-toggleable-md navbar-light bg-faded">_x000D_
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">_x000D_
    <span class="navbar-toggler-icon"></span>_x000D_
  </button>_x000D_
  <a class="navbar-brand" href="#">Navbar</a>_x000D_
  <div class="collapse navbar-collapse" id="navbarNavDropdown">_x000D_
    <ul class="navbar-nav">_x000D_
      <li class="nav-item active">_x000D_
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>_x000D_
      </li>_x000D_
      <li class="nav-item dropdown">_x000D_
        <a class="nav-link dropdown-toggle" href="http://example.com" id="navbarDropdownMenuLink" aria-haspopup="true" aria-expanded="false">_x000D_
          Dropdown link_x000D_
        </a>_x000D_
        <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink">_x000D_
          <a class="dropdown-item" href="#">Action</a>_x000D_
          <a class="dropdown-item" href="#">Another action</a>_x000D_
          <a class="dropdown-item" href="#">Something else here</a>_x000D_
        </div>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Features</a>_x000D_
      </li>_x000D_
      <li class="nav-item">_x000D_
        <a class="nav-link" href="#">Pricing</a>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

How to encode a URL in Swift

XCODE 8, SWIFT 3.0

From grokswift

Creating URLs from strings is a minefield for bugs. Just miss a single / or accidentally URL encode the ? in a query and your API call will fail and your app won’t have any data to display (or even crash if you didn’t anticipate that possibility). Since iOS 8 there’s a better way to build URLs using NSURLComponents and NSURLQueryItems.

func createURLWithComponents() -> URL? {
    var urlComponents = URLComponents()
    urlComponents.scheme = "http"
    urlComponents.host = "maps.googleapis.com"
    urlComponents.path = "/maps/api/geocode/json"

    let addressQuery = URLQueryItem(name: "address", value: "American Tourister, Abids Road, Bogulkunta, Hyderabad, Andhra Pradesh, India")
    urlComponents.queryItems = [addressQuery]

    return urlComponents.url
}

Below is the code to access url using guard statement.

guard let url = createURLWithComponents() else {
            print("invalid URL")
            return nil
      }
      print(url)

Output:

http://maps.googleapis.com/maps/api/geocode/json?address=American%20Tourister,%20Abids%20Road,%20Bogulkunta,%20Hyderabad,%20Andhra%20Pradesh,%20India

Read More: Building URLs With NSURLComponents and NSURLQueryItems

Inserting records into a MySQL table using Java

no that cannot work(not with real data):

String sql = "INSERT INTO course " +
        "VALUES (course_code, course_desc, course_chair)";
    stmt.executeUpdate(sql);

change it to:

String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
        "VALUES (?, ?, ?)";

Create a PreparedStatment with that sql and insert the values with index:

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate(); 

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

If you have @oneToOne mapping set to FetchType.LAZY and you use second query (because you need Department objects to be loaded as part of Employee objects) what Hibernate will do is, it will issue queries to fetch Department objects for every individual Employee object it fetches from DB.

Later, in the code you might access Department objects via Employee to Department single-valued association and Hibernate will not issue any query to fetch Department object for the given Employee.

Remember, Hibernate still issues queries equal to the number of Employees it has fetched. Hibernate will issue same number of queries in both above queries, if you wish to access Department objects of all Employee objects

sql searching multiple words in a string

Here is what I uses to search for multiple words in multiple columns - SQL server

Hope my answer help someone :) Thanks

declare @searchTrm varchar(MAX)='one two three ddd 20   30 comment'; 
--select value from STRING_SPLIT(@searchTrm, ' ') where trim(value)<>''
select * from Bols 
WHERE EXISTS (SELECT value  
    FROM STRING_SPLIT(@searchTrm, ' ')  
    WHERE 
        trim(value)<>''
        and(    
        BolNumber like '%'+ value+'%'
        or UserComment like '%'+ value+'%'
        or RequesterId like '%'+ value+'%' )
        )

How to delete selected text in the vi editor

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

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

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

Happy hacking!

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

MySQL multiple instances present on Ubuntu.

step 1 : if it's listed as installed, you got it. Else you need to get it.

sudo ps -A | grep mysql

step 2 : remove the one MySQL

sudo apt-get remove mysql

sudo service mysql restart

step 3 : restart lamp

sudo /opt/lampp/lampp restart

jquery smooth scroll to an anchor?

Here's the code I used to quickly bind jQuery scrollTo to all anchor links:

// Smooth scroll
$('a[href*=#]').click(function () {
    var hash = $(this).attr('href');
    hash = hash.slice(hash.indexOf('#') + 1);
    $.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500);
    window.location.hash = '#' + hash;
    return false;
});

JSON forEach get Key and Value

Loop through object with arrow functions

ES6

Object.keys(myObj).forEach(key => {
    console.log(key + ' - ' + myObj[key]) // key - value
})

ES7

Object.entries(myObj).forEach(([key, value]) => {
    console.log(key + ' - ' + value) // key - value
})

ES8

Loop through objects with ES8 with explanation

Angular: Cannot find a differ supporting object '[object Object]'

Missing square brackets around input property may cause this error. For example:

Component Foo {
    @Input()
    bars: BarType[];
}

Correct:

<app-foo [bars]="smth"></app-foo>

Incorrect (triggering error):

<app-foo bars="smth"></app-foo>

Convert a RGB Color Value to a Hexadecimal String

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.

Using variable in SQL LIKE statement

I had also problem using local variables in LIKE.
Important is to know: how long is variable.
Below, ORDER_NO is 50 characters long, so You can not use: LIKE @ORDER_NO, because in the end will be spaces.
You need to trim right side of the variable first.
Like this:

DECLARE @ORDER_NO char(50)
SELECT @ORDER_NO = 'OR/201910/0012%'

SELECT * FROM orders WHERE ord_no LIKE RTRIM(@ORDER_NO)

Split an integer into digits to compute an ISBN checksum

Convert it to string and map over it with the int() function.

map(int, str(1231231231))

Alter and Assign Object Without Side Effects

Objects are passed by reference.. To create a new object, I follow this approach..

//Template code for object creation.
function myElement(id, value) {
    this.id = id;
    this.value = value;
}
var myArray = [];

//instantiate myEle
var myEle = new myElement(0, 0);
//store myEle
myArray[0] = myEle;

//Now create a new object & store it
myEle = new myElement(0, 1);
myArray[1] = myEle;

How do you initialise a dynamic array in C++?

Two ways:

char *c = new char[length];
std::fill(c, c + length, INITIAL_VALUE);
// just this once, since it's char, you could use memset

Or:

std::vector<char> c(length, INITIAL_VALUE);

In my second way, the default second parameter is 0 already, so in your case it's unnecessary:

std::vector<char> c(length);

[Edit: go vote for Fred's answer, char* c = new char[length]();]

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Npm and Bower are both dependency management tools. But the main difference between both is npm is used for installing Node js modules but bower js is used for managing front end components like html, css, js etc.

A fact that makes this more confusing is that npm provides some packages which can be used in front-end development as well, like grunt and jshint.

These lines add more meaning

Bower, unlike npm, can have multiple files (e.g. .js, .css, .html, .png, .ttf) which are considered the main file(s). Bower semantically considers these main files, when packaged together, a component.

Edit: Grunt is quite different from Npm and Bower. Grunt is a javascript task runner tool. You can do a lot of things using grunt which you had to do manually otherwise. Highlighting some of the uses of Grunt:

  1. Zipping some files (e.g. zipup plugin)
  2. Linting on js files (jshint)
  3. Compiling less files (grunt-contrib-less)

There are grunt plugins for sass compilation, uglifying your javascript, copy files/folders, minifying javascript etc.

Please Note that grunt plugin is also an npm package.

Question-1

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

It really depends where does this package belong to. If it is a node module(like grunt,request) then it will go in package.json otherwise into bower json.

Question-2

When should I ever install packages explicitly like that without adding them to the file that manages dependencies

It does not matter whether you are installing packages explicitly or mentioning the dependency in .json file. Suppose you are in the middle of working on a node project and you need another project, say request, then you have two options:

  • Edit the package.json file and add a dependency on 'request'
  • npm install

OR

  • Use commandline: npm install --save request

--save options adds the dependency to package.json file as well. If you don't specify --save option, it will only download the package but the json file will be unaffected.

You can do this either way, there will not be a substantial difference.

An existing connection was forcibly closed by the remote host - WCF

I' ve got the same problem. My solution is this :

If you using LinQ2SQL in your project, Open your dbml file in Visual Studio and change Serialization Mode to "Unidirectional" on

R not finding package even after package installation

So the package will be downloaded in a temp folder C:\Users\U122337.BOSTONADVISORS\AppData\Local\Temp\Rtmp404t8Y\downloaded_packages from where it will be installed into your library folder, e.g. C:\R\library\zoo

What you have to do once install command is done: Open Packages menu -> Load package...

You will see your package on the list. You can automate this: How to load packages in R automatically?

"Prevent saving changes that require the table to be re-created" negative effects

The table is only dropped and re-created in cases where that's the only way SQL Server's Management Studio has been programmed to know how to do it.

There are certainly cases where it will do that when it doesn't need to, but there will also be cases where edits you make in Management Studio will not drop and re-create because it doesn't have to.

The problem is that enumerating all of the cases and determining which side of the line they fall on will be quite tedious.

This is why I like to use ALTER TABLE in a query window, instead of visual designers that hide what they're doing (and quite frankly have bugs) - I know exactly what is going to happen, and I can prepare for cases where the only possibility is to drop and re-create the table (which is some number less than how often SSMS will do that to you).

How to install beautiful soup 4 with python 2.7 on windows

Install pip

Download get-pip. Remember to save it as "get-pip.py"

Now go to the download folder. Right click on get-pip.py then open with python.exe.

You can add system variable by

(by doing this you can use pip and easy_install without specifying path)

1 Clicking on Properties of My Computer

2 Then chose Advanced System Settings

3 Click on Advanced Tab

4 Click on Environment Variables

5 From System Variables >>> select variable path.

6 Click edit then add the following lines at the end of it

 ;c:\Python27;c:\Python27\Scripts

(please dont copy this, just go to your python directory and copy the paths similar to this)

NB:- you have to do this once only.

Install beautifulsoup4

Open cmd and type

pip install beautifulsoup4

How to identify a strong vs weak relationship on ERD?

The relationship Room to Class is considered weak (non-identifying) because the primary key components CID and DATE of entity Class doesn't contain the primary key RID of entity Room (in this case primary key of Room entity is a single component, but even if it was a composite key, one component of it also fulfills the condition).

However, for instance, in the case of the relationship Class and Class_Ins we see that is a strong (identifying) relationship because the primary key components EmpID and CID and DATE of Class_Ins contains a component of the primary key Class (in this case it contains both components CID and DATE).

Should I use window.navigate or document.location in JavaScript?

window.navigate is NOT supported in some browsers, so that one should be avoided. Any of the other methods using the location property are the most reliable and consistent approach

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

force browsers to get latest js and css files in asp.net application

Starting from the above answer I modified a little bit the code to make the helper work with CSS files too and add a version every time when you do some change in the files and not only when you do the build

public static class HtmlHelperExtensions
{
    public static MvcHtmlString IncludeVersionedJs(this HtmlHelper helper, string filename)
    {
        string version = GetVersion(helper, filename);
        return MvcHtmlString.Create("<script type='text/javascript' src='" + filename + version + "'></script>");
    }

    public static MvcHtmlString IncludeVersionedCss(this HtmlHelper helper, string filename)
    {
        string version = GetVersion(helper, filename);
        return MvcHtmlString.Create("<link href='" + filename + version + "' type ='text/css' rel='stylesheet'/>");
    }

    private static string GetVersion(this HtmlHelper helper, string filename)
    {
        var context = helper.ViewContext.RequestContext.HttpContext;
        var physicalPath = context.Server.MapPath(filename);
        var version = "?v=" +
        new System.IO.FileInfo(physicalPath).LastWriteTime
        .ToString("yyyyMMddHHmmss");
        context.Cache.Add(physicalPath, version, null,
          DateTime.Now.AddMinutes(1), TimeSpan.Zero,
          CacheItemPriority.Normal, null);

        if (context.Cache[filename] == null)
        {
            context.Cache[filename] = version;
            return version;
        }
        else
        {
            if (version != context.Cache[filename].ToString())
            {
                context.Cache[filename] = version;
                return version;
            }
            return context.Cache[filename] as string;
        }
    }
}

How do I divide in the Linux console?

I still prefer using dc, which is an RPN calculator, so quick session to divide 67 by 18 with 4 digits precision would look like

>dc
4k
67
18/p
3.7222
q
>

Obviously, much more available: man dc

C++/CLI Converting from System::String^ to std::string

Check out System::Runtime::InteropServices::Marshal::StringToCoTaskMemUni() and its friends.

Sorry can't post code now; I don't have VS on this machine to check it compiles before posting.

How do you check if a certain index exists in a table?

If the hidden purpose of your question is to DROP the index before making INSERT to a large table, then this is useful one-liner:

DROP INDEX IF EXISTS [IndexName] ON [dbo].[TableName]

This syntax is available since SQL Server 2016. Documentation for IF EXISTS:

https://blogs.msdn.microsoft.com/sqlserverstorageengine/2015/11/03/drop-if-exists-new-thing-in-sql-server-2016/

In case you deal with a primery key instead, then use this:

ALTER TABLE [TableName] DROP CONSTRAINT IF EXISTS [PK_name] 

How to convert an array into an object using stdClass()

use this Tutorial

<?php
function objectToArray($d) {
        if (is_object($d)) {
            // Gets the properties of the given object
            // with get_object_vars function
            $d = get_object_vars($d);
        }

        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return array_map(__FUNCTION__, $d);
        }
        else {
            // Return array
            return $d;
        }
    }

    function arrayToObject($d) {
        if (is_array($d)) {
            /*
            * Return array converted to object
            * Using __FUNCTION__ (Magic constant)
            * for recursive call
            */
            return (object) array_map(__FUNCTION__, $d);
        }
        else {
            // Return object
            return $d;
        }
    }

        // Create new stdClass Object
    $init = new stdClass;

    // Add some test data
    $init->foo = "Test data";
    $init->bar = new stdClass;
    $init->bar->baaz = "Testing";
    $init->bar->fooz = new stdClass;
    $init->bar->fooz->baz = "Testing again";
    $init->foox = "Just test";

    // Convert array to object and then object back to array
    $array = objectToArray($init);
    $object = arrayToObject($array);

    // Print objects and array
    print_r($init);
    echo "\n";
    print_r($array);
    echo "\n";
    print_r($object);


//OUTPUT
    stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

Array
(
    [foo] => Test data
    [bar] => Array
        (
            [baaz] => Testing
            [fooz] => Array
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

stdClass Object
(
    [foo] => Test data
    [bar] => stdClass Object
        (
            [baaz] => Testing
            [fooz] => stdClass Object
                (
                    [baz] => Testing again
                )

        )

    [foox] => Just test
)

Reshaping data.frame from wide to long format

Since this answer is tagged with , I felt it would be useful to share another alternative from base R: stack.

Note, however, that stack does not work with factors--it only works if is.vector is TRUE, and from the documentation for is.vector, we find that:

is.vector returns TRUE if x is a vector of the specified mode having no attributes other than names. It returns FALSE otherwise.

I'm using the sample data from @Jaap's answer, where the values in the year columns are factors.

Here's the stack approach:

cbind(wide[1:2], stack(lapply(wide[-c(1, 2)], as.character)))
##    Code     Country values  ind
## 1   AFG Afghanistan 20,249 1950
## 2   ALB     Albania  8,097 1950
## 3   AFG Afghanistan 21,352 1951
## 4   ALB     Albania  8,986 1951
## 5   AFG Afghanistan 22,532 1952
## 6   ALB     Albania 10,058 1952
## 7   AFG Afghanistan 23,557 1953
## 8   ALB     Albania 11,123 1953
## 9   AFG Afghanistan 24,555 1954
## 10  ALB     Albania 12,246 1954

How can I convert string to double in C++?

atof and strtod do what you want but are very forgiving. If you don't want to accept strings like "32asd" as valid you need to wrap strtod in a function such as this:

#include <stdlib.h>
double strict_str2double(char* str)
{
    char* endptr;
    double value = strtod(str, &endptr);
    if (*endptr) return 0;
    return value;
}

RVM is not a function, selecting rubies with 'rvm use ...' will not work

My env is OSX Yosemite. Had the same issue .... solved by adding the following

1) edit and add the following line to .bash_profile file.

[[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm"

2) Restart terminal and try RVM command again

Should Gemfile.lock be included in .gitignore?

The real problem happens when you are working on an open-source Rails app that needs to have a configurable database adapter. I'm developing the Rails 3 branch of Fat Free CRM. My preference is postgres, but we want the default database to be mysql2.

In this case, Gemfile.lock still needs be checked in with the default set of gems, but I need to ignore changes that I have made to it on my machine. To accomplish this, I run:

git update-index --assume-unchanged Gemfile.lock

and to reverse:

git update-index --no-assume-unchanged Gemfile.lock

It is also useful to include something like the following code in your Gemfile. This loads the appropriate database adapter gem, based on your database.yml.

# Loads the database adapter gem based on config/database.yml (Default: mysql2)
# -----------------------------------------------------------------------------
db_gems = {"mysql2"     => ["mysql2", ">= 0.2.6"],
           "postgresql" => ["pg",     ">= 0.9.0"],
           "sqlite3"    => ["sqlite3"]}
adapter = if File.exists?(db_config = File.join(File.dirname(__FILE__),"config","database.yml"))
  db = YAML.load_file(db_config)
  # Fetch the first configured adapter from config/database.yml
  (db["production"] || db["development"] || db["test"])["adapter"]
else
  "mysql2"
end
gem *db_gems[adapter]
# -----------------------------------------------------------------------------

I can't say if this is an established best practice or not, but it works well for me.

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

How to Create a Form Dynamically Via Javascript

some thing as follows ::

Add this After the body tag

This is a rough sketch, you will need to modify it according to your needs.

<script>
var f = document.createElement("form");
f.setAttribute('method',"post");
f.setAttribute('action',"submit.php");

var i = document.createElement("input"); //input element, text
i.setAttribute('type',"text");
i.setAttribute('name',"username");

var s = document.createElement("input"); //input element, Submit button
s.setAttribute('type',"submit");
s.setAttribute('value',"Submit");

f.appendChild(i);
f.appendChild(s);

//and some more input elements here
//and dont forget to add a submit button

document.getElementsByTagName('body')[0].appendChild(f);

</script>

How to copy a file to another path?

string directoryPath = Path.GetDirectoryName(destinationFileName);

// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}

File.Copy(sourceFileName, destinationFileName);

How to NodeJS require inside TypeScript file?

The correct syntax is:

import sampleModule = require('modulename');

or

import * as sampleModule from 'modulename';

Then compile your TypeScript with --module commonjs.

If the package doesn't come with an index.d.ts file and its package.json doesn't have a "typings" property, tsc will bark that it doesn't know what 'modulename' refers to. For this purpose you need to find a .d.ts file for it on http://definitelytyped.org/, or write one yourself.

If you are writing code for Node.js you will also want the node.d.ts file from http://definitelytyped.org/.

Reading a column from CSV file using JAVA

If you are using Java 7+, you may want to use NIO.2, e.g.:

Code:

public static void main(String[] args) throws Exception {

    File file = new File("test.csv");

    List<String> lines = Files.readAllLines(file.toPath(), 
            StandardCharsets.UTF_8);

    for (String line : lines) {
        String[] array = line.split(",", -1);
        System.out.println(array[0]);
    }

}

Output:

a
1RW
1RW
1RW
1RW
1RW
1RW
1R1W
1R1W
1R1W

Git Clone: Just the files, please?

It sounds like you just want a copy of the source code. If so why not just copy the directory and exclude the .git directory from the copy?

JDBC connection to MSSQL server in windows authentication mode

Try following these steps:

  1. Add the integratedSecurity=true to JDBC URL like this:

    Url: jdbc:sqlserver://<<Server>>:<<Port>>;databasename=<<DatabaseName>>;integratedsecurity=true 
    
  2. Make sure to add the sqljdbc driver 4 or above version (sqljdbc.jar) in your project build path:

    java.sql.DatabaseMetaData metaData = connection.getMetaData();
    System.out.println("Driver version:" + metaData.getDriverVersion());
    
  3. Add the VM argument for your project:

    • Find the sqljdbc_auth.dll file from DB installed server (C:\Program Files\sqljdbc_4.0\enu\auth\x86), or download from this link.

    • Place the dll file in your project folder and specify the VM argument like this: VM Argument: -Djava.library.path="<<DLL File path till folder>>"

      NOTE: Check your java version 32/64 bit then add 32/64 bit version dll file accordingly.

Difference between npx and npm?

NPX:

From https://www.futurehosting.com/blog/npx-makes-life-easier-for-node-developers-plus-node-vulnerability-news/:

Web developers can have dozens of projects on their development machines, and each project has its own particular set of npm-installed dependencies. A few years back, the usual advice for dealing with CLI applications like Grunt or Gulp was to install them locally in each project and also globally so they could easily be run from the command line.

But installing globally caused as many problems as it solved. Projects may depend on different versions of command line tools, and polluting the operating system with lots of development-specific CLI tools isn’t great either. Today, most developers prefer to install tools locally and leave it at that.

Local versions of tools allow developers to pull projects from GitHub without worrying about incompatibilities with globally installed versions of tools. NPM can just install local versions and you’re good to go. But project specific installations aren’t without their problems: how do you run the right version of the tool without specifying its exact location in the project or playing around with aliases?

That’s the problem npx solves. A new tool included in NPM 5.2, npx is a small utility that’s smart enough to run the right application when it’s called from within a project.

If you wanted to run the project-local version of mocha, for example, you can run npx mocha inside the project and it will do what you expect.

A useful side benefit of npx is that it will automatically install npm packages that aren’t already installed. So, as the tool’s creator Kat Marchán points out, you can run npx benny-hill without having to deal with Benny Hill polluting the global environment.

If you want to take npx for a spin, update to the most recent version of npm.

Parsing Json rest api response in C#

1> Add this namspace. using Newtonsoft.Json.Linq;

2> use this source code.

JObject joResponse = JObject.Parse(response);                   
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());

Delete multiple rows by selecting checkboxes using PHP

 $deleted = $_POST['checkbox'];
 $sql = "DELETE FROM $tbl_name WHERE id IN (".implode(",", $deleted ) . ")";

How is a CSS "display: table-column" supposed to work?

The "table-column" display type means it acts like the <col> tag in HTML - i.e. an invisible element whose width* governs the width of the corresponding physical column of the enclosing table.

See the W3C standard for more information about the CSS table model.

* And a few other properties like borders, backgrounds.

Android Gradle plugin 0.7.0: "duplicate files during packaging of APK"

In my case I had to include several additional exclusions. It appears it doesn't like Regular expressions which would've made this a nice one-liner.

android {
    packagingOptions {
        exclude 'META-INF/DEPENDENCIES.txt'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/dependencies.txt'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/license.txt'
        exclude 'META-INF/LGPL2.1'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/notice.txt'
    }
}

Pagination response payload from a RESTful API

just add in your backend API new property's into response body. from example .net core:

[Authorize]
[HttpGet]
public async Task<IActionResult> GetUsers([FromQuery]UserParams userParams)
{
  var users = await _repo.GetUsers(userParams);
  var usersToReturn = _mapper.Map<IEnumerable<UserForListDto>>(users);


  // create new object and add into it total count param etc
  var UsersListResult = new
  {
    usersToReturn,
    currentPage = users.CurrentPage,
    pageSize = users.PageSize,
    totalCount = users.TotalCount,
    totalPages = users.TotalPages
  };

  return Ok(UsersListResult);
}

In body response it look like this

{
"usersToReturn": [
    {
        "userId": 1,
        "username": "[email protected]",
        "firstName": "Joann",
        "lastName": "Wilson",
        "city": "Armstrong",
        "phoneNumber": "+1 (893) 515-2172"
    },
    {
        "userId": 2,
        "username": "[email protected]",
        "firstName": "Booth",
        "lastName": "Drake",
        "city": "Franks",
        "phoneNumber": "+1 (800) 493-2168"
    }
],
// metadata to pars in client side
"currentPage": 1,
"pageSize": 2,
"totalCount": 87,
"totalPages": 44

}

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

I found a faster way to solve the problem, at least on realistically large datasets using: df.set_index(KEY).to_dict()[VALUE]

Proof on 50,000 rows:

df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']

Output:

100 loops, best of 3: 7.04 ms per loop  # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop  # Jeff
100 loops, best of 3: 4.28 ms per loop  # Kikohs (me)

Simple export and import of a SQLite database on Android

To export db rather it is SQLITE or ROOM:

Firstly, add this permission in AndroidManifest.xml file:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

Secondly, we drive to code the db functions:

private void exportDB() {
    try {
        File dbFile = new File(this.getDatabasePath(DATABASE_NAME).getAbsolutePath());
        FileInputStream fis = new FileInputStream(dbFile);

        String outFileName = DirectoryName + File.separator +
                DATABASE_NAME + ".db";

        // Open the empty db as the output stream
        OutputStream output = new FileOutputStream(outFileName);

        // Transfer bytes from the inputfile to the outputfile
        byte[] buffer = new byte[1024];
        int length;
        while ((length = fis.read(buffer)) > 0) {
            output.write(buffer, 0, length);
        }
        // Close the streams
        output.flush();
        output.close();
        fis.close();


    } catch (IOException e) {
        Log.e("dbBackup:", e.getMessage());
    }
}

Create Folder on Daily basis with name of folder is Current date:

public void createBackup() {

    sharedPref = getSharedPreferences("dbBackUp", MODE_PRIVATE);
    editor = sharedPref.edit();

    String dt = sharedPref.getString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));

    if (dt != new SimpleDateFormat("dd-MM-yy").format(new Date())) {
        editor.putString("dt", new SimpleDateFormat("dd-MM-yy").format(new Date()));

        editor.commit();
    }

    File folder = new File(Environment.getExternalStorageDirectory() + File.separator + "BackupDBs");
    boolean success = true;
    if (!folder.exists()) {
        success = folder.mkdirs();
    }
    if (success) {

        DirectoryName = folder.getPath() + File.separator + sharedPref.getString("dt", "");
        folder = new File(DirectoryName);
        if (!folder.exists()) {
            success = folder.mkdirs();
        }
        if (success) {
            exportDB();
        }
    } else {
        Toast.makeText(this, "Not create folder", Toast.LENGTH_SHORT).show();
    }

}

Assign the DATABASE_NAME without .db extension and its data type is string

Loop Through Each HTML Table Column and Get the Data using jQuery

Using a nested .each() means that your inner loop is doing one td at a time, so you can't set the productId and product and quantity all in the inner loop.

Also using function(key, val) and then val[key].innerHTML isn't right: the .each() method passes the index (an integer) and the actual element, so you'd use function(i, element) and then element.innerHTML. Though jQuery also sets this to the element, so you can just say this.innerHTML.

Anyway, here's a way to get it to work:

    table.find('tr').each(function (i, el) {
        var $tds = $(this).find('td'),
            productId = $tds.eq(0).text(),
            product = $tds.eq(1).text(),
            Quantity = $tds.eq(2).text();
        // do something with productId, product, Quantity
    });

Demo: http://jsfiddle.net/bqX7Q/

Drop-down box dependent on the option selected in another drop-down box

I am posting this answer because in this way you will never need any plugin like jQuery and any other, This has the solution by simple javascript.

<html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <script language="javascript" type="text/javascript">
    function dynamicdropdown(listindex)
    {
        switch (listindex)
        {
        case "manual" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            break;
        case "online" :
            document.getElementById("status").options[0]=new Option("Select status","");
            document.getElementById("status").options[1]=new Option("OPEN","open");
            document.getElementById("status").options[2]=new Option("DELIVERED","delivered");
            document.getElementById("status").options[3]=new Option("SHIPPED","shipped");
            break;
        }
        return true;
    }
    </script>
    </head>
    <title>Dynamic Drop Down List</title>
    <body>
    <div class="category_div" id="category_div">Source:
        <select id="source" name="source" onchange="javascript: dynamicdropdown(this.options[this.selectedIndex].value);">
        <option value="">Select source</option>
        <option value="manual">MANUAL</option>
        <option value="online">ONLINE</option>
        </select>
    </div>
    <div class="sub_category_div" id="sub_category_div">Status:
        <script type="text/javascript" language="JavaScript">
        document.write('<select name="status" id="status"><option value="">Select status</option></select>')
        </script>
        <noscript>
        <select id="status" name="status">
            <option value="open">OPEN</option>
            <option value="delivered">DELIVERED</option>
        </select>
        </noscript>
    </div>
    </body>
</html>

For more details, I mean to make dynamic and more dependency please take a look at my article create dynamic drop-down list

CLEAR SCREEN - Oracle SQL Developer shortcut?

To clear the SQL window you can use:

clear screen;

which can also be shortened to

cl scr;

Browser: Identifier X has already been declared

I had a very close issue but in my case, it was Identifier 'e' has already been declared.

In my case caused because of using try {} catch (e) { var e = ... } where letter e is generated via minifier (uglifier).

So better solution could be use catch(ex){} (ex as an Excemption)

Hope somebody who searched with the similar question could find this question helpful.

How to download file from database/folder using php

butangDonload.php

$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;    

Try this,

<?php

$name=$_SESSION['name'];
download($name);

function download($name){
$file = $nama_fail;
?>

Java Could not reserve enough space for object heap error

If you go thru this IBM link on java, it says that on 32 bit windows the recommended heap size is 1.5 GB and the Maximum heap size is 1.8 GB. So your jvm does not gets initialized for -Xmx2G and above.

Also if you go thru this SO answer, clearly the DLL bindings are an issue for memory reservation changing which is no trivial task. Hence what may be recommended is that you go for 64-bit Windows and a 64-bit JVM. while it will chew up more RAM, you will have much more contiguous virtual address space.

How to change position of Toast in Android?

setting toast at topin screen

toast.setView(view);
toast.setGravity(Gravity.BOTTOM , 0, 0); // here i am setting toast at bottom
 toast.setDuration(Toast.LENGTH_LONG);
 toast.show(); 

now at bottom

 toast.setView(view);
 toast.setGravity(Gravity.BOTTOM , 0, 0); // here i am setting toast at bottom
 toast.setDuration(Toast.LENGTH_LONG);
 toast.show();  

the same way we can set toast in left, right and also center

Click here

addEventListener not working in IE8

Mayb it's easier (and has more performance) if you delegate the event handling to another element, for example your table

$('idOfYourTable').on("click", "input:checkbox", function(){

});

in this way you will have only one event handler, and this will work also for newly added elements. This requires jQuery >= 1.7

Otherwise use delegate()

$('idOfYourTable').delegate("input:checkbox", "click", function(){

});

Set a thin border using .css() in javascript

Current Example:

You need to define border-width:1px

Your code should read:

$(this).css({"border-color": "#C1E0FF", 
             "border-width":"1px", 
             "border-style":"solid"});

Suggested Example:

You should ideally use a class and addClass/removeClass

$(this).addClass('borderClass'); $(this).removeClass('borderClass');

and in your CSS:

.borderClass{
  border-color: #C1E0FF;
  border-width:1px;
  border-style: solid;
  /** OR USE INLINE
  border: 1px solid #C1E0FF;
  **/
}

jsfiddle working example: http://jsfiddle.net/gorelative/tVbvF/\

jsfiddle with animate: http://jsfiddle.net/gorelative/j9Xxa/ This just gives you an example of how it could work, you should get the idea.. There are better ways of doing this most likely.. like using a toggle()

How to store custom objects in NSUserDefaults

Swift 3

class MyObject: NSObject, NSCoding  {
    let name : String
    let url : String
    let desc : String

    init(tuple : (String,String,String)){
        self.name = tuple.0
        self.url = tuple.1
        self.desc = tuple.2
    }
    func getName() -> String {
        return name
    }
    func getURL() -> String{
        return url
    }
    func getDescription() -> String {
        return desc
    }
    func getTuple() -> (String, String, String) {
        return (self.name,self.url,self.desc)
    }

    required init(coder aDecoder: NSCoder) {
        self.name = aDecoder.decodeObject(forKey: "name") as? String ?? ""
        self.url = aDecoder.decodeObject(forKey: "url") as? String ?? ""
        self.desc = aDecoder.decodeObject(forKey: "desc") as? String ?? ""
    }

    func encode(with aCoder: NSCoder) {
        aCoder.encode(self.name, forKey: "name")
        aCoder.encode(self.url, forKey: "url")
        aCoder.encode(self.desc, forKey: "desc")
    }
    }

to store and retrieve:

func save() {
            let data  = NSKeyedArchiver.archivedData(withRootObject: object)
            UserDefaults.standard.set(data, forKey:"customData" )
        }
        func get() -> MyObject? {
            guard let data = UserDefaults.standard.object(forKey: "customData") as? Data else { return nil }
            return NSKeyedUnarchiver.unarchiveObject(with: data) as? MyObject
        }

How to view DB2 Table structure

In DB2, enter on db2 command prompt.

  db2  =>  describe  table MyTableName

What are some good SSH Servers for windows?

copssh - OpenSSH for Windows

http://www.itefix.no/i2/copssh

Packages essential Cygwin binaries.

The differences between initialize, define, declare a variable

"So does it mean definition equals declaration plus initialization."

Not necessarily, your declaration might be without any variable being initialized like:

 void helloWorld(); //declaration or Prototype.

 void helloWorld()
 {
    std::cout << "Hello World\n";
 } 

converting string to long in python

longcan only take string convertibles which can end in a base 10 numeral. So, the decimal is causing the harm. What you can do is, float the value before calling the long. If your program is on Python 2.x where int and long difference matters, and you are sure you are not using large integers, you could have just been fine with using int to provide the key as well.

So, the answer is long(float('234.89')) or it could just be int(float('234.89')) if you are not using large integers. Also note that this difference does not arise in Python 3, because int is upgraded to long by default. All integers are long in python3 and call to covert is just int

How to add ID property to Html.BeginForm() in asp.net mvc?

In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details

BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)

Means you should use like this :

Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)

So, it worked in MVC 4

@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
    new { @id = "signupform" }))
{
    <input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
    <input type="submit" value="Create" id="btnSubmit" />
}

How to get element by classname or id

@tasseKATT's Answer is great, but if you don't want to make a directive, why not use $document?

.controller('ExampleController', ['$scope', '$document', function($scope, $document) {
  var dumb = function (id) {
  var queryResult = $document[0].getElementById(id)
  var wrappedID = angular.element(queryResult);
  return wrappedID;
};

PLUNKR

"Not allowed to load local resource: file:///C:....jpg" Java EE Tomcat

The concept of http location and disk location is different. What you need to do is:

  1. for uploaded file summer.jpg
  2. move that under a known (to the application) location to disk, e.g c:\images\summer.jpg
  3. insert into db record representing the image with text summer.jpg
  4. to display it use plain <img src="images/summer.jpg" />
  5. you need something (e.g apache) that will serve c:\images\ under your application's /images. If you cannot do this then in step #2 you need to save somewhere under your web root, e.g c:\my-applications\demo-app\build\images

PostgreSQL: FOREIGN KEY/ON DELETE CASCADE

In my humble experience with postgres 9.6, cascade delete doesn't work in practice for tables that grow above a trivial size.

  • Even worse, while the delete cascade is going on, the tables involved are locked so those tables (and potentially your whole database) is unusable.
  • Still worse, it's hard to get postgres to tell you what it's doing during the delete cascade. If it's taking a long time, which table or tables is making it slow? Perhaps it's somewhere in the pg_stats information? It's hard to tell.

HttpListener Access Denied

Can I make it run without admin mode? if yes how? If not how can I make the app change to admin mode after start running?

You can't, it has to start with elevated privileges. You can restart it with the runas verb, which will prompt the user to switch to admin mode

static void RestartAsAdmin()
{
    var startInfo = new ProcessStartInfo("yourApp.exe") { Verb = "runas" };
    Process.Start(startInfo);
    Environment.Exit(0);
}

EDIT: actually, that's not true; HttpListener can run without elevated privileges, but you need to give permission for the URL on which you want to listen. See Darrel Miller's answer for details.

How to add 20 minutes to a current date?

Add it in milliseconds:

var currentDate = new Date();
var twentyMinutesLater = new Date(currentDate.getTime() + (20 * 60 * 1000));

Boxplot show the value of mean

First, you can calculate the group means with aggregate:

means <- aggregate(weight ~  group, PlantGrowth, mean)

This dataset can be used with geom_text:

library(ggplot2)
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) + geom_boxplot() +
  stat_summary(fun.y=mean, colour="darkred", geom="point", 
               shape=18, size=3,show_guide = FALSE) + 
  geom_text(data = means, aes(label = weight, y = weight + 0.08))

Here, + 0.08 is used to place the label above the point representing the mean.

enter image description here


An alternative version without ggplot2:

means <- aggregate(weight ~  group, PlantGrowth, mean)

boxplot(weight ~ group, PlantGrowth)
points(1:3, means$weight, col = "red")
text(1:3, means$weight + 0.08, labels = means$weight)

enter image description here

RESTful API methods; HEAD & OPTIONS

OPTIONS method returns info about API (methods/content type)

HEAD method returns info about resource (version/length/type)

Server response

OPTIONS

HTTP/1.1 200 OK
Allow: GET,HEAD,POST,OPTIONS,TRACE
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:24:43 GMT
Content-Length: 0

HEAD

HTTP/1.1 200 OK
Accept-Ranges: bytes
Content-Type: text/html; charset=UTF-8
Date: Wed, 08 May 2013 10:12:29 GMT
ETag: "780602-4f6-4db31b2978ec0"
Last-Modified: Thu, 25 Apr 2013 16:13:23 GMT
Content-Length: 1270
  • OPTIONS Identifying which HTTP methods a resource supports, e.g. can we DELETE it or update it via a PUT?
  • HEAD Checking whether a resource has changed. This is useful when maintaining a cached version of a resource
  • HEAD Retrieving metadata about the resource, e.g. its media type or its size, before making a possibly costly retrieval
  • HEAD, OPTIONS Testing whether a resource exists and is accessible. For example, validating user-submitted links in an application

Here is nice and concise article about how HEAD and OPTIONS fit into RESTful architecture.