Programs & Examples On #Last insert id

LAST_INSERT_ID is MySQL specific functionality to get the value of the AUTO_INCREMENT column most recently inserted into. It is the recommended means of getting the value in MySQL, because SELECT MAX(auto_increment) ... is not reliable, as concurrency problems can occur.

LAST_INSERT_ID() MySQL

I had the same problem in bash and i'm doing something like this:

mysql -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');"

which works fine:-) But

mysql -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');set @last_insert_id = LAST_INSERT_ID();"
mysql -D "dbname" -e "insert into table2 (id_tab1) values (@last_insert_id);"

don't work. Because after the first command, the shell will be logged out from mysql and logged in again for the second command, and then the variable @last_insert_id isn't set anymore. My solution is:

lastinsertid=$(mysql -B -N -D "dbname" -e "insert into table1 (myvalue) values ('${foo}');select LAST_INSERT_ID();")
mysql -D "dbname" -e "insert into table2 (id_tab1) values (${lastinsertid});"

Maybe someone is searching for a solution an bash :-)

Node.js Write a line into a .txt file

I did a log file which prints data into text file using "Winston" log. The source code is here below,

const { createLogger, format, transports } = require('winston');
var fs = require('fs')
var logger = fs.createWriteStream('Data Log.txt', {`
flags: 'a' 
})
const os = require('os');
var sleep = require('system-sleep');
var endOfLine = require('os').EOL;
var t = '             ';var s = '         ';var q = '               ';
var array1=[];
var array2=[];
var array3=[];
var array4=[];

array1[0]  =  78;`
array1[1]  =  56;
array1[2]  =  24;
array1[3]  =  34;

for (var n=0;n<4;n++)
{
array2[n]=array1[n].toString();
}

for (var k=0;k<4;k++)
{
array3[k]=Buffer.from('                    ');
}

for (var a=0;a<4;a++)  
{
array4[a]=Buffer.from(array2[a]);
}

for (m=0;m<4;m++)
{
array4[m].copy(array3[m],0);
}

logger.write('Date'+q);
logger.write('Time'+(q+'  '))
logger.write('Data 01'+t);
logger.write('Data 02'+t); 
logger.write('Data 03'+t);
logger.write('Data 04'+t)

logger.write(endOfLine);
logger.write(endOfLine);
enter code here`enter code here`
}

function mydata()      //user defined function
{
logger.write(datechar+s);
logger.write(timechar+s);
for ( n = 0; n < 4; n++) 
{
logger.write(array3[n]);
}
logger.write(endOfLine); 
}

for (;;)
}
var now = new Date();
var dateFormat = require('dateformat');
var date = dateFormat(now,"isoDate");
var time = dateFormat(now, "h:MM:ss TT ");
var datechar = date.toString();
var timechar = time.toString();
mydata();
sleep(5*1000);
}

How can I take a screenshot with Selenium WebDriver?

Java

I could not get the accepted answer to work, but as per the current WebDriver documentation, the following worked fine for me with Java 7 on OS X v10.9 (Mavericks):

import java.io.File;
import java.net.URL;

import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;

public class Testing {

   public void myTest() throws Exception {
       WebDriver driver = new RemoteWebDriver(
               new URL("http://localhost:4444/wd/hub"),
               DesiredCapabilities.firefox());

       driver.get("http://www.google.com");

       // RemoteWebDriver does not implement the TakesScreenshot class
       // if the driver does have the Capabilities to take a screenshot
       // then Augmenter will add the TakesScreenshot methods to the instance
       WebDriver augmentedDriver = new Augmenter().augment(driver);
       File screenshot = ((TakesScreenshot)augmentedDriver).
               getScreenshotAs(OutputType.FILE);
   }
}

Input length must be multiple of 16 when decrypting with padded cipher

This is a very old question, but my answer may help someone.

  • In the encrypt method, don't forget to encode your string to Base64
  • In the decrypt method, don't forget to decode your string to Base64

Below is the working code

    import java.util.Arrays;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    public class EncryptionDecryptionUtil {

    public static String encrypt(final String secret, final String data) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while encrypting data", e);
        }

    }

    public static String decrypt(final String secret,
            final String encryptedString) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.DECRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
            return new String(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while decrypting data", e);
        }
    }


    public static void main(String[] args) {

        String data = "This is not easy as you think";
        String key = "---------------------------------";
        String encrypted = encrypt(key, data);
        System.out.println(encrypted);
        System.out.println(decrypt(key, encrypted));
      }
  }

For Generating Key you can use below class

    import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyGenerator {

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

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();
        int keyBitSize = 256;
        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();

 System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
    }

}

Get program execution time in the shell

Use the built-in time keyword:

$ help time

time: time [-p] PIPELINE
    Execute PIPELINE and print a summary of the real time, user CPU time,
    and system CPU time spent executing PIPELINE when it terminates.
    The return status is the return status of PIPELINE.  The `-p' option
    prints the timing summary in a slightly different format.  This uses
    the value of the TIMEFORMAT variable as the output format.

Example:

$ time sleep 2
real    0m2.009s
user    0m0.000s
sys     0m0.004s

Of Countries and their Cities

You can use database from here -

http://myip.ms/info/cities_sql_database/

CREATE TABLE `cities` (
  `cityID` mediumint(8) unsigned NOT NULL AUTO_INCREMENT,
  `cityName` varchar(50) NOT NULL,
  `stateID` smallint(5) unsigned NOT NULL DEFAULT '0',
  `countryID` varchar(3) NOT NULL DEFAULT '',
  `language` varchar(10) NOT NULL DEFAULT '',
  `latitude` double NOT NULL DEFAULT '0',
  `longitude` double NOT NULL DEFAULT '0',
  PRIMARY KEY (`cityID`),
  UNIQUE KEY `unq` (`countryID`,`stateID`,`cityID`),
  KEY `cityName` (`cityName`),
  KEY `stateID` (`stateID`),
  KEY `countryID` (`countryID`),
  KEY `latitude` (`latitude`),
  KEY `longitude` (`longitude`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

using batch echo with special characters

Here's one more approach by using SET and FOR /F

@echo off

set "var=<?xml version="1.0" encoding="utf-8" ?>"

for /f "tokens=1* delims==" %%a in ('set var') do echo %%b

and you can beautify it like:

@echo off
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
set "print{[=for /f "tokens=1* delims==" %%a in ('set " & set "]}=') do echo %%b"
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::


set "xml_line.1=<?xml version="1.0" encoding="utf-8" ?>"
set "xml_line.2=<root>"
set "xml_line.3=</root>"

%print{[% xml_line %]}%

Sum rows in data.frame or matrix

The rowSums function (as Greg mentions) will do what you want, but you are mixing subsetting techniques in your answer, do not use "$" when using "[]", your code should look something more like:

data$new <- rowSums( data[,43:167] )

If you want to use a function other than sum, then look at ?apply for applying general functions accross rows or columns.

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
{ 
    [DllImport("User32.Dll")]
    public static extern long SetCursorPos(int x, int y);

    [DllImport("User32.Dll")]
    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;

        public POINT(int X, int Y)
        {
            x = X;
            y = Y;
        }
    }
}

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

How to get longitude and latitude of any address?

I came up with the following which takes account of rubbish passed in and file_get_contents failing....

function get_lonlat(  $addr  ) {
    try {
            $coordinates = @file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?address=' . urlencode($addr) . '&sensor=true');
            $e=json_decode($coordinates);
            // call to google api failed so has ZERO_RESULTS -- i.e. rubbish address...
            if ( isset($e->status)) { if ( $e->status == 'ZERO_RESULTS' ) {echo '1:'; $err_res=true; } else {echo '2:'; $err_res=false; } } else { echo '3:'; $err_res=false; }
            // $coordinates is false if file_get_contents has failed so create a blank array with Longitude/Latitude.
            if ( $coordinates == false   ||  $err_res ==  true  ) {
                $a = array( 'lat'=>0,'lng'=>0);
                $coordinates  = new stdClass();
                foreach (  $a  as $key => $value)
                {
                    $coordinates->$key = $value;
                }
            } else {
                // call to google ok so just return longitude/latitude.
                $coordinates = $e;

                $coordinates  =  $coordinates->results[0]->geometry->location;
            }

            return $coordinates;
    }
    catch (Exception $e) {
    }

then to get the cords: where $pc is the postcode or address.... $address = get_lonlat( $pc ); $l1 = $address->lat; $l2 = $address->lng;

How to update and order by using ms sql

I have to offer this as a better approach - you don't always have the luxury of an identity field:

UPDATE m
SET [status]=10
FROM (
  Select TOP (10) *
  FROM messages
  WHERE [status]=0
  ORDER BY [priority] DESC
) m

You can also make the sub-query as complicated as you want - joining multiple tables, etc...

Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the messages table. It can be used to update the top N rows from any table, even if that table has no unique key at all.

Five equal columns in twitter bootstrap

Below is a combo of @machineaddict and @Mafnah answers, re-written for Bootstrap 3 (working well for me so far):

@media (min-width: 768px){
    .fivecolumns .col-md-2, .fivecolumns .col-sm-2, .fivecolumns .col-lg-2  {
        width: 20%;
        *width: 20%;
    }
}
@media (min-width: 1200px) {
    .fivecolumns .col-md-2, .fivecolumns .col-sm-2, .fivecolumns .col-lg-2 {
        width: 20%;
        *width: 20%;
    }
}
@media (min-width: 768px) and (max-width: 979px) {
    .fivecolumns .col-md-2, .fivecolumns .col-sm-2, .fivecolumns .col-lg-2 {
        width: 20%;
        *width: 20%;
    }
}

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

android.os.NetworkOnMainThreadException with android 4.2

Write below code into your MainActivity file after setContentView(R.layout.activity_main);

if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

And below import statement into your java file.

import android.os.StrictMode;

Using node.js as a simple web server

I found a interesting library on npm that might be of some use to you. It's called mime(npm install mime or https://github.com/broofa/node-mime) and it can determine the mime type of a file. Here's an example of a webserver I wrote using it:

var mime = require("mime"),http = require("http"),fs = require("fs");
http.createServer(function (req, resp) {
path  = unescape(__dirname + req.url)
var code = 200
 if(fs.existsSync(path)) {
    if(fs.lstatSync(path).isDirectory()) {
        if(fs.existsSync(path+"index.html")) {
        path += "index.html"
        } else {
            code = 403
            resp.writeHead(code, {"Content-Type": "text/plain"});
            resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
        }
    }
    resp.writeHead(code, {"Content-Type": mime.lookup(path)})
    fs.readFile(path, function (e, r) {
    resp.end(r);

})
} else {
    code = 404
    resp.writeHead(code, {"Content-Type":"text/plain"});
    resp.end(code+" "+http.STATUS_CODES[code]+" "+req.url);
}
console.log("GET "+code+" "+http.STATUS_CODES[code]+" "+req.url)
}).listen(9000,"localhost");
console.log("Listening at http://localhost:9000")

This will serve any regular text or image file (.html, .css, .js, .pdf, .jpg, .png, .m4a and .mp3 are the extensions I've tested, but it theory it should work for everything)

Developer Notes

Here is an example of output that I got with it:

Listening at http://localhost:9000
GET 200 OK /cloud
GET 404 Not Found /cloud/favicon.ico
GET 200 OK /cloud/icon.png
GET 200 OK /
GET 200 OK /501.png
GET 200 OK /cloud/manifest.json
GET 200 OK /config.log
GET 200 OK /export1.png
GET 200 OK /Chrome3DGlasses.pdf
GET 200 OK /cloud
GET 200 OK /-1
GET 200 OK /Delta-Vs_for_inner_Solar_System.svg

Notice the unescape function in the path construction. This is to allow for filenames with spaces and encoded characters.

Unable to import path from django.urls

You need Django version 2

pip install --upgrade django
pip3 install --upgrade django

python -m django --version # 2.0.2
python3 -m django --version # 2.0.2

C# Checking if button was clicked

These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.

if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
   //Do not reload the gridview.

}
else
{
   reload my gridview.
}

SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked

What are the best JVM settings for Eclipse?

Here's my own setting for my Eclipse running on i7 2630M 16GB RAM laptop, this setting has been using for a week, without a single crashing, and Eclipse 3.7 is running smoothly.

-startup
plugins/org.eclipse.equinox.launcher_1.2.0.v20110502.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.100.v20110502
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
256M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms1024m
-Xmx4096m 
-XX:MaxPermSize=256m

Calculations: For Win 7 x64

  • Xms = Physical Memory / 16
  • Xmx = Physical Memory / 4
  • MaxPermSize = Same as default value, which is 256m

Get docker container id from container name

I tried sudo docker container stats, and it will give out Container ID along with details of memory usage and Name, etc. If you want to stop viewing the process, do Ctrl+C. I hope you find it useful.

jQuery getJSON save result into variable

$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO best is to call the callback function. which is nicer to eyes, readability aspects.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

Using GroupBy, Count and Sum in LINQ Lambda Expressions

var boxSummary = from b in boxes
                 group b by b.Owner into g
                 let nrBoxes = g.Count()
                 let totalWeight = g.Sum(w => w.Weight)
                 let totalVolume = g.Sum(v => v.Volume)
                 select new { Owner = g.Key, Boxes = nrBoxes,
                              TotalWeight = totalWeight,
                              TotalVolume = totalVolume }

What is this date format? 2011-08-12T20:17:46.384Z

There are other ways to parse it rather than the first answer. To parse it:

(1) If you want to grab information about date and time, you can parse it to a ZonedDatetime(since Java 8) or Date(old) object:

// ZonedDateTime's default format requires a zone ID(like [Australia/Sydney]) in the end.
// Here, we provide a format which can parse the string correctly.
DateTimeFormatter dtf = DateTimeFormatter.ISO_DATE_TIME;
ZonedDateTime zdt = ZonedDateTime.parse("2011-08-12T20:17:46.384Z", dtf);

or

// 'T' is a literal.
// 'X' is ISO Zone Offset[like +01, -08]; For UTC, it is interpreted as 'Z'(Zero) literal.
String pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSX";

// since no built-in format, we provides pattern directly.
DateFormat df = new SimpleDateFormat(pattern);

Date myDate = df.parse("2011-08-12T20:17:46.384Z");

(2) If you don't care the date and time and just want to treat the information as a moment in nanoseconds, then you can use Instant:

// The ISO format without zone ID is Instant's default.
// There is no need to pass any format.
Instant ins = Instant.parse("2011-08-12T20:17:46.384Z");

PHP mkdir: Permission denied problem

After you install the ftp server with sudo apt-get install vsftpd you will have to configure it. To enable write access you have to edit the /etc/vsftpd.conf file and uncomment the

#write_enable=YES

line, so it should read

write_enable=YES

Save the file and restart vsftpd with sudo service vsftpd restart.

For other configuration options consult this documentation or man vsftpd.conf

How to create an empty file with Ansible?

In order to create a file in the remote machine with the ad-hoc command

ansible client -m file -a"dest=/tmp/file state=touch"

Please correct me if I am wrong

Java and SQLite

I understand you asked specifically about SQLite, but maybe HSQL database would be a better fit with Java. It is written in Java itself, runs in the JVM, supports in-memory tables etc. and all that features make it quite usable for prototyping and unit-testing.

center a row using Bootstrap 3

I know this question was specifically targeted at Bootstrap 3, but in case Bootstrap 4 users stumble upon this question, here is how i centered rows in v4:

<div class="container">
  <div class="row justify-content-center">
  ...

More related to this topic can be found on bootstrap site.

Get HTML code using JavaScript with a URL

There is a tutorial on how to use Ajax here: https://www.w3schools.com/xml/ajax_intro.asp

This is an example code taken from that tutorial:

<html>

<head>
    <script type="text/javascript">
        function loadXMLDoc()
        {
            var xmlhttp;
            if (window.XMLHttpRequest)
            {
              // Code for Internet Explorer 7+, Firefox, Chrome, Opera, and Safari
              xmlhttp = new XMLHttpRequest();
            }
            else
            {
                // Code for Internet Explorer 6 and Internet Explorer 5
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            xmlhttp.onreadystatechange=function()
            {
                if (xmlhttp.readyState==4 && xmlhttp.status==200)
                {
                    document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
                }
            }
            xmlhttp.open("GET", "ajax_info.txt", true);
            xmlhttp.send();
        }
    </script>
</head>

<body>
    <div id="myDiv"><h2>Let AJAX change this text</h2></div>
    <button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>

</html>

Representing null in JSON

According to the JSON spec, the outermost container does not have to be a dictionary (or 'object') as implied in most of the comments above. It can also be a list or a bare value (i.e. string, number, boolean or null). If you want to represent a null value in JSON, the entire JSON string (excluding the quotes containing the JSON string) is simply null. No braces, no brackets, no quotes. You could specify a dictionary containing a key with a null value ({"key1":null}), or a list with a null value ([null]), but these are not null values themselves - they are proper dictionaries and lists. Similarly, an empty dictionary ({}) or an empty list ([]) are perfectly fine, but aren't null either.

In Python:

>>> print json.loads('{"key1":null}')
{u'key1': None}
>>> print json.loads('[null]')
[None]
>>> print json.loads('[]')
[]
>>> print json.loads('{}')
{}
>>> print json.loads('null')
None

What does enumerate() mean?

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

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

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

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

   # Do something with the other `value`

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

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

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

Example:

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

Output:

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

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

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

The name 'controlname' does not exist in the current context

1) Check the CodeFile property in <%@Page CodeFile="filename.aspx.cs" %> in "filename.aspx" page , your Code behind file name and this Property name should be same.

2)you may miss runat="server" in code

Converting String to Cstring in C++

string name;
char *c_string;

getline(cin, name);

c_string = new char[name.length()];

for (int index = 0; index < name.length(); index++){
    c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
                              // the char array

I know this is not the predefined method but thought it may be useful to someone nevertheless.

Correct way to try/except using Python requests module?

Have a look at the Requests exception docs. In short:

In the event of a network problem (e.g. DNS failure, refused connection, etc), Requests will raise a ConnectionError exception.

In the event of the rare invalid HTTP response, Requests will raise an HTTPError exception.

If a request times out, a Timeout exception is raised.

If a request exceeds the configured number of maximum redirections, a TooManyRedirects exception is raised.

All exceptions that Requests explicitly raises inherit from requests.exceptions.RequestException.

To answer your question, what you show will not cover all of your bases. You'll only catch connection-related errors, not ones that time out.

What to do when you catch the exception is really up to the design of your script/program. Is it acceptable to exit? Can you go on and try again? If the error is catastrophic and you can't go on, then yes, you may abort your program by raising SystemExit (a nice way to both print an error and call sys.exit).

You can either catch the base-class exception, which will handle all cases:

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.RequestException as e:  # This is the correct syntax
    raise SystemExit(e)

Or you can catch them separately and do different things.

try:
    r = requests.get(url, params={'s': thing})
except requests.exceptions.Timeout:
    # Maybe set up for a retry, or continue in a retry loop
except requests.exceptions.TooManyRedirects:
    # Tell the user their URL was bad and try a different one
except requests.exceptions.RequestException as e:
    # catastrophic error. bail.
    raise SystemExit(e)

As Christian pointed out:

If you want http errors (e.g. 401 Unauthorized) to raise exceptions, you can call Response.raise_for_status. That will raise an HTTPError, if the response was an http error.

An example:

try:
    r = requests.get('http://www.google.com/nothere')
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

Will print:

404 Client Error: Not Found for url: http://www.google.com/nothere

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

Assign keyboard shortcut to run procedure

F function keys (F1,F2,F3,F4,F5 etc.) can be assigned to macros with the following codes :

Sub A_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\a1.wav", 0)
End Sub

Sub B_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\b1.wav", 0)
End Sub

Sub C_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\c1.wav", 0)
End Sub

Sub D_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\d1.wav", 0)
End Sub

Sub E_1()
    Call sndPlaySound32(ThisWorkbook.Path & "\e1.wav", 0)
End Sub


Sub auto_open()
    Application.OnKey "{F1}", "A_1"
    Application.OnKey "{F2}", "B_1"
    Application.OnKey "{F3}", "C_1"
    Application.OnKey "{F4}", "D_1"
    Application.OnKey "{F5}", "E_1"
End Sub

How to enable SOAP on CentOS

The yum install php-soap command will install the Soap module for php 5.x

For installing the correct version for your environment I recommend to create a file info.php and put this code: <?php echo phpinfo(); ?>

In the header you'll see the version you're using:

enter image description here

Now that you know the correct version you can run this command: yum search php-soap

This command will return the avaliable versions:

php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php54-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php55-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php56-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php73-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
php74-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php70-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php71-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol
rh-php72-php-soap.x86_64 : A module for PHP applications that use the SOAP protocol

Now you just need to choose the correct module to your php version.

For this example, you should run this command php72-php-soap.x86_64

C# HttpWebRequest of type "application/x-www-form-urlencoded" - how to send '&' character in content body?

Since your content-type is application/x-www-form-urlencoded you'll need to encode the POST body, especially if it contains characters like & which have special meaning in a form.

Try passing your string through HttpUtility.UrlEncode before writing it to the request stream.

Here are a couple links for reference.

Wpf DataGrid Add new row

Just simply use this Style of DataGridRow:

<DataGrid.RowStyle>
        <Style TargetType="DataGridRow">
            <Setter Property="IsEnabled" Value="{Binding RelativeSource={RelativeSource Self},Path=IsNewItem,Mode=OneWay}" />
        </Style>
</DataGrid.RowStyle>

Using a remote repository with non-standard port

This avoids your problem rather than fixing it directly, but I'd recommend adding a ~/.ssh/config file and having something like this

Host git_host
HostName git.host.de
User root
Port 4019

then you can have

url = git_host:/var/cache/git/project.git

and you can also ssh git_host and scp git_host ... and everything will work out.

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

For people that find this question by searching for the error message, you can also see this error if you make a mistake in your @JsonProperty annotations such that you annotate a List-typed property with the name of a single-valued field:

@JsonProperty("someSingleValuedField") // Oops, should have been "someMultiValuedField"
public List<String> getMyField() { // deserialization fails - single value into List
  return myField;
}

Difference between dict.clear() and assigning {} in Python

d = {} will create a new instance for d but all other references will still point to the old contents. d.clear() will reset the contents, but all references to the same instance will still be correct.

Microsoft.ACE.OLEDB.12.0 provider is not registered

Basically, if you're on a 64-bit machine, IIS 7 is not (by default) serving 32-bit apps, which the database engine operates on. So here is exactly what you do:

1) ensure that the 2007 database engine is installed, this can be downloaded at: http://www.microsoft.com/downloads/details.aspx?FamilyID=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en

2) open IIS7 manager, and open the Application Pools area. On the right sidebar, you will see an option that says "Set application pool defaults". Click it, and a window will pop up with the options.

3) the second field down, which says 'Enable 32-bit applications' is probably set to FALSE by default. Simply click where it says 'false' to change it to 'true'.

4) Restart your app pool (you can do this by hitting RECYCLE instead of STOP then START, which will also work).

5) done, and your error message will go away.

Executing JavaScript after X seconds

onclick = "setTimeout(function() { document.getElementById('div1').style.display='none';document.getElementById('div2').style.display='none'}, 1000)"

Change 1000 to the number of milliseconds you want to delay.

PHP isset() with multiple parameters

Use the php's OR (||) logical operator for php isset() with multiple operator e.g

if (isset($_POST['room']) || ($_POST['cottage']) || ($_POST['villa'])) {

}

How to present a simple alert message in java?

Even without importing swing, you can get the call in one, all be it long, string. Otherwise just use the swing import and simple call:

JOptionPane.showMessageDialog(null, "Thank you for using Java", "Yay, java", JOptionPane.PLAIN_MESSAGE);

Easy enough.

How do I clear the dropdownlist values on button click event using jQuery?

If you want to reset bootstrap page with button click using jQuery :

function resetForm(){
        var validator = $( "#form_ID" ).validate();
        validator.resetForm();
}

Using above code you also have change the field colour as red to normal.

If you want to reset only fielded value then :

$("#form_ID")[0].reset();

versionCode vs versionName in Android Manifest

Version Code - It's a positive integer that's used for comparison with other version codes. It's not shown to the user, it's just for record-keeping in a way. You can set it to any integer you like but it's suggested that you linearly increment it for successive versions.

Version Name - This is the version string seen by the user. It isn't used for internal comparisons or anything, it's just for users to see.

For example: Say you release an app, its initial versionCode could be 1 and versionName could also be 1. Once you make some small changes to the app and want to publish an update, you would set versionName to "1.1" (since the changes aren't major) while logically your versionCode should be 2 (regardless of size of changes).

Say in another condition you release a completely revamped version of your app, you could set versionCode and versionName to "2".

Hope that helps.

You can read more about it here

Sql Server string to date conversion

I know this is a wicked old post with a whole lot of answers but a lot of people think that they NEED to either break things apart and put them back together or they insist that there's no way to implicitly do the conversion the OP original asked for.

To review and to hopefully provide an easy answer to others with the same question, the OP asked how to convert '10/15/2008 10:06:32 PM' to a DATETIME. Now, SQL Server does have some language dependencies for temporal conversions but if the language is english or something similar, this becomes a simple problem... just do the conversion and don't worry about the format. For example (and you can use CONVERT or CAST)...

 SELECT UsingCONVERT = CONVERT(DATETIME,'10/15/2008 10:06:32 PM')
        ,UsingCAST   = CAST('10/15/2008 10:06:32 PM' AS DATETIME)
;

... and that produces the follow answers, both of which are correct.

enter image description here

Like they say on the TV commercials, "But wait! Don't order yet! For no extra cost, it can do MUCH more!"

Let's see the real power of temporal conversions with the DATETIME and partially examine the mistake known as DATETIME2. Check out the whacky formats that DATETIME can handle auto-magically and that DATETIME2 cannot. Run the following code and see...

--===== Set the language for this example.
    SET LANGUAGE ENGLISH --Same a US-English
;
--===== Use a table constructor as if it were a table for this example.
 SELECT *
        ,DateTimeCONVERT  = TRY_CONVERT(DATETIME,StringDT)
        ,DateTimeCAST     = TRY_CAST(StringDT AS DATETIME)
        ,DateTime2CONVERT = TRY_CONVERT(DATETIME2,StringDT)
        ,DateTime2CAST    = TRY_CAST(StringDT AS DATETIME2)
   FROM (
         VALUES
         ('Same Format As In The OP'    ,'12/16/2001 01:51:01 PM')
        ,('Almost Normal'               ,'16 December, 2001 1:51:01 PM')
        ,('More Normal'                 ,'December 16, 2001 01:51:01 PM')
        ,('Time Up Front + Spaces'      ,'   13:51:01  16 December   2001')
        ,('Totally Whacky Format #01'   ,'  16  13:51:01  December   2001')
        ,('Totally Whacky Format #02'   ,'  16    December 13:51:01  2001  ')
        ,('Totally Whacky Format #03'   ,'  16    December 01:51:01  PM 2001  ')
        ,('Totally Whacky Format #04'   ,' 2001 16    December 01:51:01  PM ')
        ,('Totally Whacky Format #05'   ,' 2001    December 01:51:01  PM  16  ')
        ,('Totally Whacky Format #06'   ,' 2001 16    December  01:51:01 PM  ')
        ,('Totally Whacky Format #07'   ,' 2001 16    December  13:51:01 PM  ')
        ,('Totally Whacky Format #08'   ,' 2001 16  13:51:01 PM  December    ')
        ,('Totally Whacky Format #09'   ,'   13:51:01   PM  2001.12/16 ')
        ,('Totally Whacky Format #10'   ,'   13:51:01   PM  2001.December/16 ')
        ,('Totally Whacky Format #11'   ,'   13:51:01   PM  2001.Dec/16 ')
        ,('Totally Whacky Format #12'   ,'   13:51:01   PM  2001.Dec.16 ')
        ,('Totally Whacky Format #13'   ,'   13:51:01   PM  2001/Dec.16')
        ,('Totally Whacky Format #14'   ,'   13:51:01   PM  2001 . 12/16 ')
        ,('Totally Whacky Format #15'   ,'   13:51:01   PM  2001 . December / 16 ')
        ,('Totally Whacky Format #16'   ,'   13:51:01   PM  2001 . Dec /   16 ')
        ,('Totally Whacky Format #17'   ,'   13:51:01   PM  2001 . Dec .   16 ')
        ,('Totally Whacky Format #18'   ,'   13:51:01   PM  2001 / Dec .   16')
        ,('Totally Whacky Format #19'   ,'   13:51:01   PM  2001 . Dec -   16 ')
        ,('Totally Whacky Format #20'   ,'   13:51:01   PM  2001 - Dec -   16 ')
        ,('Totally Whacky Format #21'   ,'   13:51:01   PM  2001 - Dec .   16')
        ,('Totally Whacky Format #22'   ,'   13:51:01   PM  2001 - Dec /   16 ')
        ,('Totally Whacky Format #23'   ,'   13:51:01   PM  2001 / Dec -   16')
        ,('Just the year'               ,' 2001      ')
        ,('YYYYMM'                      ,' 200112      ')
        ,('YYYY MMM'                    ,'2001 Dec')
        ,('YYYY-MMM'                    ,'2001-Dec')
        ,('YYYY    .     MMM'           ,'2001    .     Dec')
        ,('YYYY    /     MMM'           ,'2001    /     Dec')
        ,('YYYY    -     MMM'           ,'2001    /     Dec')
        ,('Forgot The Spaces #1'        ,'2001December26')
        ,('Forgot The Spaces #2'        ,'2001Dec26')
        ,('Forgot The Spaces #3'        ,'26December2001')
        ,('Forgot The Spaces #4'        ,'26Dec2001')
        ,('Forgot The Spaces #5'        ,'26Dec2001 13:51:01')
        ,('Forgot The Spaces #6'        ,'26Dec2001 13:51:01PM')
        ,('Oddly, this doesn''t work'   ,'2001-12')
        ,('Oddly, this doesn''t work'   ,'12-2001')
        ) v (Description,StringDT)
;

So, yeah... SQL Server DOES actually have a pretty flexible method of handling all sorts of weird-o temporal formats and no special handling is required. We didn't even need to remove the "PM"s that were added to the 24 hour times. It's "PFM" (Pure Freakin' Magic).

Things will vary a bit depending on the the LANGUAGE is that you've selected for your server but a whole lot of it will be handled either way.

And these "auto-magic" conversions aren't something new. They go a real long way back.

xcode-select active developer directory error

Install Xcode from App Store. After installing run xcodebuild with root privileges i.e. sudo xcodebuild and accept the language. After this npm install bcrypt worked like a charm!

How do you add a scroll bar to a div?

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
    overflow-y: auto;
    max-height: 100px;
}

How to check if array element exists or not in javascript?

Use typeof arrayName[index] === 'undefined'

i.e.

if(typeof arrayName[index] === 'undefined') {
    // does not exist
}
else {
    // does exist
}

What is stability in sorting algorithms and why is it important?

Some more examples of the reason for wanting stable sorts. Databases are a common example. Take the case of a transaction data base than includes last|first name, date|time of purchase, item number, price. Say the data base is normally sorted by date|time. Then a query is made to make a sorted copy of the data base by last|first name, since a stable sort preserves the original order, even though the inquiry compare only involves last|first name, the transactions for each last|first name will be in data|time order.

A similar example is classic Excel, which limited sorts to 3 columns at a time. To sort 6 columns, a sort is done with the least significant 3 columns, followed by a sort with the most significant 3 columns.

A classic example of a stable radix sort is a card sorter, used to sort by a field of base 10 numeric columns. The cards are sorted from least significant digit to most significant digit. On each pass, a deck of cards is read and separated into 10 different bins according to the digit in that column. Then the 10 bins of cards are put back into the input hopper in order ("0" cards first, "9" cards last). Then another pass is done by the next column, until all columns are sorted. Actual card sorters have more than 10 bins since there are 12 zones on a card, a column can be blank, and there is a mis-read bin. To sort letters, 2 passes per column are needed, 1st pass for digit, 2nd pass for the 12 11 zone.

Later (1937) there were card collating (merging) machines that could merge two decks of cards by comparing fields. The input was two already sorted decks of cards, a master deck and an update deck. The collator merged the two decks into a a new mater bin and an archive bin, which was optionally used for master duplicates so that the new master bin would only have update cards in case of duplicates. This was probably the basis for the idea behind the original (bottom up) merge sort.

Moment.js - how do I get the number of years since a date, not rounded up?

When you want to show years and the remaining days:

var m = moment(d.birthday.date, "DD.MM.YYYY");
var years = moment().diff(m, 'years', false);
var days = moment().diff(m.add(years, 'years'), 'days', false);
alert(years + ' years, ' + days + ' days');

CSS: borders between table columns only

I know this is an old question, but there is a simple, one line solution which works consistently for Chrome, Firefox, etc., as well as IE8 and above (and, for the most part, works on IE7 too - see http://www.quirksmode.org/css/selectors/ for details):

table td + td { border-left:2px solid red; }


The output is something like this:

Col1 | Col2 | Col3

What is making this work is that you are defining a border only on table cells which are adjacent to another table cell. In other words, you're applying the CSS to all cells in a row except the first one.

By applying a left border to the second through the last child, it gives the appearance of the line being "between" the cells.

How to convert byte array to string and vice versa?

public class byteString {

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
        String msg = "Hello";
        byte[] buff = new byte[1024];
        buff = msg.getBytes("UTF-8");
        System.out.println(buff);
        String m = new String(buff);
        System.out.println(m);


    }

}

How can I tell if a VARCHAR variable contains a substring?

Instead of LIKE (which does work as other commenters have suggested), you can alternatively use CHARINDEX:

declare @full varchar(100) = 'abcdefg'
declare @find varchar(100) = 'cde'
if (charindex(@find, @full) > 0)
    print 'exists'

typeof !== "undefined" vs. != null

You can also use the void operator to obtain an undefined value:

if (input !== void 0) {
    // do stuff    
}

(And yes, as noted in another answer, this will throw an error if the variable was not declared, but this case can often be ruled out either by code inspection, or by code refactoring, e.g. using window.input !== void 0 for testing global variables or adding var input.)

Get absolute path of initially run script

__DIR__

From the manual:

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory.
__FILE__ always contains an absolute path with symlinks resolved whereas in older versions (than 4.0.2) it contained relative path under some circumstances.

Note: __DIR__ was added in PHP 5.3.0.

Kotlin: How to get and set a text to TextView in Android using Kotlin?

  <TextView
        android:id="@+id/usage"
        android:layout_marginTop="220dip"
        android:layout_marginLeft="45dip"
        android:layout_marginRight="15dip"
        android:typeface="serif"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Google "
        android:textColor="#030900"/>


usage.text="hello world"

Access localhost from the internet

Even though you didn't provide enough information to answer this question properly, your best shots are SSH tunnels (or reverse SSH tunnels).

You only need one SSH server on your internal or remote network to provide access to your local machine.

You can use PUTTY (it has a GUI) on Windows to create your tunnel.

How to make a TextBox accept only alphabetic characters?

Here is my solution and it works as planned:

string errmsg = "ERROR : Wrong input";
ErrorLbl.Text = errmsg;

if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space))
{
  ErrorLbl.Text = "ERROR : Wrong input";
}
else ErrorLbl.Text = string.Empty;
if (ErrorLbl.Text == errmsg)
{
  Nametxt.Text = string.Empty;
}

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

People are asserting one can't remove from a Collection being iterated by a foreach loop. I just wanted to point out that is technically incorrect and describe exactly (I know the OP's question is so advanced as to obviate knowing this) the code behind that assumption:

for (TouchableObj obj : untouchedSet) {  // <--- This is where ConcurrentModificationException strikes
    if (obj.isTouched()) {
        untouchedSet.remove(obj);
        touchedSt.add(obj);
        break;  // this is key to avoiding returning to the foreach
    }
}

It isn't that you can't remove from the iterated Colletion rather that you can't then continue iteration once you do. Hence the break in the code above.

Apologies if this answer is a somewhat specialist use-case and more suited to the original thread I arrived here from, that one is marked as a duplicate (despite this thread appearing more nuanced) of this and locked.

Remove special symbols and extra spaces and replace with underscore using the replace method

Remove the \s from your new regex and it should work - whitespace is already included in "anything but alphanumerics".

Note that you may want to add a + after the ] so you don't get sequences of more than one underscore. You can also chain onto .replace(/^_+|_+$/g,'') to trim off underscores at the start or end of the string.

How to check if there exists a process with a given pid in Python?

This will work for Linux, for example if you want to check if banshee is running... (banshee is a music player)

import subprocess

def running_process(process):
    "check if process is running. < process > is the name of the process."

    proc = subprocess.Popen(["if pgrep " + process + " >/dev/null 2>&1; then echo 'True'; else echo 'False'; fi"], stdout=subprocess.PIPE, shell=True)

    (Process_Existance, err) = proc.communicate()
    return Process_Existance

# use the function
print running_process("banshee")

How to set Navigation Drawer to be opened from right to left

Add this code to manifest:

<application android:supportsRtl="true">

and then write this code on Oncreate:

getWindow().getDecorView().setLayoutDirection(View.LAYOUT_DIRECTION_RTL);

It works for me. ;)

What's "tools:context" in Android layout files?

1.Description

tools: context = "activity name" it won't be packaged into the apk .Only ADT Layout Editor in your current Layout file set corresponding rendering context, show your current Layout in rendering the context is the activity name corresponds to the activity, if the activity in the manifest file set a Theme, then ADT Layout Editor will render your current Layout according to the Theme.Means that if you set the MainActivity set a Theme. The Light (the other), then you see in visual layout manager o background control of what should be the Theme. The Light looks like.Only to show you what you see is what you get results.

Some people see will understand some, some people see the also don't know, I'll add a few words of explanation:

2.Sample

Take a simple tools:text, for example, some more image, convenient to further understand the tools:context

<TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="sample name1" />

<TextView
    android:id="@+id/text2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    tools:text="sample name2" />

enter image description here

TextView1 adopted the android: text, and use the tools:text in the TextView2, on the right side of the Layout editor will display the sample name1, the sample name2 two font, if after you run the code to compile, generated apk, terminal display only the sample name1, does not show the sample name2 the words. You can try to run, see how the effect.

3.Specific description

1.The tools: context = "activity name" it won't be packaged into the apk(understanding: the equivalent of this is commented, the compiled no effect.)

2.Only ADT Layout Editor (i.e., for the above icon on the right side of the simulator) in the current Layout file set corresponding rendering context, the Layout of the current XML in rendering the context is the activity name corresponds to the activity, if the activity in the manifest file set a Theme, then ADT Layout Editor will render your current Layout according to the Theme.Means that if you set the MainActivity set a Theme. The Light can also be (other).(understand: you added tools: context = "activity name", the XML layout is rendering specified activity, establishes a Theme in the manifest file, pictured above right simulator Theme style will also follow changes corresponding to the Theme.)

4.summary

To sum up, these properties mainly aimed at above the right tools, the simulator debugging time display status, and compile doesn't work,

Generate fixed length Strings filled with whitespaces

For right pad you need String.format("%0$-15s", str)

i.e. - sign will "right" pad and no - sign will "left" pad

See my example:

import java.util.Scanner;
 
public class Solution {
 
    public static void main(String[] args) {
            Scanner sc=new Scanner(System.in);
            System.out.println("================================");
            for(int i=0;i<3;i++)
            {
                String s1=sc.nextLine();
                
                
                Scanner line = new Scanner( s1);
                line=line.useDelimiter(" ");
               
                String language = line.next();
                int mark = line.nextInt();;
                
                System.out.printf("%s%03d\n",String.format("%0$-15s", language),mark);
                
            }
            System.out.println("================================");
 
    }
}

The input must be a string and a number

example input : Google 1

PHP PDO with foreach and fetch

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

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

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

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

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

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

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

How can I read a text file in Android?

Try this code

public static String pathRoot = "/sdcard/system/temp/";
public static String readFromFile(Context contect, String nameFile) {
    String aBuffer = "";
    try {
        File myFile = new File(pathRoot + nameFile);
        FileInputStream fIn = new FileInputStream(myFile);
        BufferedReader myReader = new BufferedReader(new InputStreamReader(fIn));
        String aDataRow = "";
        while ((aDataRow = myReader.readLine()) != null) {
            aBuffer += aDataRow;
        }
        myReader.close();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return aBuffer;
}

@class vs. #import

Use a forward declaration in the header file if needed, and #import the header files for any classes you're using in the implementation. In other words, you always #import the files you're using in your implementation, and if you need to reference a class in your header file use a forward declaration as well.

The exception to this is that you should #import a class or formal protocol you're inheriting from in your header file (in which case you wouldn't need to import it in the implementation).

Are there constants in JavaScript?

I use const instead of var in my Greasemonkey scripts, but it is because they will run only on Firefox...
Name convention can be indeed the way to go, too (I do both!).

Spring 3.0 - Unable to locate Spring NamespaceHandler for XML schema namespace [http://www.springframework.org/schema/security]

I struggled with this for a while and none of these answers helped. Thanks to the comment from user64141 I realised that there was a problem with the spring.handlers files.

I am using the Shade plugin for Maven to generate a fat jar, and all the spring.handlers (and spring.schemas) files were being overwritten by each Spring dependency.

The Maven site covers this exact problem and how to solve it by appending the files together instead:

http://maven.apache.org/plugins/maven-shade-plugin/examples/resource-transformers.html#AppendingTransformer

Invalid length parameter passed to the LEFT or SUBSTRING function

Something else you can use is isnull:

isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)

How to convert HTML to PDF using iText

This links might be helpful to convert.

https://code.google.com/p/flying-saucer/

https://today.java.net/pub/a/today/2007/06/26/generating-pdfs-with-flying-saucer-and-itext.html

If it is a college Project, you can even go for these, http://pd4ml.com/examples.htm

Example is given to convert HTML to PDF

How to iterate over the files of a certain directory, in Java?

Here is an example that lists all the files on my desktop. you should change the path variable to your path.

Instead of printing the file's name with System.out.println, you should place your own code to operate on the file.

public static void main(String[] args) {
    File path = new File("c:/documents and settings/Zachary/desktop");

    File [] files = path.listFiles();
    for (int i = 0; i < files.length; i++){
        if (files[i].isFile()){ //this line weeds out other directories/folders
            System.out.println(files[i]);
        }
    }
}

How to diff one file to an arbitrary version in Git?

You can do:

git diff master~20:pom.xml pom.xml

... to compare your current pom.xml to the one from master 20 revisions ago through the first parent. You can replace master~20, of course, with the object name (SHA1sum) of a commit or any of the many other ways of specifying a revision.

Note that this is actually comparing the old pom.xml to the version in your working tree, not the version committed in master. If you want that, then you can do the following instead:

git diff master~20:pom.xml master:pom.xml

Flutter command not found

You must have .bash_profile file and define flutter path in .bash_profile file.

  1. First of all, if you do not have or do not know .bash_profile, please look my answer: How do I edit $PATH (.bash_profile) on OSX?

  2. You should add below line(.../flutter_SDK_path/flutter/bin) in your .bash_profile

export PATH=$PATH:/home/username/Documents/flutter_SDK_path/flutter/bin

After these steps, you can write flutter codes such as, flutter doctor, flutter build ios, flutter clean or etc. in terminal of Macbook.

@canerkaseler

Bootstrap: Open Another Modal in Modal

Working on a project that has a lot of modals calling other modals and a few HTML guys that might not know to initiate it everytime for each button. Came to a similar conclusion as @gmaggio, begrudgingly after going the long way around first.

EDIT: Now supports modals called via javascript.

EDIT: Opening a scrolling modal from another modal now works.

$(document).on('show.bs.modal', function (event) {
    if (!event.relatedTarget) {
        $('.modal').not(event.target).modal('hide');
    };
    if ($(event.relatedTarget).parents('.modal').length > 0) {
        $(event.relatedTarget).parents('.modal').modal('hide');
    };
});

$(document).on('shown.bs.modal', function (event) {
    if ($('body').hasClass('modal-open') == false) {
        $('body').addClass('modal-open');
    };
});

Just place the modal calling button in as normal, and if it is picked up to be inside a modal, it will close the current one first before opening the one specified in data-target. Note that relatedTarget is provided by Bootstrap.

I also added the following to smooth out the fading a bit: I am sure more can be done though.

.modal-backdrop.fade + .modal-backdrop.fade {
    transition: opacity 0.40s linear 0s;
}

S3 - Access-Control-Allow-Origin Header

Below is the configuration and it's fine to work for me. I hope it will help to resolve your issue on AWS S3.

<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
    <AllowedOrigin>*</AllowedOrigin>
    <AllowedMethod>GET</AllowedMethod>
    <AllowedMethod>PUT</AllowedMethod>
    <AllowedMethod>POST</AllowedMethod>
    <AllowedMethod>DELETE</AllowedMethod>
    <ExposeHeader>ETag</ExposeHeader>
    <AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>

How to get a view table query (code) in SQL Server 2008 Management Studio

Additionally, if you have restricted access to the database (IE: Can't use "Script Function as > CREATE To"), there is another option to get this query.

Find your View > right click > "Design".

This will give you the query you are looking for.

Accessing nested JavaScript objects and arrays by string path

Working with Underscore's property or propertyOf:

_x000D_
_x000D_
var test = {_x000D_
  foo: {_x000D_
    bar: {_x000D_
      baz: 'hello'_x000D_
    }_x000D_
  }_x000D_
}_x000D_
var string = 'foo.bar.baz';_x000D_
_x000D_
_x000D_
// document.write(_.propertyOf(test)(string.split('.')))_x000D_
_x000D_
document.write(_.property(string.split('.'))(test));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script>
_x000D_
_x000D_
_x000D_

Good Luck...

Access restriction on class due to restriction on required library rt.jar?

for me this how I solve it:

  • go to the build path of the current project

under Libraries

  • select the "JRE System Library [jdk1.8xxx]"
  • click edit
  • and select either "Workspace default JRE(jdk1.8xx)" OR Alternate JRE
  • Click finish
  • Click OK

enter image description here

Note: make sure that in Eclipse / Preferences (NOT the project) / Java / Installed JRE ,that the jdk points to the JDK folder not the JRE C:\Program Files\Java\jdk1.8.0_74

enter image description here

How to convert webpage into PDF by using Python

thanks to below posts, and I am able to add on the webpage link address to be printed and present time on the PDF generated, no matter how many pages it has.

Add text to Existing PDF using Python

https://github.com/disflux/django-mtr/blob/master/pdfgen/doc_overlay.py

To share the script as below:

import time
from pyPdf import PdfFileWriter, PdfFileReader
import StringIO
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from xhtml2pdf import pisa
import sys 
from PyQt4.QtCore import *
from PyQt4.QtGui import * 
from PyQt4.QtWebKit import * 

url = 'http://www.yahoo.com'
tem_pdf = "c:\\tem_pdf.pdf"
final_file = "c:\\younameit.pdf"

app = QApplication(sys.argv)
web = QWebView()
#Read the URL given
web.load(QUrl(url))
printer = QPrinter()
#setting format
printer.setPageSize(QPrinter.A4)
printer.setOrientation(QPrinter.Landscape)
printer.setOutputFormat(QPrinter.PdfFormat)
#export file as c:\tem_pdf.pdf
printer.setOutputFileName(tem_pdf)

def convertIt():
    web.print_(printer)
    QApplication.exit()

QObject.connect(web, SIGNAL("loadFinished(bool)"), convertIt)

app.exec_()
sys.exit

# Below is to add on the weblink as text and present date&time on PDF generated

outputPDF = PdfFileWriter()
packet = StringIO.StringIO()
# create a new PDF with Reportlab
can = canvas.Canvas(packet, pagesize=letter)
can.setFont("Helvetica", 9)
# Writting the new line
oknow = time.strftime("%a, %d %b %Y %H:%M")
can.drawString(5, 2, url)
can.drawString(605, 2, oknow)
can.save()

#move to the beginning of the StringIO buffer
packet.seek(0)
new_pdf = PdfFileReader(packet)
# read your existing PDF
existing_pdf = PdfFileReader(file(tem_pdf, "rb"))
pages = existing_pdf.getNumPages()
output = PdfFileWriter()
# add the "watermark" (which is the new pdf) on the existing page
for x in range(0,pages):
    page = existing_pdf.getPage(x)
    page.mergePage(new_pdf.getPage(0))
    output.addPage(page)
# finally, write "output" to a real file
outputStream = file(final_file, "wb")
output.write(outputStream)
outputStream.close()

print final_file, 'is ready.'

Proxy Basic Authentication in C#: HTTP 407 error

I had a similar problem due to a password protected proxy server and couldn't find much in the way of information out there - hopefully this helps someone. I wanted to pick up the credentials as used by the customer's browser. However, the CredentialCache.DefaultCredentials and DefaultNetworkCredentials aren't working when the proxy has it's own username and password even though I had entered these details to ensure thatInternet explorer and Edge had access.

The solution for me in the end was to use a nuget package called "CredentialManagement.Standard" and the below code:

using WebClient webClient = new WebClient();    
var request = WebRequest.Create("http://google.co.uk");
var proxy = request.Proxy.GetProxy(new Uri("http://google.co.uk"));

var cmgr = new CredentialManagement.Credential() { Target = proxy.Host };
if (cmgr.Load())
{
    var credentials = new NetworkCredential(cmgr.Username, cmgr.Password);
    webClient.Proxy.Credentials = credentials;
    webClient.Credentials = credentials;
}

This grabs credentials from 'Credentials Manager' - which can be found via Windows - click Start then search for 'Credentials Manager'. Credentials for the proxy that were manually entered when prompted by the browser will be in the Windows Credentials section.

How to kill an Android activity when leaving it so that it cannot be accessed from the back button?

Setting android:noHistory="true" on the activity in your manifest will remove an activity from the stack whenever it is navigated away from. see here

Install Qt on Ubuntu

The ubuntu package name is qt5-default, not qt.

How may I align text to the left and text to the right in the same line?

_x000D_
_x000D_
<p style="text-align:left;">_x000D_
    This text is left aligned_x000D_
    <span style="float:right;">_x000D_
        This text is right aligned_x000D_
    </span>_x000D_
</p>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/gionaf/5z3ec48r/

How can I select the row with the highest ID in MySQL?

SELECT MAX(ID) FROM tablename LIMIT 1

Use this query to find the highest ID in the MySQL table.

How do I remove the space between inline/inline-block elements?

This is the same answer I gave over on the related: Display: Inline block - What is that space?

There’s actually a really simple way to remove whitespace from inline-block that’s both easy and semantic. It’s called a custom font with zero-width spaces, which allows you to collapse the whitespace (added by the browser for inline elements when they're on separate lines) at the font level using a very tiny font. Once you declare the font, you just change the font-family on the container and back again on the children, and voila. Like this:

@font-face{ 
    font-family: 'NoSpace';
    src: url('../Fonts/zerowidthspaces.eot');
    src: url('../Fonts/zerowidthspaces.eot?#iefix') format('embedded-opentype'),
         url('../Fonts/zerowidthspaces.woff') format('woff'),
         url('../Fonts/zerowidthspaces.ttf') format('truetype'),
         url('../Fonts/zerowidthspaces.svg#NoSpace') format('svg');
}

body {
    font-face: 'OpenSans', sans-serif;
}

.inline-container {
    font-face: 'NoSpace';
}

.inline-container > * {
    display: inline-block;
    font-face: 'OpenSans', sans-serif;
}

Suit to taste. Here’s a download to the font I just cooked up in font-forge and converted with FontSquirrel webfont generator. Took me all of 5 minutes. The css @font-face declaration is included: zipped zero-width space font. It's in Google Drive so you'll need to click File > Download to save it to your computer. You'll probably need to change the font paths as well if you copy the declaration to your main css file.

When should I use a List vs a LinkedList

The difference between List and LinkedList lies in their underlying implementation. List is array based collection (ArrayList). LinkedList is node-pointer based collection (LinkedListNode). On the API level usage, both of them are pretty much the same since both implement same set of interfaces such as ICollection, IEnumerable, etc.

The key difference comes when performance matter. For example, if you are implementing the list that has heavy "INSERT" operation, LinkedList outperforms List. Since LinkedList can do it in O(1) time, but List may need to expand the size of underlying array. For more information/detail you might want to read up on the algorithmic difference between LinkedList and array data structures. http://en.wikipedia.org/wiki/Linked_list and Array

Hope this help,

How do I combine the first character of a cell with another cell in Excel?

Not sure why no one is using semicolons. This is how it works for me:

=CONCATENATE(LEFT(A1;1); B1)

Solutions with comma produce an error in Excel.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

Open for new app "HTTPD" (Apache server) in your Firewall

Take a look at this: https://www.youtube.com/watch?v=eqgUGF3NnuM

How to change environment's font size?

you can use editor.fontSize into your setting.json file of the editor.

for example :

{
"editor.fontSize": 14
}

How do I append to a table in Lua

foo = {}
foo[#foo+1]="bar"
foo[#foo+1]="baz"

This works because the # operator computes the length of the list. The empty list has length 0, etc.

If you're using Lua 5.3+, then you can do almost exactly what you wanted:

foo = {}
setmetatable(foo, { __shl = function (t,v) t[#t+1]=v end })
_= foo << "bar"
_= foo << "baz"

Expressions are not statements in Lua and they need to be used somehow.

Limit the output of the TOP command to a specific process name

A more specific case, like I actually was looking for:

For Java processes you can also use jps -q whereby jps is a tool from $JAVA_HOME/bin and hence should be in your $PATH.

How do I update a formula with Homebrew?

You can't use brew install to upgrade an installed formula. If you want upgrade all of outdated formulas, you can use the command below.

brew outdated | xargs brew upgrade

How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit

Assuming you're dealing with Windows 7 x64 and something that was previously installed with some sort of an installer, you can open regedit and search the keys under

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

(which references 32-bit programs) for part of the name of the program, or

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

(if it actually was a 64-bit program).

If you find something that matches your program in one of those, the contents of UninstallString in that key usually give you the exact command you are looking for (that you can run in a script).

If you don't find anything relevant in those registry locations, then it may have been "installed" by unzipping a file. Because you mentioned removing it by the Control Panel, I gather this likely isn't then case; if it's in the list of programs there, it should be in one of the registry keys I mentioned.

Then in a .bat script you can do

if exist "c:\program files\whatever\program.exe" (place UninstallString contents here)
if exist "c:\program files (x86)\whatever\program.exe" (place UninstallString contents here)

How can I use numpy.correlate to do autocorrelation?

Auto-correlation comes in two versions: statistical and convolution. They both do the same, except for a little detail: The statistical version is normalized to be on the interval [-1,1]. Here is an example of how you do the statistical one:

def acf(x, length=20):
    return numpy.array([1]+[numpy.corrcoef(x[:-i], x[i:])[0,1]  \
        for i in range(1, length)])

How can I wrap or break long text/word in a fixed width span?

Try this

span {
    display: block;
    width: 150px;
}

Use dynamic (variable) string as regex pattern in JavaScript

var string = "Hi welcome to stack overflow"
var toSearch = "stack"

//case insensitive search

var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'

https://jsfiddle.net/9f0mb6Lz/

Hope this helps

Convert command line arguments into an array in Bash

Easier Yet, you can operate directly on $@ ;)

Here is how to do pass a a list of args directly from the prompt:

function echoarg { for stuff in "$@" ; do echo $stuff ; done ; } 
    echoarg Hey Ho Lets Go
    Hey
    Ho
    Lets
    Go

PHP: Best way to check if input is a valid number?

return ctype_digit($num) && (int) $num > 0

How to connect to MongoDB in Windows?

  1. Go to C:\Program Files\MongoDB\Server\3.4\bin using cmd and write mongod.
  2. Open another cmd by right click and run as admin point to your monogodb installed directory as mentioned above and then just like write this mongo.exe
  3. After that, write db.test.save({Field:'Hello mongodb'}) this command will insert a field having name Field and value is Hello mongodb.
  4. After, check the record db.test.find() and press enter you will find the record that you have recently entered.

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

1 to 10:

[0-9]{1,10}

In .NET (and not only, see the comment below) also valid (with a stipulation) this:

\d{1,10}

C#:

var regex = new Regex("^[0-9]{1,10}$", RegexOptions.Compiled);
regex.IsMatch("1"); // true
regex.IsMatch("12"); // true
..
regex.IsMatch("1234567890"); // true
regex.IsMatch(""); // false
regex.IsMatch(" "); // true
regex.IsMatch("a"); // false

P.S. Here's a very useful sandbox.

Entity Framework Timeouts

If you are using a DbContext, use the following constructor to set the command timeout:

public class MyContext : DbContext
{
    public MyContext ()
    {
        var adapter = (IObjectContextAdapter)this;
        var objectContext = adapter.ObjectContext;
        objectContext.CommandTimeout = 1 * 60; // value in seconds
    }
}

How to return Json object from MVC controller to view

You could use AJAX to call this controller action. For example if you are using jQuery you might use the $.ajax() method:

<script type="text/javascript">
    $.ajax({
        url: '@Url.Action("NameOfYourAction")',
        type: 'GET',
        cache: false,
        success: function(result) {
            // you could use the result.values dictionary here
        }
    });
</script>

Session timeout in ASP.NET

In my situation, it was Application Pool. It is set to restart when idle for xx mins. When I set it to not restart, it seems to use value from Web Config.

xcopy file, rename, suppress "Does xxx specify a file name..." message

I suggest robocopy instead of copy or xcopy. Used as command or in GUI on clients or servers. Tolerant of network pauses and you can choose to ignore file attributes when copying of copy by file attributes. Oh, and it supports multi-core machines so files are copied much faster in "parallel" with each other instead of sequentially. robocopy can be found on MS TechNet.

How to downgrade Xcode to previous version?

I'm assuming you are having at least OSX 10.7, so go ahead into the applications folder (Click on Finder icon > On the Sidebar, you'll find "Applications", click on it ), delete the "Xcode" icon. That will remove Xcode from your system completely. Restart your mac.

Now go to https://developer.apple.com/download/more/ and download an older version of Xcode, as needed and install. You need an Apple ID to login to that portal.

What is the different between RESTful and RESTless

Here are summarized the key differences between RESTful and RESTless web services:

1. Protocol

  • RESTful services use REST architectural style,
  • RESTless services use SOAP protocol.

2. Business logic / Functionality

  • RESTful services use URL to expose business logic,
  • RESTless services use the service interface to expose business logic.

3. Security

  • RESTful inherits security from the underlying transport protocols,
  • RESTless defines its own security layer, thus it is considered as more secure.

4. Data format

  • RESTful supports various data formats such as HTML, JSON, text, etc,
  • RESTless supports XML format.

5. Flexibility

  • RESTful is easier and flexible,
  • RESTless is not as easy and flexible.

6. Bandwidth

  • RESTful services consume less bandwidth and resource,
  • RESTless services consume more bandwidth and resources.

Declare Variable for a Query String

Using EXEC

You can use following example for building SQL statement.

DECLARE @sqlCommand varchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = '''London'''
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = ' + @city
EXEC (@sqlCommand)

Using sp_executesql

With using this approach you can ensure that the data values being passed into the query are the correct datatypes and avoind use of more quotes.

DECLARE @sqlCommand nvarchar(1000)
DECLARE @columnList varchar(75)
DECLARE @city varchar(75)
SET @columnList = 'CustomerID, ContactName, City'
SET @city = 'London'
SET @sqlCommand = 'SELECT ' + @columnList + ' FROM customers WHERE City = @city'
EXECUTE sp_executesql @sqlCommand, N'@city nvarchar(75)', @city = @city

Reference

UICollectionView current visible cell index

You can use scrollViewDidEndDecelerating: for this

//@property (strong, nonatomic) IBOutlet UICollectionView *collectionView;

   - (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{

        for (UICollectionViewCell *cell in [self.collectionView visibleCells]) {
            NSIndexPath *indexPath = [self.collectionView indexPathForCell:cell];
            NSUInteger lastIndex = [indexPath indexAtPosition:[indexPath length] - 1];
            NSLog(@"visible cell value %d",lastIndex);
        }

    }

Left-pad printf with spaces

If you want exactly 40 spaces before the string then you should just do:

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

If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces): printf("%40s%s", "", myStr );

If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this: printf("%40s", myStr);

You can also put "up to" 40 spaces AfTER the string by doing: printf("%-40s", myStr);

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

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

Problems after upgrading to Xcode 10: Build input file cannot be found

In my case I had a build script that generated the .app binary (Buck). The Buck build script ran in parallel with Swift Embed build step. Because the .app binary was not generated yet the Swift step would fail.

In my build script I added "$BUILD_PRODUCTS_DIR/$EXECUTABLE_PATH" under "Output Files".

This tells Xcode's New Build System that this script will output the app Binary and in turn Xcode will make sure to synchronize any build steps that depend on this artifact.

enter image description here

Zoom in on a point (using scale and translate)

I want to put here some information for those, who do separately drawing of picture and moving -zooming it.

This may be useful when you want to store zooms and position of viewport.

Here is drawer:

function redraw_ctx(){
   self.ctx.clearRect(0,0,canvas_width, canvas_height)
   self.ctx.save()
   self.ctx.scale(self.data.zoom, self.data.zoom) // 
   self.ctx.translate(self.data.position.left, self.data.position.top) // position second
   // Here We draw useful scene My task - image:
   self.ctx.drawImage(self.img ,0,0) // position 0,0 - we already prepared
   self.ctx.restore(); // Restore!!!
}

Notice scale MUST be first.

And here is zoomer:

function zoom(zf, px, py){
    // zf - is a zoom factor, which in my case was one of (0.1, -0.1)
    // px, py coordinates - is point within canvas 
    // eg. px = evt.clientX - canvas.offset().left
    // py = evt.clientY - canvas.offset().top
    var z = self.data.zoom;
    var x = self.data.position.left;
    var y = self.data.position.top;

    var nz = z + zf; // getting new zoom
    var K = (z*z + z*zf) // putting some magic

    var nx = x - ( (px*zf) / K ); 
    var ny = y - ( (py*zf) / K);

    self.data.position.left = nx; // renew positions
    self.data.position.top = ny;   
    self.data.zoom = nz; // ... and zoom
    self.redraw_ctx(); // redraw context
    }

and, of course, we would need a dragger:

this.my_cont.mousemove(function(evt){
    if (is_drag){
        var cur_pos = {x: evt.clientX - off.left,
                       y: evt.clientY - off.top}
        var diff = {x: cur_pos.x - old_pos.x,
                    y: cur_pos.y - old_pos.y}

        self.data.position.left += (diff.x / self.data.zoom);  // we want to move the point of cursor strictly
        self.data.position.top += (diff.y / self.data.zoom);

        old_pos = cur_pos;
        self.redraw_ctx();

    }


})

Node.js Error: Cannot find module express

Given you have installed node on your system, install Express locally for your project using the following for Windows:

npm install express

or

npm install express --save

You might give it global access by using:

npm install -g express --save

How to sort mongodb with pymongo

.sort([("field1",pymongo.ASCENDING), ("field2",pymongo.DESCENDING)])

Python uses key,direction. You can use the above way.

So in your case you can do this

for post in db.posts.find().sort('entities.user_mentions.screen_name',pymongo.ASCENDING):
        print post

Can't subtract offset-naive and offset-aware datetimes

I've found timezone.make_aware(datetime.datetime.now()) is helpful in django (I'm on 1.9.1). Unfortunately you can't simply make a datetime object offset-aware, then timetz() it. You have to make a datetime and make comparisons based on that.

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

I've been to this post about 10 times now and I just wanted to leave my two cents here. You can just unmount it conditionally.

if (renderMyComponent) {
  <MyComponent props={...} />
}

All you have to do is remove it from the DOM in order to unmount it.

As long as renderMyComponent = true, the component will render. If you set renderMyComponent = false, it will unmount from the DOM.

Swift how to sort array of custom objects by property value

If you want to sort original array of custom objects. Here is another way to do so in Swift 2.1

var myCustomerArray = [Customer]()
myCustomerArray.sortInPlace {(customer1:Customer, customer2:Customer) -> Bool in
    customer1.id < customer2.id
}

Where id is an Integer. You can use the same < operator for String properties as well.

You can learn more about its use by looking at an example here: Swift2: Nearby Customers

How can I scale the content of an iframe?

I think you can do this by calculating the height and width you want with javascript (via document.body.clientWidth etc.) and then injecting the iframe into your HTML like this:

var element = document.getElementById("myid");
element.innerHTML += "<iframe src='http://www.google.com' height='200' width='" + document.body.clientWidth * 0.8 + "'/>";

I didn't test this in IE6 but it seems to work with the good ones :)

load iframe in bootstrap modal

I came across this implementation in Codepen. I hope you find it helpful.

this.on('hidden.bs.modal', function(){
      $(this).find('iframe').html("").attr("src", "");
    });

Access event to call preventdefault from custom function originating from onclick attribute of tag

The simplest solution simply is:

<a href="#" onclick="event.preventDefault(); myfunc({a:1, b:'hi'});" />click</a>

It's actually a good way of doing cache busting for documents with a fallback for no JS enabled browsers (no cache busting if no JS)

<a onclick="
if(event.preventDefault) event.preventDefault(); else event.returnValue = false;
window.location = 'http://www.domain.com/docs/thingy.pdf?cachebuster=' + 
Math.round(new Date().getTime() / 1000);" 
href="http://www.domain.com/docs/thingy.pdf">

If JavaScript is enabled, it opens the PDF with a cache busting query string, if not it just opens the PDF.

Press enter in textbox to and execute button command

If you're just gonna click the button when Enter was pressed how about this?

private void textbox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Enter)
        {
            buttonSearch.PerformClick();
        }

How to trust a apt repository : Debian apt-get update error public key is not available: NO_PUBKEY <id>

I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):

aptitude install debian-archive-keyring

In case it is some other keyring you need, check out

apt-cache search keyring | grep debian

My squeeze system shows all these:

debian-archive-keyring       - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring   - GnuPG archive keys of the Debian Edu archive
debian-keyring               - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring     - GnuPG archive keys for the emdebian repository

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.
</xsl:if>

How to concatenate multiple lines of output to one line?

The fastest and easiest ways I know to solve this problem:

When we want to replace the new line character \n with the space:

xargs < file

xargs has own limits on the number of characters per line and the number of all characters combined, but we can increase them. Details can be found by running this command: xargs --show-limits and of course in the manual: man xargs

When we want to replace one character with another exactly one character:

tr '\n' ' ' < file

When we want to replace one character with many characters:

tr '\n' '~' < file | sed s/~/many_characters/g

First, we replace the newline characters \n for tildes ~ (or choose another unique character not present in the text), and then we replace the tilde characters with any other characters (many_characters) and we do it for each tilde (flag g).

Stop Chrome Caching My JS Files

Quick steps:

1) Open up the Developer Tools dashboard by going to the Chrome Menu -> Tools -> Developer Tools

2) Click on the settings icon on the right hand side (it's a cog!)

3) Check the box "Disable cache (when DevTools is open)"

4) Now, while the dashboard is up, just hit refresh and JS won't be cached!

Java java.sql.SQLException: Invalid column index on preparing statement

Everywhere inside the query string, the wildcard should be ? instead of '?'. That should solve the problem.

EDIT :

To add to that, you need to change date '?' to to_date(?, 'yyyy-mm-dd'). Please try that and let me know.

How to convert number to words in java

Find this code for Indian rupees and in lakhs & crores than Million and Billion. You can pass String or Bigdecimal to the method. This will give the correct output for paisa as well.

package yourpackage;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

public class Currency {
    
    public static String convertToWords(BigDecimal num) {
        return convertToWords(num.toString());
    }

    public static String convertToWords(String num) {
        BigDecimal bd = new BigDecimal(num);
        long number = bd.longValue();
        long no = bd.longValue();
        int decimal = (int) (bd.remainder(BigDecimal.ONE).doubleValue() * 100);
        int digits_length = String.valueOf(no).length();
        int i = 0;
        ArrayList<String> str = new ArrayList<>();
        HashMap<Integer, String> words = new HashMap<>();
        words.put(0, "");
        words.put(1, "One");
        words.put(2, "Two");
        words.put(3, "Three");
        words.put(4, "Four");
        words.put(5, "Five");
        words.put(6, "Six");
        words.put(7, "Seven");
        words.put(8, "Eight");
        words.put(9, "Nine");
        words.put(10, "Ten");
        words.put(11, "Eleven");
        words.put(12, "Twelve");
        words.put(13, "Thirteen");
        words.put(14, "Fourteen");
        words.put(15, "Fifteen");
        words.put(16, "Sixteen");
        words.put(17, "Seventeen");
        words.put(18, "Eighteen");
        words.put(19, "Nineteen");
        words.put(20, "Twenty");
        words.put(30, "Thirty");
        words.put(40, "Forty");
        words.put(50, "Fifty");
        words.put(60, "Sixty");
        words.put(70, "Seventy");
        words.put(80, "Eighty");
        words.put(90, "Ninety");
        String digits[] = { "", "Hundred", "Thousand", "Lakh", "Crore" };
        while (i < digits_length) {
            int divider = (i == 2) ? 10 : 100;
            number = no % divider;
            no = no / divider;
            i += divider == 10 ? 1 : 2;
            if (number > 0) {
                int counter = str.size();
                String plural = (counter > 0 && number > 9) ? "s" : "";
                String tmp = (number < 21) ? words.get(Integer.valueOf((int) number)) + " " + digits[counter] + plural
                        : words.get(Integer.valueOf((int) Math.floor(number / 10) * 10)) + " "
                                + words.get(Integer.valueOf((int) (number % 10))) + " " + digits[counter] + plural;
                str.add(tmp);
            } else {
                str.add("");
            }
        }

        Collections.reverse(str);
        String Rupees = String.join(" ", str).trim();

        String paise = (decimal) > 0
                ? " And " + words.get(Integer.valueOf((int) (decimal - decimal % 10))) + " "
                        + words.get(Integer.valueOf((int) (decimal % 10))) + " Paise "
                : "";
        return "Rupees " + Rupees + paise + " Only";
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("56721351 = " + Currency.convertToWords(new BigDecimal(56721351)));
        System.out.println("76521351.61 = " + Currency.convertToWords("76521351.61"));
    }

}

When you run this program for 56721351(as Bigdecimal) and 76521351.61(as String) the output is

56721351 = Rupees Five Crore Sixty Seven Lakhs Twenty One Thousands Three Hundred Fifty One Only
76521351.61 = Rupees Seven Crore Sixty Five Lakhs Twenty One Thousands Three Hundred Fifty One And Sixty One Paise  Only

Find element in List<> that contains a value

hi body very late but i am writing

if(mylist.contains(value)){}

How can I autoplay a video using the new embed code style for Youtube?

Just put "?autoplay=1" in the url the video will autoload.

So your url would be: http://www.youtube.com/embed/JW5meKfy3fY?autoplay=1

In case you wanna disable autoplay, just make 1 to 0 as ?autoplay=0

MAX function in where clause mysql

Use a subselect:

SELECT row  FROM table  WHERE id=(
    SELECT max(id) FROM table
)

Note: ID must be unique, else multiple rows are returned

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
}
<div>
  Your Text
</div>

Especially useful when you don't know the width of the div.


align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {
    position:absolute;
    width:300px;
    height:300px;
    background:#063;
    bottom:0px;
    right:25%;
    left:50%;
    margin-left:-150px;
}

SQL Server : login success but "The database [dbName] is not accessible. (ObjectExplorer)"

Go to

Security >> Logins >> Right click to the user >> Properties >>

On the left navigation move to >> User Mapping >> Check the database and in the "Database role membership for: <>" check "db_owner" for user that you are experience the issue.

PROBLEM SOLVED...

Unique random string generation

I am surprised why there is not a CrytpoGraphic solution in place. GUID is unique but not cryptographically safe. See this Dotnet Fiddle.

var bytes = new byte[40]; // byte size
using (var crypto = new RNGCryptoServiceProvider())
  crypto.GetBytes(bytes);

var base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

In case you want to Prepend with a Guid:

var result = Guid.NewGuid().ToString("N") + base64;
Console.WriteLine(result);

A cleaner alphanumeric string:

result = Regex.Replace(result,"[^A-Za-z0-9]","");
Console.WriteLine(result);

use video as background for div

Why not fix a <video> and use z-index:-1 to put it behind all other elements?

html, body { width:100%; height:100%; margin:0; padding:0; }

<div style="position: fixed; top: 0; width: 100%; height: 100%; z-index: -1;">
    <video id="video" style="width:100%; height:100%">
        ....
    </video>
</div>
<div class='content'>
    ....

Demo

If you want it within a container you have to add a container element and a little more CSS

/* HTML */
<div class='vidContain'>
    <div class='vid'>
        <video> ... </video>
    </div>
    <div class='content'> ... The rest of your content ... </div>
</div>

/* CSS */
.vidContain {
    width:300px; height:200px;
    position:relative;
    display:inline-block;
    margin:10px;
}
.vid {
    position: absolute; 
    top: 0; left:0;
    width: 100%; height: 100%; 
    z-index: -1;
}    
.content {
    position:absolute;
    top:0; left:0;
    background: black;
    color:white;
}

Demo

How to determine whether an object has a given property in JavaScript

If you want to know if the object physically contains the property @gnarf's answer using hasOwnProperty will do the work.

If you're want to know if the property exists anywhere, either on the object itself or up in the prototype chain, you can use the in operator.

if ('prop' in obj) {
  // ...
}

Eg.:

var obj = {};

'toString' in obj == true; // inherited from Object.prototype
obj.hasOwnProperty('toString') == false; // doesn't contains it physically

How to set scope property with ng-init?

You are trying to read the set value before Angular is done assigning.

Demo:

var testController = function ($scope, $timeout) {
    console.log('test');
    $timeout(function(){
        console.log($scope.testInput);
    },1000);
}

Ideally you should use $watch as suggested by @Beterraba to get rid of the timer:

var testController = function ($scope) {
    console.log('test');
    $scope.$watch("testInput", function(){
        console.log($scope.testInput);
    });
}

Angular - Set headers for every request

The simplest of all

Create a config.ts file

import { HttpHeaders } from '@angular/common/http';

export class Config {
    url: string = 'http://localhost:3000';
    httpOptions: any = {
        headers: new HttpHeaders({
           'Content-Type': 'application/json',
           'Authorization': JSON.parse(localStorage.getItem('currentUser')).token
        })
    }
}

Then on your service, just import the config.ts file

import { Config } from '../config';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class OrganizationService {
  config = new Config;

  constructor(
    private http: HttpClient
  ) { }

  addData(data): Observable<any> {
     let sendAddLink = `${this.config.url}/api/addData`;

     return this.http.post(sendAddLink , data, this.config.httpOptions).pipe(
       tap(snap => {
      return snap;
        })
    );
 } 

I think it was the simplest and the safest.

CSS: styled a checkbox to look like a button, is there a hover?

it looks like you need a rule very similar to your checked rule

http://jsfiddle.net/VWBN4/3

#ck-button input:hover + span {
    background-color:#191;
    color:#fff;
}

and for hover and clicked state:

#ck-button input:checked:hover + span {
    background-color:#c11;
    color:#fff;
}

the order is important though.

Address already in use: JVM_Bind

I notice you are using windows, which is particularly bad about using low port numbers for outgoing sockets. See here for how to reserve the port number that you want to rely on using for glassfish.

Convert base class to derived class

No it is not possible. The only way that is possible is

static void Main(string[] args)
{
    BaseClass myBaseObject = new DerivedClass();
    DerivedClass myDerivedObject = myBaseObject as DerivedClass;

    myDerivedObject.MyDerivedProperty = true;
}

Python data structure sort list alphabetically

[] denotes a list, () denotes a tuple and {} denotes a dictionary. You should take a look at the official Python tutorial as these are the very basics of programming in Python.

What you have is a list of strings. You can sort it like this:

In [1]: lst = ['Stem', 'constitute', 'Sedge', 'Eflux', 'Whim', 'Intrigue']

In [2]: sorted(lst)
Out[2]: ['Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim', 'constitute']

As you can see, words that start with an uppercase letter get preference over those starting with a lowercase letter. If you want to sort them independently, do this:

In [4]: sorted(lst, key=str.lower)
Out[4]: ['constitute', 'Eflux', 'Intrigue', 'Sedge', 'Stem', 'Whim']

You can also sort the list in reverse order by doing this:

In [12]: sorted(lst, reverse=True)
Out[12]: ['constitute', 'Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux']

In [13]: sorted(lst, key=str.lower, reverse=True)
Out[13]: ['Whim', 'Stem', 'Sedge', 'Intrigue', 'Eflux', 'constitute']

Please note: If you work with Python 3, then str is the correct data type for every string that contains human-readable text. However, if you still need to work with Python 2, then you might deal with unicode strings which have the data type unicode in Python 2, and not str. In such a case, if you have a list of unicode strings, you must write key=unicode.lower instead of key=str.lower.

Getting a count of rows in a datatable that meet certain criteria

If the data is stored in a database it will be faster to send the query to the database instead of getting all data and query it in memory.

A third way to do it will be linq to datasets, but i doubt any of these 3 methods differ much in performance.

MySQL: can't access root account

This worked for me:

https://blog.dotkam.com/2007/04/10/mysql-reset-lost-root-password/

Step 1: Stop MySQL daemon if it is currently running

  ps -ef | grep mysql      - checks if mysql/mysqld is one of the running processes.

  pkill mysqld             - kills the daemon, if it is running.

Step 2: Run MySQL safe daemon with skipping grant tables

  mysqld_safe --skip-grant-tables &

  mysql -u root mysql

Step 3: Login to MySQL as root with no password

  mysql -u root mysql

Step 4: Run UPDATE query to reset the root password

  UPDATE user SET password=PASSWORD("value=42") WHERE user="root";
  FLUSH PRIVILEGES;

In MySQL 5.7, the 'password' field was removed, now the field name is 'authentication_string':

  UPDATE user SET authentication_string=PASSWORD("42") WHERE 
  user="root";
  FLUSH PRIVILEGES;

Step 5: Stop MySQL safe daemon

Step 6: Start MySQL daemon

OS specific instructions in CMAKE: How to?

Generator expressions are also possible:

target_link_libraries(
    target_name
    PUBLIC
        libA
        $<$<PLATFORM_ID:Windows>:wsock32>
    PRIVATE
        $<$<PLATFORM_ID:Linux>:libB>
        libC
)

This will link libA, wsock32 & libC on Windows and link libA, libB & libC on Linux

CMake Generator Expressions

What does LayoutInflater in Android do?

LayoutInflater creates View objects based on layouts defined in XML. There are several different ways to use LayoutInflater, including creating custom Views, inflating Fragment views into Activity views, creating Dialogs, or simply inflating a layout file View into an Activity.

There are a lot of misconceptions about how the inflation process works. I think this comes from poor of the documentation for the inflate() method. If you want to learn about the inflate() method in detail, I wrote a blog post about it here:

https://www.bignerdranch.com/blog/understanding-androids-layoutinflater-inflate/

no operator "<<" matches these operands

You're not including the standard <string> header.

You got [un]lucky that some of its pertinent definitions were accidentally made available by the other standard headers that you did include ... but operator<< was not.

Could not find the main class, program will exit

The Manifest text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

Get selected value in dropdown list using JavaScript

The previous answers still leave room for improvement because of the possibilities, the intuitiveness of the code, and the use of id versus name. One can get a read-out of three data of a selected option -- its index number, its value and its text. This simple, cross-browser code does all three:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Demo GetSelectOptionData</title>
</head>
<body>
    <form name="demoForm">
        <select name="demoSelect" onchange="showData()">
            <option value="zilch">Select:</option>
            <option value="A">Option 1</option>
            <option value="B">Option 2</option>
            <option value="C">Option 3</option>
        </select>
    </form>

    <p id="firstP">&nbsp;</p>
    <p id="secondP">&nbsp;</p>
    <p id="thirdP">&nbsp;</p>

    <script>
    function showData() {
        var theSelect = demoForm.demoSelect;
        var firstP = document.getElementById('firstP');
        var secondP = document.getElementById('secondP');
        var thirdP = document.getElementById('thirdP');
        firstP.innerHTML = ('This option\'s index number is: ' + theSelect.selectedIndex + ' (Javascript index numbers start at 0)');
        secondP.innerHTML = ('Its value is: ' + theSelect[theSelect.selectedIndex].value);
        thirdP.innerHTML = ('Its text is: ' + theSelect[theSelect.selectedIndex].text);
    }
     </script>
</body>
</html>

Live demo: http://jsbin.com/jiwena/1/edit?html,output .

id should be used for make-up purposes. For functional form purposes, name is still valid, also in HTML5, and should still be used. Lastly, mind the use of square versus round brackets in certain places. As was explained before, only (older versions of) Internet Explorer will accept round ones in all places.

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

How to get the number of days of difference between two dates on mysql?

What about the DATEDIFF function ?

Quoting the manual's page :

DATEDIFF() returns expr1 – expr2 expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation


In your case, you'd use :

mysql> select datediff('2010-04-15', '2010-04-12');
+--------------------------------------+
| datediff('2010-04-15', '2010-04-12') |
+--------------------------------------+
|                                    3 | 
+--------------------------------------+
1 row in set (0,00 sec)

But note the dates should be written as YYYY-MM-DD, and not DD-MM-YYYY like you posted.

How can I programmatically generate keypress events in C#?

The question is tagged WPF but the answers so far are specific WinForms and Win32.

To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:

var key = Key.Insert;                    // Key to send
var target = Keyboard.FocusedElement;    // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send
     target.RaiseEvent(
  new KeyEventArgs(
    Keyboard.PrimaryDevice,
    PresentationSource.FromVisual(target),
    0,
    key)
  { RoutedEvent=routedEvent }
);

This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.

Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:

var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;

target.RaiseEvent(
  new TextCompositionEventArgs(
    InputManager.Current.PrimaryKeyboardDevice,
    new TextComposition(InputManager.Current, target, text))
  { RoutedEvent = routedEvent }
);

Also note that:

  • Controls expect to receive Preview events, for example PreviewKeyDown should precede KeyDown

  • Using target.RaiseEvent(...) sends the event directly to the target without meta-processing such as accelerators, text composition and IME. This is normally what you want. On the other hand, if you really do what to simulate actual keyboard keys for some reason, you would use InputManager.ProcessInput() instead.

Objective-C: Calling selectors with multiple arguments

@Shane Arney

performSelector:withObject:withObject:

You might also want to mention that this method is only for passing maximum 2 arguments, and it cannot be delayed. (such as performSelector:withObject:afterDelay:).

kinda weird that apple only supports 2 objects to be send and didnt make it more generic.

How can I check the system version of Android?

Given you have bash on your android device, you can use this bash function :

function androidCodeName {
    androidRelease=$(getprop ro.build.version.release)
    androidCodeName=$(getprop ro.build.version.codename)

    # Time "androidRelease" x10 to test it as an integer
    case $androidRelease in
        [0-9].[0-9]|[0-9].[0-9].|[0-9].[0-9].[0-9])  androidRelease=$(echo $androidRelease | cut -d. -f1-2 | tr -d .);;
        [0-9].) androidRelease=$(echo $androidRelease | sed 's/\./0/');;
        [0-9]) androidRelease+="0";;
    esac

    [ -n "$androidRelease" ] && [ $androidCodeName = REL ] && {
    # Do not use "androidCodeName" when it equals to "REL" but infer it from "androidRelease"
        androidCodeName=""
        case $androidRelease in
        10) androidCodeName+=NoCodename;;
        11) androidCodeName+="Petit Four";;
        15) androidCodeName+=Cupcake;;
        20|21) androidCodeName+=Eclair;;
        22) androidCodeName+=FroYo;;
        23) androidCodeName+=Gingerbread;;
        30|31|32) androidCodeName+=Honeycomb;;
        40) androidCodeName+="Ice Cream Sandwich";;
        41|42|43) androidCodeName+="Jelly Bean";;
        44) androidCodeName+=KitKat;;
        50|51) androidCodeName+=Lollipop;;
        60) androidCodeName+=Marshmallow;;
        70|71) androidCodeName+=Nougat;;
        80|81) androidCodeName+=Oreo;;
        90) androidCodeName+=Pie;;
        100) androidCodeName+=ToBeReleased;;
        *) androidCodeName=unknown;;
        esac
    }
    echo $androidCodeName
}

Task.Run with Parameter(s)?

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

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

Edit

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

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

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

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

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

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

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

You must first decorate RunAsync with async:

private async void RunAsync()

Important Note

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

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

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

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

Side Note

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

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

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

Git mergetool generates unwanted .orig files

You have to be a little careful with using kdiff3 as while git mergetool can be configured to save a .orig file during merging, the default behaviour for kdiff3 is to also save a .orig backup file independently of git mergetool.

You have to make sure that mergetool backup is off:

git config --global mergetool.keepBackup false

and also that kdiff3's settings are set to not create a backup:

Configure/Options => Directory Merge => Backup Files (*.orig)

How can I create a simple index.html file which lists all files/directories?

If you have a staging server that has directory listing enabled, then you can copy the index.html to the production server.

For example:

wget https://staging/dir/index.html

# do any additional processing on index.html

scp index.html prod/dir

Get domain name

I found this question by the title. If anyone else is looking for the answer on how to just get the domain name, use the following environment variable.

System.Environment.UserDomainName

I'm aware that the author to the question mentions this, but I missed it at the first glance and thought someone else might do the same.

What the description of the question then ask for is the fully qualified domain name (FQDN).

Android - Dynamically Add Views into View

See the LayoutInflater class.

LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewGroup parent = (ViewGroup)findViewById(R.id.where_you_want_to_insert);
inflater.inflate(R.layout.the_child_view, parent);

Finding CN of users in Active Directory

Most common AD default design is to have a container, cn=users just after the root of the domain. Thus a DN might be:

cn=admin,cn=users,DC=domain,DC=company,DC=com

Also, you might have sufficient rights in an LDAP bind to connect anonymously, and query for (cn=admin). If so, you should get the full DN back in that query.

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to center a subview of UIView

1. If you have autolayout enabled:

  • Hint: For centering a view on another view with autolayout you can use same code for any two views sharing at least one parent view.

First of all disable child views autoresizing

UIView *view1, *view2;
[childview setTranslatesAutoresizingMaskIntoConstraints:NO];
  1. If you are UIView+Autolayout or Purelayout:

    [view1 autoAlignAxis:ALAxisHorizontal toSameAxisOfView:view2];
    [view1 autoAlignAxis:ALAxisVertical toSameAxisOfView:view2];
    
  2. If you are using only UIKit level autolayout methods:

    [view1 addConstraints:({
        @[ [NSLayoutConstraint
           constraintWithItem:view1
           attribute:NSLayoutAttributeCenterX
           relatedBy:NSLayoutRelationEqual
           toItem:view2
           attribute:NSLayoutAttributeCenterX
           multiplier:1.f constant:0.f],
    
           [NSLayoutConstraint
            constraintWithItem:view1
            attribute:NSLayoutAttributeCenterY
            relatedBy:NSLayoutRelationEqual
            toItem:view2
            attribute:NSLayoutAttributeCenterY
            multiplier:1.f constant:0.f] ];
    })];
    

2. Without autolayout:

I prefer:

UIView *parentView, *childView;
[childView setFrame:({
    CGRect frame = childView.frame;

    frame.origin.x = (parentView.frame.size.width - frame.size.width) / 2.0;
    frame.origin.y = (parentView.frame.size.height - frame.size.height) / 2.0;

    CGRectIntegral(frame);
})];

ORA-12514 TNS:listener does not currently know of service requested in connect descriptor

I know this is an old question, but still unanswered. It took me a day of research, but I found the simplest solution, at least in my case (Oracle 11.2 on Windows 2008 R2) and wanted to share.

The error, if looked at directly, indicates that the listener does not recognize the service name. But where does it keep service names? In %ORACLE_HOME%\NETWORK\ADMIN\listener.ora

The "SID_LIST" is just that, a list of SIDs and service names paired up in a format you can copy or lookup.

I added the problem Service Name, then in Windows "Services" control panel, I did a "Restart" on the Oracle listener service. Now all is well.


For example, your listener.ora file might initially look like:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

... And to make it recognize a service name of orcl, you might change it to:

# listener.ora Network Configuration File: C:\app\oracle_user\product\12.1.0\dbhome_1\network\admin\listener.ora
# Generated by Oracle configuration tools.

SID_LIST_LISTENER =
  (SID_LIST =
    (SID_DESC =
      (SID_NAME = CLRExtProc)
      (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
      (PROGRAM = extproc)
      (ENVS = "EXTPROC_DLLS=ONLY:C:\app\oracle_user\product\12.1.0\dbhome_1\bin\oraclr12.dll")
    )
    (SID_DESC = 
        (GLOBAL_DBNAME = orcl)
        (ORACLE_HOME = C:\app\oracle_user\product\12.1.0\dbhome_1)
        (SID_NAME = orcl)
    )
  )

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
    )
  )

Utilizing multi core for tar+gzip/bzip compression/decompression

You can also use the tar flag "--use-compress-program=" to tell tar what compression program to use.

For example use:

tar -c --use-compress-program=pigz -f tar.file dir_to_zip 

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

VB.NET: how to prevent user input in a ComboBox

---- in form level Declaration of cbx veriable---

Dim cbx as string

Private Sub comboBox1_Enter(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBox1.Enter
    cbx = Me.comboBox1.Text
End Sub

Private Sub comboBox1_Leave(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles comboBox1.Leave
    Me.comboBox1.Text = cbx
End Sub

How can I append a query parameter to an existing URL?

There are plenty of libraries that can help you with URI building (don't reinvent the wheel). Here are three to get you started:


Java EE 7

import javax.ws.rs.core.UriBuilder;
...
return UriBuilder.fromUri(url).queryParam(key, value).build();

org.apache.httpcomponents:httpclient:4.5.2

import org.apache.http.client.utils.URIBuilder;
...
return new URIBuilder(url).addParameter(key, value).build();

org.springframework:spring-web:4.2.5.RELEASE

import org.springframework.web.util.UriComponentsBuilder;
...
return UriComponentsBuilder.fromUriString(url).queryParam(key, value).build().toUri();

See also: GIST > URI Builder Tests

How to Validate a DateTime in C#?

DateTime temp;
try
{
    temp = Convert.ToDateTime(date);
    date = temp.ToString("yyyy/MM/dd");
}
catch 
{
    MessageBox.Show("Sorry The date not valid", "Error", MessageBoxButtons.OK, MessageBoxIcon.Stop,MessageBoxDefaultButton.Button1,MessageBoxOptions .RightAlign);
    date = null;
}

how to run vibrate continuously in iphone?

There are numerous examples that show how to do this with a private CoreTelephony call: _CTServerConnectionSetVibratorState, but it's really not a sensible course of action since your app will get rejected for abusing the vibrate feature like that. Just don't do it.

JQuery How to extract value from href tag?

First of all you need to extract the path with something like this:

$("a#myLink").attr("href");

Then take a look at this plugin: http://plugins.jquery.com/project/query-object

It will help you handle all kinds of querystring things you want to do.

/Peter F

Loading context in Spring using web.xml

From the spring docs

Spring can be easily integrated into any Java-based web framework. All you need to do is to declare the ContextLoaderListener in your web.xml and use a contextConfigLocation to set which context files to load.

The <context-param>:

<context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param>

<listener>
   <listener-class>
        org.springframework.web.context.ContextLoaderListener
   </listener-class>
</listener> 

You can then use the WebApplicationContext to get a handle on your beans.

WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servlet.getServletContext());
SomeBean someBean = (SomeBean) ctx.getBean("someBean");

See http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/context/support/WebApplicationContextUtils.html for more info

How do I get PHP errors to display?

You can show Php error in your display via simple ways. Firstly, just put this below code in your php.ini file.

display_errors = on;

(if you don't have access to php.ini, then putting this line in .htaccess might work too):

php_flag display_errors 1

OR you can also use the following code in your index.php file

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

How to tell if string starts with a number with Python?

You can also use try...except:

try:
    int(string[0])
    # do your stuff
except:
    pass # or do your stuff

SQL keys, MUL vs PRI vs UNI

Walkthough on what is MUL, PRI and UNI in MySQL?

From the MySQL 5.7 documentation:

  • If Key is PRI, the column is a PRIMARY KEY or is one of the columns in a multiple-column PRIMARY KEY.
  • If Key is UNI, the column is the first column of a UNIQUE index. (A UNIQUE index permits multiple NULL values, but you can tell whether the column permits NULL by checking the Null field.)
  • If Key is MUL, the column is the first column of a nonunique index in which multiple occurrences of a given value are permitted within the column.

Live Examples

Control group, this example has neither PRI, MUL, nor UNI:

mysql> create table penguins (foo INT);
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with one column and an index on the one column has a MUL:

mysql> create table penguins (foo INT, index(foo));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with a column that is a primary key has PRI

mysql> create table penguins (foo INT primary key);
Query OK, 0 rows affected (0.02 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with a column that is a unique key has UNI:

mysql> create table penguins (foo INT unique);
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | UNI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

A table with an index covering foo and bar has MUL only on foo:

mysql> create table penguins (foo INT, bar INT, index(foo, bar));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

A table with two separate indexes on two columns has MUL for each one

mysql> create table penguins (foo INT, bar int, index(foo), index(bar));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
2 rows in set (0.00 sec)

A table with an Index spanning three columns has MUL on the first:

mysql> create table penguins (foo INT, 
       bar INT, 
       baz INT, 
       INDEX name (foo, bar, baz));
Query OK, 0 rows affected (0.01 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| foo   | int(11) | YES  | MUL | NULL    |       |
| bar   | int(11) | YES  |     | NULL    |       |
| baz   | int(11) | YES  |     | NULL    |       |
+-------+---------+------+-----+---------+-------+
3 rows in set (0.00 sec)

A table with a foreign key that references another table's primary key is MUL

mysql> create table penguins(id int primary key);
Query OK, 0 rows affected (0.01 sec)

mysql> create table skipper(id int, foreign key(id) references penguins(id));
Query OK, 0 rows affected (0.01 sec)

mysql> desc skipper;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | YES  | MUL | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

mysql> desc penguins;
+-------+---------+------+-----+---------+-------+
| Field | Type    | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+-------+
| id    | int(11) | NO   | PRI | NULL    |       |
+-------+---------+------+-----+---------+-------+
1 row in set (0.00 sec)

Stick that in your neocortex and set the dial to "frappe".

Search for a particular string in Oracle clob column

Below code can be used to search a particular string in Oracle clob column

select *  
from RLOS_BINARY_BP
where dbms_lob.instr(DED_ENQ_XML,'2003960067') > 0;

where RLOS_BINARY_BP is table name and DED_ENQ_XML is column name (with datatype as CLOB) of Oracle database.

Simple search MySQL database using php

`

require_once('functions.php');

$errors = FALSE;
$errorMessage = "";

if(mysqli_connect_error()){
  $errors = TRUE;
  $errorMessage .= "There was a connection error <br/>";
  errorDisplay($errorMessage);
  die($errors);
} else if($errors != "TRUE"){
  $errors .= FALSE;
}

if(isset(mysqli_real_escape_string($_POST['search']))){
  $search = mysqli_real_escape_string($_POST['search']);
  search(search);
}



?>
<?php
//This is functions.php
function search($searchQuery){
  echo "<div class="col-md-10 col-md-offset-1">";
  $searchTerm
  $query = query("SELECT * FROM `index` WHERE `keywords` LIKE '".$searchTerm."' ");
  while($row = mysqli_fetch_array($query)){
    $results = <<< DELIMITER
      <div class="result col-md-12">
        <a href="index.php?search={$row['id']}"> {$row['Title']} </a>
        <p class="searchDesc">{$row['description']}</p>
      </div>
DELIMITER;
    echo $results;
  }
  echo "</div>";
}

function errorDisplay($msg){
  if(!isset($_SESSION['errors'])){
    $_SESSION['errors'] = $msg;
    showError($msg);
  } else if() {
    $_SESSION['errors'] .= $msg . "<br>";
    showError($msg);
  }
}
function showError($msg) {
  return $msg;
  unset($_SESSION['errors']);
}


?>`
Perhaps That Helps?

"Full screen" <iframe>

Impossible to say without seeing a live example, but try giving both bodies margin: 0px

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

How do you easily create empty matrices javascript?

Array.fill

Consider using fill:

Array(9).fill().map(()=>Array(9).fill())

The idea here is that fill() will fill out the items with undefined, which is enough to get map to work on them.

You could also fill directly:

Array(9).fill(Array(9))

Alternatives to Array(9).fill() include

Array(...Array(9))
[].push(...Array(9))
[].concat(Array(9))
Array.from(Array(9))

We can rewrite the solution a bit more semantically as:

function array9() { return Array(9).fill(); }
array9().map(array9)

or

function array(n) { return Array(n).fill(); }
array(9).map(() => array(9))

Array.from provides us with an optional second mapping argument, so we have the alternative of writing

Array.from(Array(9), () => Array.from(Array(9));

or, if you prefer

function array9(map) { return Array.from(Array(9), map); }
array9(array9);

For verbose description and examples, see Mozilla's Docs on Array.prototype.fill() here.
and for Array.from(), here.

Note that neither Array.prototype.fill() nor Array.from() has support in Internet Explorer. A polyfill for IE is available at the above MDN links.

Partitioning

partition(Array(81), 9)

if you have a partition utility handy. Here's a quick recursive one:

function partition(a, n) {
  return a.length ? [a.splice(0, n)].concat(partition(a, n)) : [];
}  

Looping

We can loop a bit more efficiently with

var a = [], b;
while (a.push(b = []) < 9) while (b.push(null) < 9);

Taking advantage of the fact that push returns the new array length.

Java Swing revalidate() vs repaint()

revalidate() just request to layout the container, when you experienced simply call revalidate() works, it could be caused by the updating of child components bounds triggers the repaint() when their bounds are changed during the re-layout. In the case you mentioned, only component removed and no component bounds are changed, this case no repaint() is "accidentally" triggered.

How can you check for a #hash in a URL using JavaScript?

Put the following:

<script type="text/javascript">
    if (location.href.indexOf("#") != -1) {
        // Your code in here accessing the string like this
        // location.href.substr(location.href.indexOf("#"))
    }
</script>

twitter bootstrap navbar fixed top overlapping site

As I've posted in a similar question, I've had good success with creating a dummy non-fixed nav bar right before my real fixed nav bar.

<nav class="navbar navbar-default"></nav> <!-- Dummy nav bar -->
<nav class="navbar navbar-default navbar-fixed-top"> <!-- Real nav bar -->
    <!-- Nav bar details -->
</nav>

The spacing works out great on all screen sizes.

Change one value based on another value in pandas

This question might still be visited often enough that it's worth offering an addendum to Mr Kassies' answer. The dict built-in class can be sub-classed so that a default is returned for 'missing' keys. This mechanism works well for pandas. But see below.

In this way it's possible to avoid key errors.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> class SurnameMap(dict):
...     def __missing__(self, key):
...         return ''
...     
>>> surnamemap = SurnameMap()
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap[x])
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

The same thing can be done more simply in the following way. The use of the 'default' argument for the get method of a dict object makes it unnecessary to subclass a dict.

>>> import pandas as pd
>>> data = { 'ID': [ 101, 201, 301, 401 ] }
>>> df = pd.DataFrame(data)
>>> surnamemap = {}
>>> surnamemap[101] = 'Mohanty'
>>> surnamemap[301] = 'Drake'
>>> df['Surname'] = df['ID'].apply(lambda x: surnamemap.get(x, ''))
>>> df
    ID  Surname
0  101  Mohanty
1  201         
2  301    Drake
3  401         

Replace new line/return with space using regex

You May use first split and rejoin it using white space. it will work sure.

String[] Larray = L.split("[\\n]+");
L = "";
for(int i = 0; i<Larray.lengh; i++){
   L = L+" "+Larray[i];  
}

How to find longest string in the table column data

SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) ASC LIMIT 1;
SELECT CITY,LENGTH(CITY) FROM STATION GROUP BY CITY ORDER BY LENGTH(CITY) DESC LIMIT 1;

How do I add target="_blank" to a link within a specified div?

Use this for every external link

$('a[href^="http://"], a[href^="https://"]').attr('target', '_blank');

Abstract Class:-Real Time Example

You should be able to cite at least one from the JDK itself. Look in the java.util.collections package. There are several abstract classes. You should fully understand interface, abstract, and concrete for Map and why Joshua Bloch wrote it that way.

Clearing a text field on button click

If you want to reset it, then simple use:

<input type="reset" value="Reset" />

But beware, it will not clear out textboxes that have default value. For example, if we have the following textboxes and by default, they have the following values:

<input id="textfield1" type="text" value="sample value 1" />
<input id="textfield2" type="text" value="sample value 2" />

So, to clear it out, compliment it with javascript:

function clearText()  
{
    document.getElementById('textfield1').value = "";
    document.getElementById('textfield2').value = "";
}  

And attach it to onclick of the reset button:
<input type="reset" value="Reset" onclick="clearText()" />

Monitor network activity in Android Phones

You would need to root the phone and cross compile tcpdump or use someone else's already compiled version.

You might find it easier to do these experiments with the emulator, in which case you could do the monitoring from the hosting pc. If you must use a real device, another option would be to put it on a wifi network hanging off of a secondary interface on a linux box running tcpdump.

I don't know off the top of my head how you would go about filtering by a specific process. One suggestion I found in some quick googling is to use strace on the subject process instead of tcpdump on the system.

Explicitly set column value to null SQL Developer

It is clear that most people who haven't used SQL Server Enterprise Manager don't understand the question (i.e. Justin Cave).

I came upon this post when I wanted to know the same thing.

Using SQL Server, when you are editing your data through the MS SQL Server GUI Tools, you can use a KEYBOARD SHORTCUT to insert a NULL rather than having just an EMPTY CELL, as they aren't the same thing. An empty cell can have a space in it, rather than being NULL, even if it is technically empty. The difference is when you intentionally WANT to put a NULL in a cell rather than a SPACE or to empty it and NOT using a SQL statement to do so.

So, the question really is, how do I put a NULL value in the cell INSTEAD of a space to empty the cell?

I think the answer is, that the way the Oracle Developer GUI works, is as Laniel indicated above, And THAT should be marked as the answer to this question.

Oracle Developer seems to default to NULL when you empty a cell the way the op is describing it.

Additionally, you can force Oracle Developer to change how your null cells look by changing the color of the background color to further demonstrate when a cell holds a null:

Tools->Preferences->Advanced->Display Null Using Background Color

or even the VALUE it shows when it's null:

Tools->Preferences->Advanced->Display Null Value As

Hope that helps in your transition.

The property 'Id' is part of the object's key information and cannot be modified

Another strange behavior in my case I have a table without any primary key.EF itself creates composite primary key using all columns i.e.:

 <Key>
        <PropertyRef Name="ID" />
        <PropertyRef Name="No" />
       <PropertyRef Name="Code" />
   </Key>

And whenever I do any update operation it throws this exception:

The property 'Code' is part of the object's key information and cannot be modified.

Solution: remove table from EF diagram and go to your DB add primary key on table that is creating problem and re-add table to EF diagram it's all now it will have single key i.e.

<Key>
        <PropertyRef Name="ID" />
</Key>

How to do if-else in Thymeleaf?

I tried this code to find out if a customer is logged in or anonymous. I did using the th:if and th:unless conditional expressions. Pretty simple way to do it.

<!-- IF CUSTOMER IS ANONYMOUS -->
<div th:if="${customer.anonymous}">
   <div>Welcome, Guest</div>
</div>
<!-- ELSE -->
<div th:unless="${customer.anonymous}">
   <div th:text=" 'Hi,' + ${customer.name}">Hi, User</div>
</div>

LF will be replaced by CRLF in git - What is that and is it important?

If you want, you can deactivate this feature in your git core config using

git config core.autocrlf false

But it would be better to just get rid of the warnings using

git config core.autocrlf true

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

I had a similar issue; turns out it was case-sensitivity issue. So, make sure you use the proper case.

Convert a Unicode string to a string in Python (containing extra symbols)

If you have a Unicode string, and you want to write this to a file, or other serialised form, you must first encode it into a particular representation that can be stored. There are several common Unicode encodings, such as UTF-16 (uses two bytes for most Unicode characters) or UTF-8 (1-4 bytes / codepoint depending on the character), etc. To convert that string into a particular encoding, you can use:

>>> s= u'£10'
>>> s.encode('utf8')
'\xc2\x9c10'
>>> s.encode('utf16')
'\xff\xfe\x9c\x001\x000\x00'

This raw string of bytes can be written to a file. However, note that when reading it back, you must know what encoding it is in and decode it using that same encoding.

When writing to files, you can get rid of this manual encode/decode process by using the codecs module. So, to open a file that encodes all Unicode strings into UTF-8, use:

import codecs
f = codecs.open('path/to/file.txt','w','utf8')
f.write(my_unicode_string)  # Stored on disk as UTF-8

Do note that anything else that is using these files must understand what encoding the file is in if they want to read them. If you are the only one doing the reading/writing this isn't a problem, otherwise make sure that you write in a form understandable by whatever else uses the files.

In Python 3, this form of file access is the default, and the built-in open function will take an encoding parameter and always translate to/from Unicode strings (the default string object in Python 3) for files opened in text mode.