Programs & Examples On #Deployment target

Round integers to the nearest 10

About the round(..) function returning a float

That float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)

See the discussion here for details.

Printing string variable in Java

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);

Please read the tutorial on how to use it as it will explain all.

Edit
Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

SQL: Select columns with NULL values only

You'll have to loop over the set of columns and check each one. You should be able to get a list of all columns with a DESCRIBE table command.

Pseudo-code:


foreach $column ($cols) {
   query("SELECT count(*) FROM table WHERE $column IS NOT NULL")
   if($result is zero)  {
      # $column contains only null values"
      push @onlyNullColumns, $column;
   } else {
      # $column contains non-null values
   }
}
return @onlyNullColumns;

I know this seems a little counterintuitive but SQL does not provide a native method of selecting columns, only rows.

Exception: Unexpected end of ZLIB input stream

You have to call close() on the GZIPOutputStream before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush() probably won't help ... though calling finish() instead of close() should work. Look at the javadocs.)

Here's the correct code (in Java);

package test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;

public class GZipTest {

    public static void main(String[] args) throws
                FileNotFoundException, IOException {
        String name = "/tmp/test";
        GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
        gz.write(10);
        gz.close();       // Remove this to reproduce the reported bug
        System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
    }
}

(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)

How do I run a bat file in the background from another bat file?

Actually is quite easy with this option at the end:

c:\start BATCH.bat -WindowStyle Hidden

Value cannot be null. Parameter name: source

Make sure you are injecting the repository into the service's constructor. That solved it for me. ::smacks forehead::

Django: Redirect to previous page after login

In registration/login.html (nested within templates folder) if you insert the following line, the page will render like Django's original admin login page:

{% include "admin/login.html" %}

Note: The file should contain above lines only.

How to find distinct rows with field in list using JPA and Spring?

Have you tried rewording your query like this?

@Query("SELECT DISTINCT p.name FROM People p WHERE p.name NOT IN ?1")
List<String> findNonReferencedNames(List<String> names);

Note, I'm assuming your entity class is named People, and not people.

How to connect access database in c#

You are building a DataGridView on the fly and set the DataSource for it. That's good, but then do you add the DataGridView to the Controls collection of the hosting form?

this.Controls.Add(dataGridView1);

By the way the code is a bit confused

String connection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\Tables.accdb;Persist Security Info=True";
string sql  = "SELECT Clients  FROM Tables";
using(OleDbConnection conn = new OleDbConnection(connection))
{
     conn.Open();
     DataSet ds = new DataSet();
     DataGridView dataGridView1 = new DataGridView();
     using(OleDbDataAdapter adapter = new OleDbDataAdapter(sql,conn))
     {
         adapter.Fill(ds);
         dataGridView1.DataSource = ds;
         // Of course, before addint the datagrid to the hosting form you need to 
         // set position, location and other useful properties. 
         // Why don't you create the DataGrid with the designer and use that instance instead?
         this.Controls.Add(dataGridView1);
     }
}

EDIT After the comments below it is clear that there is a bit of confusion between the file name (TABLES.ACCDB) and the name of the table CLIENTS.
The SELECT statement is defined (in its basic form) as

 SELECT field_names_list FROM _tablename_

so the correct syntax to use for retrieving all the clients data is

 string sql  = "SELECT * FROM Clients";

where the * means -> all the fields present in the table

java.lang.NoClassDefFoundError:failed resolution of :Lorg/apache/http/ProtocolVersion

Do any of the following:

1- Update the play-services-maps library to the latest version:

com.google.android.gms:play-services-maps:16.1.0

2- Or include the following declaration within the <application> element of AndroidManifest.xml.

<uses-library
      android:name="org.apache.http.legacy"
      android:required="false" />

How to add certificate chain to keystore?

From the keytool man - it imports certificate chain, if input is given in PKCS#7 format, otherwise only the single certificate is imported. You should be able to convert certificates to PKCS#7 format with openssl, via openssl crl2pkcs7 command.

Add key value pair to all objects in array

You may also try this:

arrOfObj.forEach(function(item){item.isActive = true;});

console.log(arrOfObj);

What does cmd /C mean?

The part you should be interested in is the /? part, which should solve most other questions you have with the tool.

Microsoft Windows XP [Version 5.1.2600]
(C) Copyright 1985-2001 Microsoft Corp.

C:\>cmd /?
Starts a new instance of the Windows XP command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OFF]
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
/K      Carries out the command specified by string but remains
/S      Modifies the treatment of string after /C or /K (see below)
/Q      Turns echo off
/D      Disable execution of AutoRun commands from registry (see below)
/A      Causes the output of internal commands to a pipe or file to be ANSI
/U      Causes the output of internal commands to a pipe or file to be
        Unicode
/T:fg   Sets the foreground/background colors (see COLOR /? for more info)
/E:ON   Enable command extensions (see below)
/E:OFF  Disable command extensions (see below)
/F:ON   Enable file and directory name completion characters (see below)
/F:OFF  Disable file and directory name completion characters (see below)
/V:ON   Enable delayed environment variable expansion using ! as the
        delimiter. For example, /V:ON would allow !var! to expand the
        variable var at execution time.  The var syntax expands variables
        at input time, which is quite a different thing when inside of a FOR
        loop.
/V:OFF  Disable delayed environment expansion.

Where does Android emulator store SQLite database?

The other answers are severely outdated. With Android Studio, this is the way to do it:

  1. Click on Tools > Android > Android Device Monitor

enter image description here

  1. Click on File Explorer

enter image description here

  1. Navigate to your db file and click on the Save button.

enter image description here

Injecting $scope into an angular service function()

You could make your service completely unaware of the scope, but in your controller allow the scope to be updated asynchronously.

The problem you're having is because you're unaware that http calls are made asynchronously, which means you don't get a value immediately as you might. For instance,

var students = $http.get(path).then(function (resp) {
  return resp.data;
}); // then() returns a promise object, not resp.data

There's a simple way to get around this and it's to supply a callback function.

.service('StudentService', [ '$http',
    function ($http) {
    // get some data via the $http
    var path = '/students';

    //save method create a new student if not already exists
    //else update the existing object
    this.save = function (student, doneCallback) {
      $http.post(
        path, 
        {
          params: {
            student: student
          }
        }
      )
      .then(function (resp) {
        doneCallback(resp.data); // when the async http call is done, execute the callback
      });  
    }
.controller('StudentSaveController', ['$scope', 'StudentService', function ($scope, StudentService) {
  $scope.saveUser = function (user) {
    StudentService.save(user, function (data) {
      $scope.message = data; // I'm assuming data is a string error returned from your REST API
    })
  }
}]);

The form:

<div class="form-message">{{message}}</div>

<div ng-controller="StudentSaveController">
  <form novalidate class="simple-form">
    Name: <input type="text" ng-model="user.name" /><br />
    E-mail: <input type="email" ng-model="user.email" /><br />
    Gender: <input type="radio" ng-model="user.gender" value="male" />male
    <input type="radio" ng-model="user.gender" value="female" />female<br />
    <input type="button" ng-click="reset()" value="Reset" />
    <input type="submit" ng-click="saveUser(user)" value="Save" />
  </form>
</div>

This removed some of your business logic for brevity and I haven't actually tested the code, but something like this would work. The main concept is passing a callback from the controller to the service which gets called later in the future. If you're familiar with NodeJS this is the same concept.

check if a file is open in Python

You could use with open("path") as file: so that it automatically closes, else if it's open in another process you can maybe try as in Tims example you should use except IOError to not ignore any other problem with your code :)

try:
   with open("path", "r") as file: # or just open
       # Code here
except IOError:
   # raise error or print

Python regex findall

Use this pattern,

pattern = '\[P\].+?\[\/P\]'

Check here

How do I enable logging for Spring Security?

You can easily enable debugging support using an option for the @EnableWebSecurity annotation:

@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    …
}

Encrypt and Decrypt in Java

Symmetric Key Cryptography : Symmetric key uses the same key for encryption and decryption. The main challenge with this type of cryptography is the exchange of the secret key between the two parties sender and receiver.

Example : The following example uses symmetric key for encryption and decryption algorithm available as part of the Sun's JCE(Java Cryptography Extension). Sun JCE is has two layers, the crypto API layer and the provider layer.

DES (Data Encryption Standard) was a popular symmetric key algorithm. Presently DES is outdated and considered insecure. Triple DES and a stronger variant of DES. It is a symmetric-key block cipher. There are other algorithms like Blowfish, Twofish and AES(Advanced Encryption Standard). AES is the latest encryption standard over the DES.

Steps :

  1. Add the Security Provider : We are using the SunJCE Provider that is available with the JDK.
  2. Generate Secret Key : Use KeyGenerator and an algorithm to generate a secret key. We are using DESede.
  3. Encode Text : For consistency across platform encode the plain text as byte using UTF-8 encoding.
  4. Encrypt Text : Instantiate Cipher with ENCRYPT_MODE, use the secret key and encrypt the bytes.
  5. Decrypt Text : Instantiate Cipher with DECRYPT_MODE, use the same secret key and decrypt the bytes.

All the above given steps and concept are same, we just replace algorithms.

import java.util.Base64;    
import javax.crypto.Cipher;  
import javax.crypto.KeyGenerator;   
import javax.crypto.SecretKey;  
public class EncryptionDecryptionAES {  
    static Cipher cipher;  

    public static void main(String[] args) throws Exception {
        /* 
         create key 
         If we need to generate a new key use a KeyGenerator
         If we have existing plaintext key use a SecretKeyFactory
        */ 
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(128); // block size is 128bits
        SecretKey secretKey = keyGenerator.generateKey();

        /*
          Cipher Info
          Algorithm : for the encryption of electronic data
          mode of operation : to avoid repeated blocks encrypt to the same values.
          padding: ensuring messages are the proper length necessary for certain ciphers 
          mode/padding are not used with stream cyphers.  
         */
        cipher = Cipher.getInstance("AES"); //SunJCE provider AES algorithm, mode(optional) and padding schema(optional)  

        String plainText = "AES Symmetric Encryption Decryption";
        System.out.println("Plain Text Before Encryption: " + plainText);

        String encryptedText = encrypt(plainText, secretKey);
        System.out.println("Encrypted Text After Encryption: " + encryptedText);

        String decryptedText = decrypt(encryptedText, secretKey);
        System.out.println("Decrypted Text After Decryption: " + decryptedText);
    }

    public static String encrypt(String plainText, SecretKey secretKey)
            throws Exception {
        byte[] plainTextByte = plainText.getBytes();
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedByte = cipher.doFinal(plainTextByte);
        Base64.Encoder encoder = Base64.getEncoder();
        String encryptedText = encoder.encodeToString(encryptedByte);
        return encryptedText;
    }

    public static String decrypt(String encryptedText, SecretKey secretKey)
            throws Exception {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encryptedTextByte = decoder.decode(encryptedText);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedByte = cipher.doFinal(encryptedTextByte);
        String decryptedText = new String(decryptedByte);
        return decryptedText;
    }
}

Output:

Plain Text Before Encryption: AES Symmetric Encryption Decryption
Encrypted Text After Encryption: sY6vkQrWRg0fvRzbqSAYxepeBIXg4AySj7Xh3x4vDv8TBTkNiTfca7wW/dxiMMJl
Decrypted Text After Decryption: AES Symmetric Encryption Decryption

Source

Example: Cipher with two modes, they are encrypt and decrypt. we have to start every time after setting mode to encrypt or decrypt a text. enter image description here

Javascript checkbox onChange

try

totalCost.value = checkbox.checked ? 10 : calculate();

_x000D_
_x000D_
function change(checkbox) {_x000D_
  totalCost.value = checkbox.checked ? 10 : calculate();_x000D_
}_x000D_
_x000D_
function calculate() {_x000D_
  return other.value*2;_x000D_
}
_x000D_
input { display: block}
_x000D_
Checkbox: <input type="checkbox" onclick="change(this)"/>_x000D_
Total cost: <input id="totalCost" type="number" value=5 />_x000D_
Other: <input id="other" type="number" value=7 />
_x000D_
_x000D_
_x000D_

Saving lists to txt file

Framework 4: no need to use StreamWriter:

System.IO.File.WriteAllLines("SavedLists.txt", Lists.verbList);

What is the difference between XAMPP or WAMP Server & IIS?

WAMP [ Windows, Apache, Mysql, Php]

XAMPP [X-os, Apache, Mysql, Php , Perl ] (x-os : it can be used on any OS )

Both can be used to easily run and test websites and web applications locally. WAMP cannot be run parallel with XAMPP because with default installation XAMPP gets priority and it takes up ports.

WAMP easy to setup configuration in. WAMPServer has a graphical user interface to switch on or off individual component softwares while it is running. WAMPServer provide an option to switch among many versions of Apache, many versions of PHP and many versions of MySQL all installed which provide more flexibility towards developing while XAMPPServer doesn't have such an option. If you want to use Perl with WAMP you can configure Perl with WAMPServer http://phpflow.com/perl/how-to-configure-perl-on-wamp/ but it is better to go with XAMPP.

XAMPP is easy to use than WAMP. XAMPP is more powerful. XAMPP has a control panel from that you can start and stop individual components (such as MySQL,Apache etc.). XAMPP is more resource consuming than WAMP because of heavy amount of internal component softwares like Tomcat , FileZilla FTP server, Webalizer, Mercury Mail etc.So if you donot need high features better to go with WAMP. XAMPP also has SSL feature which WAMP doesn't.(Secure Sockets Layer (SSL) is a networking protocol that manages server authentication, client authentication and encrypted communication between servers and clients. )

IIS acronym for Internet Information Server also an extensible web server initiated as a research project for for Microsoft NT.IIS can be used for making Web applications, search engines, and Web-based applications that access databases such as SQL Server within Microsoft OSs. . IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.

Add views below toolbar in CoordinatorLayout

As of Android studio 3.4, You need to put this line in your Layout which holds the RecyclerView.

app:layout_behavior="android.support.design.widget.AppBarLayout$ScrollingViewBehavior"

Server.UrlEncode vs. HttpUtility.UrlEncode

I had significant headaches with these methods before, I recommend you avoid any variant of UrlEncode, and instead use Uri.EscapeDataString - at least that one has a comprehensible behavior.

Let's see...

HttpUtility.UrlEncode(" ") == "+" //breaks ASP.NET when used in paths, non-
                                  //standard, undocumented.
Uri.EscapeUriString("a?b=e") == "a?b=e" // makes sense, but rarely what you
                                        // want, since you still need to
                                        // escape special characters yourself

But my personal favorite has got to be HttpUtility.UrlPathEncode - this thing is really incomprehensible. It encodes:

  • " " ==> "%20"
  • "100% true" ==> "100%%20true" (ok, your url is broken now)
  • "test A.aspx#anchor B" ==> "test%20A.aspx#anchor%20B"
  • "test A.aspx?hmm#anchor B" ==> "test%20A.aspx?hmm#anchor B" (note the difference with the previous escape sequence!)

It also has the lovelily specific MSDN documentation "Encodes the path portion of a URL string for reliable HTTP transmission from the Web server to a client." - without actually explaining what it does. You are less likely to shoot yourself in the foot with an Uzi...

In short, stick to Uri.EscapeDataString.

Given an array of numbers, return array of products of all other numbers (no division)

Just 2 passes up and down. Job done in O(N)

private static int[] multiply(int[] numbers) {
        int[] multiplied = new int[numbers.length];
        int total = 1;

        multiplied[0] = 1;
        for (int i = 1; i < numbers.length; i++) {
            multiplied[i] = numbers[i - 1] * multiplied[i - 1];
        }

        for (int j = numbers.length - 2; j >= 0; j--) {
            total *= numbers[j + 1];
            multiplied[j] = total * multiplied[j];
        }

        return multiplied;
    }

Passing a variable to a powershell script via command line

Passed parameter like below,

Param([parameter(Mandatory=$true,
   HelpMessage="Enter name and key values")]
   $Name,
   $Key)

.\script_name.ps1 -Name name -Key key

How can I build for release/distribution on the Xcode 4?

The "play" button is specifically for build and run (or test or profile, etc). The Archive action is intended to build for release and to generate an archive that is suitable for submission to the app store. If you want to skip that, you can choose Product > Build For > Archive to force the release build without actually archiving. To find the built product, expand the Products group in the Project navigator, right-click the product and choose to show in Finder.

That said, you can click and hold the play button for a menu of other build actions (including Build and Archive).

How to drop a unique constraint from table column?

Expand to database name >> expand to table >> expand to keys >> copy the name of key then execute the below command:

ALTER TABLE Test DROP UQ__test__3213E83EB607700F;

Here UQ__test__3213E83EB607700F is the name of unique key which was created on a particular column on test table.

Map.Entry: How to use it?

Map.Entry interface helps us iterating a Map class

Check this simple example:

public class MapDemo {
    public static void main(String[] args) {
     Map<Integer,String> map=new HashMap();
     map.put(1, "Kamran");
        map.put(2, "Ali");
        map.put(3, "From");
        map.put(4, "Dir");
        map.put(5, "Lower");
        for(Map.Entry m:map.entrySet()){
        System.out.println(m.getKey()+"  "+m.getValue());
        }
    }
}

How to modify values of JsonObject / JsonArray directly?

It's actually all in the documentation.
JSONObject and JSONArray can both be used to replace the standard data structure.
To implement a setter simply call a remove(String name) before a put(String name, Object value).

Here's an simple example:

public class BasicDB {

private JSONObject jData = new JSONObject;

public BasicDB(String username, String tagline) {
    try {
        jData.put("username", username);
        jData.put("tagline" , tagline);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String getUsername () { 
    String ret = null;
    try {
        ret = jData.getString("username");
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } 
    return ret;
}

public void setUsername (String username) { 
    try {
        jData.remove("username");
        jData.put("username" , username);
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public String getTagline () {
    String ret = null;
    try {
        ret = jData.getString("tagline");
    } catch (JSONException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    } 
    return ret;
}

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

use std::fill to populate vector with increasing numbers

I created a simple templated function, Sequence(), for generating sequences of numbers. The functionality follows the seq() function in R (link). The nice thing about this function is that it works for generating a variety of number sequences and types.

#include <iostream>
#include <vector>

template <typename T>
std::vector<T> Sequence(T min, T max, T by) {
  size_t n_elements = ((max - min) / by) + 1;
  std::vector<T> vec(n_elements);
  min -= by;
  for (size_t i = 0; i < vec.size(); ++i) {
    min += by;
    vec[i] = min;
  }
  return vec;
}

Example usage:

int main()
{
    auto vec = Sequence(0., 10., 0.5);
    for(auto &v : vec) {
        std::cout << v << std::endl;
    }
}

The only caveat is that all of the numbers should be of the same inferred type. In other words, for doubles or floats, include decimals for all of the inputs, as shown.

Updated: June 14, 2018

Is there an ignore command for git like there is for svn?

There is no special git ignore command.

Edit a .gitignore file located in the appropriate place within the working copy. You should then add this .gitignore and commit it. Everyone who clones that repo will than have those files ignored.

Note that only file names starting with / will be relative to the directory .gitignore resides in. Everything else will match files in whatever subdirectory.

You can also edit .git/info/exclude to ignore specific files just in that one working copy. The .git/info/exclude file will not be committed, and will thus only apply locally in this one working copy.

You can also set up a global file with patterns to ignore with git config --global core.excludesfile. This will locally apply to all git working copies on the same user's account.

Run git help gitignore and read the text for the details.

Firebase FCM notifications click_action payload

there is dual method for fcm fcm messaging notification and app notification in first your app reciever only message notification with body ,title and you can add color ,vibration not working,sound default. in 2nd you can full control what happen when you recieve message example onMessageReciever(RemoteMessage rMessage){ notification.setContentTitle(rMessage.getData().get("yourKey")); } you will recieve data with(yourKey) but that not from fcm message that from fcm cloud functions reguard

How to iterate through XML in Powershell?

You can also do it without the [xml] cast. (Although xpath is a world unto itself. https://www.w3schools.com/xml/xml_xpath.asp)

$xml = (select-xml -xpath / -path stack.xml).node
$xml.objects.object.property

Or just this, xpath is case sensitive. Both have the same output:

$xml = (select-xml -xpath /Objects/Object/Property -path stack.xml).node
$xml


Name         Type                                                #text
----         ----                                                -----
DisplayName  System.String                                       SQL Server (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Running
DisplayName  System.String                                       SQL Server Agent (MSSQLSERVER)
ServiceState Microsoft.SqlServer.Management.Smo.Wmi.ServiceState Stopped

SQL multiple column ordering

ORDER BY column1 DESC, column2

This sorts everything by column1 (descending) first, and then by column2 (ascending, which is the default) whenever the column1 fields for two or more rows are equal.

String field value length in mongoDB

For MongoDB 3.6 and newer:

The $expr operator allows the use of aggregation expressions within the query language, thus you can leverage the use of $strLenCP operator to check the length of the string as follows:

db.usercollection.find({ 
    "name": { "$exists": true },
    "$expr": { "$gt": [ { "$strLenCP": "$name" }, 40 ] } 
})

For MongoDB 3.4 and newer:

You can also use the aggregation framework with the $redact pipeline operator that allows you to proccess the logical condition with the $cond operator and uses the special operations $$KEEP to "keep" the document where the logical condition is true or $$PRUNE to "remove" the document where the condition was false.

This operation is similar to having a $project pipeline that selects the fields in the collection and creates a new field that holds the result from the logical condition query and then a subsequent $match, except that $redact uses a single pipeline stage which is more efficient.

As for the logical condition, there are String Aggregation Operators that you can use $strLenCP operator to check the length of the string. If the length is $gt a specified value, then this is a true match and the document is "kept". Otherwise it is "pruned" and discarded.


Consider running the following aggregate operation which demonstrates the above concept:

db.usercollection.aggregate([
    { "$match": { "name": { "$exists": true } } },
    {
        "$redact": {
            "$cond": [
                { "$gt": [ { "$strLenCP": "$name" }, 40] },
                "$$KEEP",
                "$$PRUNE"
            ]
        }
    },
    { "$limit": 2 }
])

If using $where, try your query without the enclosing brackets:

db.usercollection.find({$where: "this.name.length > 40"}).limit(2);

A better query would be to to check for the field's existence and then check the length:

db.usercollection.find({name: {$type: 2}, $where: "this.name.length > 40"}).limit(2); 

or:

db.usercollection.find({name: {$exists: true}, $where: "this.name.length > 
40"}).limit(2); 

MongoDB evaluates non-$where query operations before $where expressions and non-$where query statements may use an index. A much better performance is to store the length of the string as another field and then you can index or search on it; applying $where will be much slower compared to that. It's recommended to use JavaScript expressions and the $where operator as a last resort when you can't structure the data in any other way, or when you are dealing with a small subset of data.


A different and faster approach that avoids the use of the $where operator is the $regex operator. Consider the following pattern which searches for

db.usercollection.find({"name": {"$type": 2, "$regex": /^.{41,}$/}}).limit(2); 

Note - From the docs:

If an index exists for the field, then MongoDB matches the regular expression against the values in the index, which can be faster than a collection scan. Further optimization can occur if the regular expression is a “prefix expression”, which means that all potential matches start with the same string. This allows MongoDB to construct a “range” from that prefix and only match against those values from the index that fall within that range.

A regular expression is a “prefix expression” if it starts with a caret (^) or a left anchor (\A), followed by a string of simple symbols. For example, the regex /^abc.*/ will be optimized by matching only against the values from the index that start with abc.

Additionally, while /^a/, /^a.*/, and /^a.*$/ match equivalent strings, they have different performance characteristics. All of these expressions use an index if an appropriate index exists; however, /^a.*/, and /^a.*$/ are slower. /^a/ can stop scanning after matching the prefix.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Little Edit

Try adding

return new JavascriptResult() { Script = "alert('Successfully registered');" };

in place of

return RedirectToAction("Index");

Why is 1/1/1970 the "epoch time"?

History.

The earliest versions of Unix time had a 32-bit integer incrementing at a rate of 60 Hz, which was the rate of the system clock on the hardware of the early Unix systems. The value 60 Hz still appears in some software interfaces as a result. The epoch also differed from the current value. The first edition Unix Programmer's Manual dated November 3, 1971 defines the Unix time as "the time since 00:00:00, Jan. 1, 1971, measured in sixtieths of a second".

How can I change the font-size of a select option?

try this

http://jsfiddle.net/VggvD/2/

CSS add your code

.select_join option{
    font-size:13px;
}

MSIE and addEventListener Problem in Javascript?

As of IE11, you need to use addEventListener. attachEvent is deprecated and throws an error.

Error inflating when extending a class

It's important to write full class path in the xml. I got 'Error inflating class' when only subclass's name was written in.

Connect different Windows User in SQL Server Management Studio (2005 or later)

Hold shift and right click on SQL Server Mangement studion icon. You can Run as other windows account user.

Using sed and grep/egrep to search and replace

try something using a for loop

 for i in `egrep -lR "YOURSEARCH" .` ; do echo  $i; sed 's/f/k/' <$i >/tmp/`basename $i`; mv /tmp/`basename $i` $i; done

not pretty, but should do.

How to set specific Java version to Maven

One simple solution to the problem -

JAVA_HOME=/usr/lib/jvm/java-6-sun/ mvn clean install

On Mac, it would look something like -

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/Home/ mvn clean install

PS: One special case that i found is the above given command does not work on 'fish' shell. I also had bash shell available and it worked fine there. just use command 'bash' to switch to bash shell.

How do pointer-to-pointer's work in C? (and when might you use them?)

I like this "real world" code example of pointer to pointer usage, in Git 2.0, commit 7b1004b:

Linus once said:

I actually wish more people understood the really core low-level kind of coding. Not big, complex stuff like the lockless name lookup, but simply good use of pointers-to-pointers etc.
For example, I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing something like:


   if (prev)
     prev->next = entry->next;
   else
     list_head = entry->next;

and whenever I see code like that, I just go "This person doesn't understand pointers". And it's sadly quite common.

People who understand pointers just use a "pointer to the entry pointer", and initialize that with the address of the list_head. And then as they traverse the list, they can remove the entry without using any conditionals, by just doing a

*pp =  entry->next

pointers

Applying that simplification lets us lose 7 lines from this function even while adding 2 lines of comment.

- struct combine_diff_path *p, *pprev, *ptmp;
+ struct combine_diff_path *p, **tail = &curr;

Chris points out in the comments to the 2016 video "Linus Torvalds's Double Pointer Problem".


kumar points out in the comments the blog post "Linus on Understanding Pointers", where Grisha Trubetskoy explains:

Imagine you have a linked list defined as:

   typedef struct list_entry {
       int val;
       struct list_entry *next;
   } list_entry;

You need to iterate over it from the beginning to end and remove a specific element whose value equals the value of to_remove.
The more obvious way to do this would be:

   list_entry *entry = head; /* assuming head exists and is the first entry of the list */
   list_entry *prev = NULL;
   
   while (entry) { /* line 4 */
       if (entry->val == to_remove)     /* this is the one to remove ; line 5 */
           if (prev)
              prev->next = entry->next; /* remove the entry ; line 7 */
           else
               head = entry->next;      /* special case - first entry ; line 9 */
   
       /* move on to the next entry */
       prev = entry;
       entry = entry->next;
   }

What we are doing above is:

  • iterating over the list until entry is NULL, which means we’ve reached the end of the list (line 4).
  • When we come across an entry we want removed (line 5),
  • we assign the value of current next pointer to the previous one,
  • thus eliminating the current element (line 7).

There is a special case above - at the beginning of the iteration there is no previous entry (prev is NULL), and so to remove the first entry in the list you have to modify head itself (line 9).

What Linus was saying is that the above code could be simplified by making the previous element a pointer to a pointer rather than just a pointer.
The code then looks like this:

   list_entry **pp = &head; /* pointer to a pointer */
   list_entry *entry = head;

   while (entry) {
       if (entry->val == to_remove)
           *pp = entry->next;
       else
            pp = &entry->next;
       entry = entry->next;
   }

The above code is very similar to the previous variant, but notice how we no longer need to watch for the special case of the first element of the list, since pp is not NULL at the beginning. Simple and clever.

Also, someone in that thread commented that the reason this is better is because *pp = entry->next is atomic. It is most certainly NOT atomic.
The above expression contains two dereference operators (* and ->) and one assignment, and neither of those three things is atomic.
This is a common misconception, but alas pretty much nothing in C should ever be assumed to be atomic (including the ++ and -- operators)!

How to shrink temp tablespace in oracle?

The options for managing tablespaces have got a lot better over the versions starting with 8i. This is especially true if you are using the appropriate types of file for a temporary tablespace (i.e. locally managed tempfiles).

So, it could be as simple as this command, which will shrink your tablespace to 128 meg...

alter tablespace <your_temp_ts> shrink space keep 128M;

The Oracle online documentation is pretty good. Find out more.

edit

It would appear the OP has an earlier version of the database. With earlier versions we have to resize individual datafiles. So, first of all, find the file names. One or other of these queries should do it...

select file_name from dba_data_files where tablespace_name = '<your_temp_ts>'
/

select file_name from dba_temp_files where tablespace_name = '<your_temp_ts>'
/ 

Then use that path in this command:

alter database datafile '/full/file/path/temp01.dbf'  resize 128m
/

Python Web Crawlers and "getting" html source code

Use Python 2.7, is has more 3rd party libs at the moment. (Edit: see below).

I recommend you using the stdlib module urllib2, it will allow you to comfortably get web resources. Example:

import urllib2

response = urllib2.urlopen("http://google.de")
page_source = response.read()

For parsing the code, have a look at BeautifulSoup.

BTW: what exactly do you want to do:

Just for background, I need to download a page and replace any img with ones I have

Edit: It's 2014 now, most of the important libraries have been ported, and you should definitely use Python 3 if you can. python-requests is a very nice high-level library which is easier to use than urllib2.

Python socket receive - incoming packets always have a different size

That's the nature of TCP: the protocol fills up packets (lower layer being IP packets) and sends them. You can have some degree of control over the MTU (Maximum Transfer Unit).

In other words: you must devise a protocol that rides on top of TCP where your "payload delineation" is defined. By "payload delineation" I mean the way you extract the unit of message your protocol supports. This can be as simple as "every NULL terminated strings".

Place API key in Headers or URL

It should be put in the HTTP Authorization header. The spec is here https://tools.ietf.org/html/rfc7235

How to retrieve a module's path?

Here is a quick bash script in case it's useful to anyone. I just want to be able to set an environment variable so that I can pushd to the code.

#!/bin/bash
module=${1:?"I need a module name"}

python << EOI
import $module
import os
print os.path.dirname($module.__file__)
EOI

Shell example:

[root@sri-4625-0004 ~]# export LXML=$(get_python_path.sh lxml)
[root@sri-4625-0004 ~]# echo $LXML
/usr/lib64/python2.7/site-packages/lxml
[root@sri-4625-0004 ~]#

JAVA_HOME is set to an invalid directory:

You need to set with only C:\Program Files\Java\jdk1.8.0_12.

And check with using new cmd. It will be updated

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

How to use count and group by at the same select statement

Try the following code:

select ccode, count(empno) 
from company_details 
group by ccode;

How to check if a process is running via a batch script

I use PV.exe from http://www.teamcti.com/pview/prcview.htm installed in Program Files\PV with a batch file like this:

@echo off
PATH=%PATH%;%PROGRAMFILES%\PV;%PROGRAMFILES%\YourProgram
PV.EXE YourProgram.exe >nul
if ERRORLEVEL 1 goto Process_NotFound
:Process_Found
echo YourProgram is running
goto END
:Process_NotFound
echo YourProgram is not running
YourProgram.exe
goto END
:END

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

My real sample for MVC 3 is here:

<% using (Html.BeginForm()) { %>

<p>

Start Date: <%: Html.TextBox("datepicker1", DateTime.Now.ToString("MM/dd/yyyy"), new { style = "width:80px;", maxlength = 10 })%> 

End Date: <%: Html.TextBox("datepicker2", DateTime.Now.ToString("MM/dd/yyyy"), new { style = "width:80px;", maxlength = 10 })%> 

<input type="submit" name="btnSubmit" value="Search" /> 

</p>

<% } %>

So, we have following

"datepicker1" - ID of the control

DateTime.Now.ToString("MM/dd/yyyy") - value by default

style = "width:80px;" - width of the textbox

maxlength = 10 - we can input 10 characters only

change directory in batch file using variable

The set statement doesn't treat spaces the way you expect; your variable is really named Pathname[space] and is equal to [space]C:\Program Files.

Remove the spaces from both sides of the = sign, and put the value in double quotes:

set Pathname="C:\Program Files"

Also, if your command prompt is not open to C:\, then using cd alone can't change drives.

Use

cd /d %Pathname%

or

pushd %Pathname%

instead.

How do I generate a random int number?

Random r = new Random();
int n = r.Next();

The project was not built since its build path is incomplete

Here is what made the error disappear for me:

Close eclipse, open up a terminal window and run:

$ mvn clean eclipse:clean eclipse:eclipse

Are you using Maven? If so,

  1. Right-click on the project, Build Path and go to Configure Build Path
  2. Click the libraries tab. If Maven dependencies are not in the list, you need to add it.
  3. Close the dialog.

To add it: Right-click on the project, Maven → Disable Maven Nature Right-click on the project, Configure → Convert to Maven Project.

And then clean

Edit 1:

If that doesn't resolve the issue try right-clicking on your project and select properties. Select Java Build Path → Library tab. Look for a JVM. If it's not there, click to add Library and add the default JVM. If VM is there, click edit and select the default JVM. Hopefully, that works.

Edit 2:

You can also try going into the folder where you have all your projects and delete the .metadata for eclipse (be aware that you'll have to re-import all the projects afterwards! Also all the environment settings you've set would also have to be redone). After it was deleted just import the project again, and hopefully, it works.

How to install pip with Python 3?

If your Linux distro came with Python already installed, you should be able to install PIP using your system’s package manager. This is preferable since system-installed versions of Python do not play nicely with the get-pip.py script used on Windows and Mac.

Advanced Package Tool (Python 2.x)

sudo apt-get install python-pip

Advanced Package Tool (Python 3.x)

sudo apt-get install python3-pip

pacman Package Manager (Python 2.x)

sudo pacman -S python2-pip

pacman Package Manager (Python 3.x)

sudo pacman -S python-pip

Yum Package Manager (Python 2.x)

sudo yum upgrade python-setuptools
sudo yum install python-pip python-wheel

Yum Package Manager (Python 3.x)

sudo yum install python3 python3-wheel

Dandified Yum (Python 2.x)

sudo dnf upgrade python-setuptools
sudo dnf install python-pip python-wheel

Dandified Yum (Python 3.x)

sudo dnf install python3 python3-wheel

Zypper Package Manager (Python 2.x)

sudo zypper install python-pip python-setuptools python-wheel

Zypper Package Manager (Python 3.x)

sudo zypper install python3-pip python3-setuptools python3-wheel

What does jQuery.fn mean?

jQuery.fn is defined shorthand for jQuery.prototype. From the source code:

jQuery.fn = jQuery.prototype = {
    // ...
}

That means jQuery.fn.jquery is an alias for jQuery.prototype.jquery, which returns the current jQuery version. Again from the source code:

// The current version of jQuery being used
jquery: "@VERSION",

How do I define and use an ENUM in Objective-C?

In the .h:

typedef enum {
    PlayerStateOff,
    PlayerStatePlaying,
    PlayerStatePaused
} PlayerState;

What does "#pragma comment" mean?

The answers and the documentation provided by MSDN is the best, but I would like to add one typical case that I use a lot which requires the use of #pragma comment to send a command to the linker at link time for example

#pragma comment(linker,"/ENTRY:Entry")

tell the linker to change the entry point form WinMain() to Entry() after that the CRTStartup going to transfer controll to Entry()

How to get the <html> tag HTML with JavaScript / jQuery?

The simplest way to get the html element natively is:

document.documentElement

Here's the reference: https://developer.mozilla.org/en-US/docs/Web/API/Document.documentElement.

UPDATE: To then grab the html element as a string you would do:

document.documentElement.outerHTML

What are the differences between a clustered and a non-clustered index?

Clustered Index

  • Only one per table
  • Faster to read than non clustered as data is physically stored in index order

Non Clustered Index

  • Can be used many times per table
  • Quicker for insert and update operations than a clustered index

Both types of index will improve performance when select data with fields that use the index but will slow down update and insert operations.

Because of the slower insert and update clustered indexes should be set on a field that is normally incremental ie Id or Timestamp.

SQL Server will normally only use an index if its selectivity is above 95%.

How to call a function after delay in Kotlin?

A simple example to show a toast after 3 seconds :

fun onBtnClick() {
    val handler = Handler()
    handler.postDelayed({ showToast() }, 3000)
}

fun showToast(){
    Toast.makeText(context, "Its toast!", Toast.LENGTH_SHORT).show()
}

How do I use HTML as the view engine in Express?

to server html pages through routing, I have done this.

var hbs = require('express-hbs');
app.engine('hbs', hbs.express4({
  partialsDir: __dirname + '/views/partials'
}));
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');

and renamed my .html files to .hbs files - handlebars support plain html

Python - AttributeError: 'numpy.ndarray' object has no attribute 'append'

Numpy arrays do not have an append method. Use the Numpy append function instead:

import numpy as np

array_3 = np.append(array_1, array_2, axis=n)
# you can either specify an integer axis value n or remove the keyword argument completely

For example, if array_1 and array_2 have the following values:

array_1 = np.array([1, 2])
array_2 = np.array([3, 4])

If you call np.append without specifying an axis value, like so:

array_3 = np.append(array_1, array_2)

array_3 will have the following value:

array([1, 2, 3, 4])

Else, if you call np.append with an axis value of 0, like so:

array_3 = np.append(array_1, array_2, axis=0)

array_3 will have the following value:

 array([[1, 2],
        [3, 4]]) 

More information on the append function here: https://docs.scipy.org/doc/numpy/reference/generated/numpy.append.html

Java: Reading a file into an array

Here is some example code to help you get started:

package com.acme;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileArrayProvider {

    public String[] readLines(String filename) throws IOException {
        FileReader fileReader = new FileReader(filename);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> lines = new ArrayList<String>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            lines.add(line);
        }
        bufferedReader.close();
        return lines.toArray(new String[lines.size()]);
    }
}

And an example unit test:

package com.acme;

import java.io.IOException;

import org.junit.Test;

public class FileArrayProviderTest {

    @Test
    public void testFileArrayProvider() throws IOException {
        FileArrayProvider fap = new FileArrayProvider();
        String[] lines = fap
                .readLines("src/main/java/com/acme/FileArrayProvider.java");
        for (String line : lines) {
            System.out.println(line);
        }
    }
}

Hope this helps.

Node Version Manager install - nvm command not found

For MacOS;

Run on Terminal >

open ~/.bash_profile

Paste all of this=

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && . "$NVM_DIR/nvm.sh" # This loads nvm

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

Enum.valueOf() only checks the constant name, so you need to pass it "COLUMN_HEADINGS" instead of "columnHeadings". Your name property has nothing to do with Enum internals.


To address the questions/concerns in the comments:

The enum's "builtin" (implicitly declared) valueOf(String name) method will look up an enum constant with that exact name. If your input is "columnHeadings", you have (at least) three choices:

  1. Forget about the naming conventions for a bit and just name your constants as it makes most sense: enum PropName { contents, columnHeadings, ...}. This is obviously the most convenient.
  2. Convert your camelCase input into UPPER_SNAKE_CASE before calling valueOf, if you're really fond of naming conventions.
  3. Implement your own lookup method instead of the builtin valueOf to find the corresponding constant for an input. This makes most sense if there are multiple possible mappings for the same set of constants.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

You can access the Axes instance (ax) with plt.gca(). In this case, you can use

plt.gca().legend()

You can do this either by using the label= keyword in each of your plt.plot() calls or by assigning your labels as a tuple or list within legend, as in this working example:

import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-0.75,1,100)
y0 = np.exp(2 + 3*x - 7*x**3)
y1 = 7-4*np.sin(4*x)
plt.plot(x,y0,x,y1)
plt.gca().legend(('y0','y1'))
plt.show()

pltGcaLegend

However, if you need to access the Axes instance more that once, I do recommend saving it to the variable ax with

ax = plt.gca()

and then calling ax instead of plt.gca().

How do I install SciPy on 64 bit Windows?

It is terrible to install such Python data science packages independently on Windows. Try Anaconda (one installer, 400 more Python packages, py2 & py3 support). Anaconda really helps me a lot!

compilation error: identifier expected

You must to wrap your following code into a block (Either method or static).

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("What is your name?");
String name = in.readLine(); ;
System.out.println("Hello " + name);

Without a block you can only declare variables and more than that assign them a value in single statement.

For method main() will be best choice for now:

public class details {
    public static void main(String[] args){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

or If you want to use static block then...

public class details {
    static {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

or if you want to build another method then..

public class details {
    public static void main(String[] args){
        myMethod();
    }
    private static void myMethod(){
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("What is your name?");
        String name = in.readLine(); ;
        System.out.println("Hello " + name);
    }
}

Also worry about exception due to BufferedReader .

How to escape apostrophe (') in MySql?

Possibly off-topic, but maybe you came here looking for a way to sanitise text input from an HTML form, so that when a user inputs the apostrophe character, it doesn't throw an error when you try to write the text to an SQL-based table in a DB. There are a couple of ways to do this, and you might want to read about SQL injection too. Here's an example of using prepared statements and bound parameters in PHP:

$input_str = "Here's a string with some apostrophes (')";
// sanitise it before writing to the DB (assumes PDO)
$sql = "INSERT INTO `table` (`note`) VALUES (:note)";
try {
    $stmt = $dbh->prepare($sql);
    $stmt->bindParam(':note', $input_str, PDO::PARAM_STR);
    $stmt->execute();
} catch (PDOException $e) {
    return $dbh->errorInfo();
}
return "success";

In the special case where you may want to store your apostrophes using their HTML entity references, PHP has the htmlspecialchars() function which will convert them to &#039;. As the comments indicate, this should not be used as a substitute for proper sanitisation, as per the example given.

Remove multiple whitespaces

I can't replicate the problem here:

$x = "this    \n \t\t \n    works.";
var_dump(preg_replace('/\s\s+/', ' ', $x));
// string(11) "this works."

I'm not sure if it was just a transcription error or not, but in your example, you're using a single-quoted string. \n and \t are only treated as new-line and tab if you've got a double quoted string. That is:

'\n\t' != "\n\t"

Edit: as Codaddict pointed out, \s\s+ won't replace a single tab character. I still don't think using \s+ is an efficient solution though, so how about this instead:

preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x);

How to connect android wifi to adhoc wifi?

If you specifically want to use an ad hoc wireless network, then Andy's answer seems to be your only option. However, if you just want to share your laptop's internet connection via Wi-fi using any means necessary, then you have at least two more options:

  1. Use your laptop as a router to create a wifi hotspot using Virtual Router or Connectify. A nice set of instructions can be found here.
  2. Use the Wi-fi Direct protocol which creates a direct connection between any devices that support it, although with Android devices support is limited* and with Windows the feature seems likely to be Windows 8 only.

*Some phones with Android 2.3 have proprietary OS extensions that enable Wi-fi Direct (mostly newer Samsung phones), but Android 4 should fully support this (source).

Rails 4 - passing variable to partial

You need the full render partial syntax if you are passing locals

<%= render @users, :locals => {:size => 30} %>

Becomes

<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>

Or to use the new hash syntax

<%= render partial: 'users', collection: @users, locals: {size: 30} %>

Which I think is much more readable

link_to method and click event in Rails

To follow up on Ron's answer if using JQuery and putting it in application.js or the head section you need to wrap it in a ready() section...

$(document).ready(function() {
  $('#my-link').click(function(event){
    alert('Hooray!');
    event.preventDefault(); // Prevent link from following its href
  });
});

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

When you call ScriptManager.RegisterStartupScript, the "Control" parameter must be a control that is within an UpdatePanel that will be updated. You need to change it to:

ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), script, true);

Strip all non-numeric characters from string in JavaScript

try

myString.match(/\d/g).join``

_x000D_
_x000D_
var myString = 'abc123.8<blah>'_x000D_
console.log( myString.match(/\d/g).join`` );
_x000D_
_x000D_
_x000D_

Should I use pt or px?

A pt is 1/72th of an inch and is a useless measure for anything that is rendered on a device which doesn't calculate the DPI correctly. This makes it a reasonable choice for printing and a dreadful choice for use on screen.

A px is a pixel, which will map on to a screen pixel in most cases.

CSS provides a bunch of other units, and which one you should choose depends on what you are setting the size of.

A pixel is great if you need to size something to match an image, or if you want a thin border.

Percentages are great for font sizes as, if you use them consistently, you get font sizes proportional to the user's preference.

Ems are great when you want an element to size itself based on the font size (so a paragraph might get wider if the font size is larger)

… and so on.

Twitter Bootstrap carousel different height images cause bouncing arrows

 .className{
 width: auto;
  height: 200px;
  max-height: 200px;
   max-width:200px
   object-fit: contain;
}

What characters are forbidden in Windows and Linux directory names?

When creating internet shortcuts in Windows, to create the file name, it skips illegal characters, except for forward slash, which is converted to minus.

Merge unequal dataframes and replace missing rows with 0

Or, as an alternative to @Chase's code, being a recent plyr fan with a background in databases:

require(plyr)
zz<-join(df1, df2, type="left")
zz[is.na(zz)] <- 0

How to toggle (hide / show) sidebar div using jQuery

$(document).ready(function () {
    $(".trigger").click(function () {
        $("#sidebar").toggle("fast");
        $("#sidebar").toggleClass("active");
        return false;
    });
});


<div>
    <a class="trigger" href="#">
        <img id="icon-menu" alt='menu' height='50' src="Images/Push Pin.png" width='50' />
    </a>
</div>
<div id="sidebar">
</div>

Instead #sidebar give the id of ur div.

How to resolve 'npm should be run outside of the node repl, in your normal shell'

Do not run the application using node.js icon.

Go to All Programmes->Node.js->Node.js command prompt.

Below is example screen shot.

enter image description here

enter image description here

Bootstrap carousel width and height

Are you trying to make it responsive? If you are then I would just recommend the following:

.tales {
  width: 100%;
}
.carousel-inner{
  width:100%;
  max-height: 200px !important;
}

However, the best way to handle this responsively would be thru the use of media queries like such:

/* Smaller than standard 960 (devices and browsers) */
@media only screen and (max-width: 959px) {}

/* Tablet Portrait size to standard 960 (devices and browsers) */
@media only screen and (min-width: 768px) and (max-width: 959px) {}

/* All Mobile Sizes (devices and browser) */
@media only screen and (max-width: 767px) {}

/* Mobile Landscape Size to Tablet Portrait (devices and browsers) */
@media only screen and (min-width: 480px) and (max-width: 767px) {}

/* Mobile Portrait Size to Mobile Landscape Size (devices and browsers) */
@media only screen and (max-width: 479px) {}

MySQL - How to select data by string length

select * from *tablename* where 1 having length(*fieldname*)=*fieldlength*

Example if you want to select from customer the entry's with a name shorter then 2 chars.

select * from customer where 1 **having length(name)<2**

Python Inverse of a Matrix

If you hate numpy, get out RPy and your local copy of R, and use it instead.

(I would also echo to make you you really need to invert the matrix. In R, for example, linalg.solve and the solve() function don't actually do a full inversion, since it is unnecessary.)

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

I agree with @pkozlowski.opensource answer, but ng-clock class did't work for me for using with ng-repeat. so I would like to recommend you to use class for simple delimiter expression like {{name}} and ngCloak directive for ng-repeat.

<div class="ng-cloak">{{name}}<div>

and

<li ng-repeat="item in items" ng-cloak>{{item.name}}<li>

Sorting arrays in javascript by object key value

Not spectacular different than the answers already given, but more generic is :

sortArrayOfObjects = (arr, key) => {
    return arr.sort((a, b) => {
        return a[key] - b[key];
    });
};

sortArrayOfObjects(yourArray, "distance");

Postgres DB Size Command

You can get the names of all the databases that you can connect to from the "pg_datbase" system table. Just apply the function to the names, as below.

select t1.datname AS db_name,  
       pg_size_pretty(pg_database_size(t1.datname)) as db_size
from pg_database t1
order by pg_database_size(t1.datname) desc;

If you intend the output to be consumed by a machine instead of a human, you can cut the pg_size_pretty() function.

How to read a line from a text file in c/c++?

getline() is what you're looking for. You use strings in C++, and you don't need to know the size ahead of time.

Assuming std namespace:

 ifstream file1("myfile.txt");
 string stuff;

 while (getline(file1, stuff, '\n')) {
      cout << stuff << endl;
 }

 file1.close();

How to add a TextView to LinearLayout in Android

Here's where the exception occurs

((LinearLayout) linearLayout).addView(valueTV);

addView method takes in a parameter of type View, not TextView. Therefore, typecast the valueTv object into a View object, explicitly.

Therefore, the corrected code would be :

((LinearLayout) linearLayout).addView((TextView)valueTV);

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

Static link of shared library function in gcc

Yeah, I know this is an 8 year-old question, but I was told that it was possible to statically link against a shared-object library and this was literally the top hit when I searched for more information about it.

To actually demonstrate that statically linking a shared-object library is not possible with ld (gcc's linker) -- as opposed to just a bunch of people insisting that it's not possible -- use the following gcc command:

gcc -o executablename objectname.o -Wl,-Bstatic -l:libnamespec.so

(Of course you'll have to compile objectname.o from sourcename.c, and you should probably make up your own shared-object library as well. If you do, use -Wl,--library-path,. so that ld can find your library in the local directory.)

The actual error you receive is:

/usr/bin/ld: attempted static link of dynamic object `libnamespec.so'
collect2: error: ld returned 1 exit status

Hope that helps.

MySQL Delete all rows from table and reset ID to zero

If you cannot use TRUNCATE (e.g. because of foreign key constraints) you can use an alter table after deleting all rows to restart the auto_increment:

ALTER TABLE mytable AUTO_INCREMENT = 1

MySQL error - #1932 - Table 'phpmyadmin.pma user config' doesn't exist in engine

make change in changes in /opt/lampp/phpmyadmin/config.inc.php    

<?php
    /* vim: set expandtab sw=4 ts=4 sts=4: */
    /**
     * phpMyAdmin sample configuration, you can use it as base for
     * manual configuration. For easier setup you can use setup/
     *
     * All directives are explained in documentation in the doc/ folder
     * or at <http://docs.phpmyadmin.net/>.
     *
     * @package PhpMyAdmin
     */

    /**
     * This is needed for cookie based authentication to encrypt password in
     * cookie
     */
    $cfg['blowfish_secret'] = 'xampp'; /* YOU SHOULD CHANGE THIS FOR A MORE SECURE COOKIE AUTH! */

    /**
     * Servers configuration
     */
    $i = 0;

    /**
     * First server
     */
    $i++;
    /* Authentication type */
    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    /* Server parameters */
    //$cfg['Servers'][$i]['host'] = 'localhost';
    //$cfg['Servers'][$i]['connect_type'] = 'tcp';
    $cfg['Servers'][$i]['compress'] = false;
    $cfg['Servers'][$i]['AllowNoPassword'] = true;

    /**
     * phpMyAdmin configuration storage settings.
     */

    /* User used to manipulate with storage */
    // $cfg['Servers'][$i]['controlhost'] = '';
    // $cfg['Servers'][$i]['controlport'] = '';



    $cfg['Servers'][1]['pmadb'] = 'phpmyadmin';
    $cfg['Servers'][1]['controluser'] = 'pma';
    $cfg['Servers'][1]['controlpass'] = '';

    $cfg['Servers'][1]['bookmarktable'] = 'pma_bookmark';
    $cfg['Servers'][1]['relation'] = 'pma_relation';
    $cfg['Servers'][1]['userconfig'] = 'pma_userconfig';
    $cfg['Servers'][1]['table_info'] = 'pma_table_info';
    $cfg['Servers'][1]['column_info'] = 'pma_column_info';
    $cfg['Servers'][1]['history'] = 'pma_history';
    $cfg['Servers'][1]['recent'] = 'pma_recent';
    $cfg['Servers'][1]['table_uiprefs'] = 'pma_table_uiprefs';
    $cfg['Servers'][1]['tracking'] = 'pma_tracking';
    $cfg['Servers'][1]['table_coords'] = 'pma_table_coords';
    $cfg['Servers'][1]['pdf_pages'] = 'pma_pdf_pages';
    $cfg['Servers'][1]['designer_coords'] = 'pma_designer_coords';



    // $cfg['Servers'][$i]['favorite'] = 'pma__favorite';
    // $cfg['Servers'][$i]['users'] = 'pma__users';
    // $cfg['Servers'][$i]['usergroups'] = 'pma__usergroups';
    // $cfg['Servers'][$i]['navigationhiding'] = 'pma__navigationhiding';
    // $cfg['Servers'][$i]['savedsearches'] = 'pma__savedsearches';
    // $cfg['Servers'][$i]['central_columns'] = 'pma__central_columns';
    // $cfg['Servers'][$i]['designer_settings'] = 'pma__designer_settings';
    // $cfg['Servers'][$i]['export_templates'] = 'pma__export_templates';
    /* Contrib / Swekey authentication */
    // $cfg['Servers'][$i]['auth_swekey_config'] = '/etc/swekey-pma.conf';

    /**
     * End of servers configuration
     */

    /**
     * Directories for saving/loading files from server
     */
    $cfg['UploadDir'] = '';
    $cfg['SaveDir'] = '';

    /**
     * Whether to display icons or text or both icons and text in table row
     * action segment. Value can be either of 'icons', 'text' or 'both'.
     * default = 'both'
     */
    //$cfg['RowActionType'] = 'icons';

    /**
     * Defines whether a user should be displayed a "show all (records)"
     * button in browse mode or not.
     * default = false
     */
    //$cfg['ShowAll'] = true;

    /**
     * Number of rows displayed when browsing a result set. If the result
     * set contains more rows, "Previous" and "Next".
     * Possible values: 25, 50, 100, 250, 500
     * default = 25
     */
    //$cfg['MaxRows'] = 50;

    /**
     * Disallow editing of binary fields
     * valid values are:
     *   false    allow editing
     *   'blob'   allow editing except for BLOB fields
     *   'noblob' disallow editing except for BLOB fields
     *   'all'    disallow editing
     * default = 'blob'
     */
    //$cfg['ProtectBinary'] = false;

    /**
     * Default language to use, if not browser-defined or user-defined
     * (you find all languages in the locale folder)
     * uncomment the desired line:
     * default = 'en'
     */
    //$cfg['DefaultLang'] = 'en';
    //$cfg['DefaultLang'] = 'de';

    /**
     * How many columns should be used for table display of a database?
     * (a value larger than 1 results in some information being hidden)
     * default = 1
     */
    //$cfg['PropertiesNumColumns'] = 2;

    /**
     * Set to true if you want DB-based query history.If false, this utilizes
     * JS-routines to display query history (lost by window close)
     *
     * This requires configuration storage enabled, see above.
     * default = false
     */
    //$cfg['QueryHistoryDB'] = true;

    /**
     * When using DB-based query history, how many entries should be kept?
     * default = 25
     */
    //$cfg['QueryHistoryMax'] = 100;

    /**
     * Whether or not to query the user before sending the error report to
     * the phpMyAdmin team when a JavaScript error occurs
     *
     * Available options
     * ('ask' | 'always' | 'never')
     * default = 'ask'
     */
    //$cfg['SendErrorReports'] = 'always';

    /**
     * You can find more configuration options in the documentation
     * in the doc/ folder or at <http://docs.phpmyadmin.net/>.
     */

Inserting a tab character into text using C#

Try using the \t character in your strings

How to find the process id of a running Java process on Windows? And how to kill the process alone?

After setting the path of your jdk use JPS.Then You can eaisly kill it by Task Manager
JPS will give you all java processes

Remove scrollbars from textarea

style="overflow: hidden" and style="resize: none" were the ones that did the trick.

How to get the full path of the file from a file input

You cannot do so - the browser will not allow this because of security concerns. Although there are workarounds, the fact is that you shouldn't count on this working. The following Stack Overflow questions are relevant here:

In addition to these, the new HTML5 specification states that browsers will need to feed a Windows compatible fakepath into the input type="file" field, ostensibly for backward compatibility reasons.

So trying to obtain the path is worse then useless in newer browsers - you'll actually get a fake one instead.

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Go to phpMyAdmin/config.inc.php edit the line

$cfg['Servers'][$i]['password'] = '';

to

$cfg['Servers'][$i]['password'] = 'yourpassword';

This problem might occur due to setting of a password to root, thus phpmyadmin is not able to connect to the mysql database.

And the last thing change

$cfg['Servers'][$i]['extension'] = 'mysql';

to

$cfg['Servers'][$i]['extension'] = 'mysqli';

Now restart your server. and see.

Use Fieldset Legend with bootstrap

In bootstrap 4 it is much easier to have a border on the fieldset that blends with the legend. You don't need custom css to achieve it, it can be done like this:

<fieldset class="border p-2">
   <legend  class="w-auto">Your Legend</legend>
</fieldset>

which looks like this: bootstrap 4 fieldset and legend

Centering a canvas

Tested only on Firefox:

<script>
window.onload = window.onresize = function() {
    var C = 0.8;        // canvas width to viewport width ratio
    var W_TO_H = 2/1;   // canvas width to canvas height ratio
    var el = document.getElementById("a");

    // For IE compatibility http://www.google.com/search?q=get+viewport+size+js
    var viewportWidth = window.innerWidth;
    var viewportHeight = window.innerHeight;

    var canvasWidth = viewportWidth * C;
    var canvasHeight = canvasWidth / W_TO_H;
    el.style.position = "fixed";
    el.setAttribute("width", canvasWidth);
    el.setAttribute("height", canvasHeight);
    el.style.top = (viewportHeight - canvasHeight) / 2;
    el.style.left = (viewportWidth - canvasWidth) / 2;

    window.ctx = el.getContext("2d");
    ctx.clearRect(0,0,canvasWidth,canvasHeight);
    ctx.fillStyle = 'yellow';
    ctx.moveTo(0, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, 0);
    ctx.lineTo(canvasWidth, canvasHeight/2);
    ctx.lineTo(canvasWidth/2, canvasHeight);
    ctx.lineTo(0, canvasHeight/2);
    ctx.fill()
}
</script>

<body>
<canvas id="a" style="background: black">
</canvas>
</body>

What is the difference between UTF-8 and ISO-8859-1?

My reason for researching this question was from the perspective, is in what way are they compatible. Latin1 charset (iso-8859) is 100% compatible to be stored in a utf8 datastore. All ascii & extended-ascii chars will be stored as single-byte.

Going the other way, from utf8 to Latin1 charset may or may not work. If there are any 2-byte chars (chars beyond extended-ascii 255) they will not store in a Latin1 datastore.

Select Multiple Fields from List in Linq

public class Student
{
    public string Name { set; get; }
    public int ID { set; get; }
}

class Program
{
  static void Main(string[] args)
    {
        Student[] students =
        {
        new Student { Name="zoyeb" , ID=1},
        new Student { Name="Siddiq" , ID=2},
        new Student { Name="sam" , ID=3},
        new Student { Name="james" , ID=4},
        new Student { Name="sonia" , ID=5}
        };

        var studentCollection = from s in students select new { s.ID , s.Name};

        foreach (var student in studentCollection)
        {
            Console.WriteLine(student.Name);
            Console.WriteLine(student.ID);
        }
    }
}

How to format a JavaScript date

Other way that you can format the date:

function formatDate(dDate,sMode){
    var today = dDate;
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd<10) {
        dd = '0'+dd
    }
    if(mm<10) {
        mm = '0'+mm
    }
    if (sMode+""==""){
        sMode = "dd/mm/yyyy";
    }
    if (sMode == "yyyy-mm-dd"){
        return  yyyy + "-" + mm + "-" + dd + "";
    }
    if (sMode == "dd/mm/yyyy"){
        return  dd + "/" + mm + "/" + yyyy;
    }
}

DataRow: Select cell value by a given column name

for (int i=0;i < Table.Rows.Count;i++)
{
      Var YourValue = Table.Rows[i]["ColumnName"];
}

Equivalent of Clean & build in Android Studio?

It is probably not a correct way for clean, but I made that to delete unnecessary files, and take less size of a project. It continuously finds and deletes all build and Gradle folders made file clean.bat copy that into the folder where your project is

  set mypath=%cd% 
    for /d /r %mypath% %%a in (build\) do if exist "%%a" rmdir /s /q "%%a"
    for /d /r %mypath% %%a in (.gradle\) do if exist "%%a" rmdir /s /q "%%a"

Mask output of `The following objects are masked from....:` after calling attach() function

You use attach without detach - every time you do it new call to attach masks objects attached before (they contain the same names). Either use detach or do not use attach at all. Nice discussion and tips are here.

web-api POST body object always null

It can be helpful to add TRACING to the json serializer so you can see what's up when things go wrong.

Define an ITraceWriter implementation to show their debug output like:

class TraceWriter : Newtonsoft.Json.Serialization.ITraceWriter
{
    public TraceLevel LevelFilter {
        get {
            return TraceLevel.Error;
        }
    }

    public void Trace(TraceLevel level, string message, Exception ex)
    {
        Console.WriteLine("JSON {0} {1}: {2}", level, message, ex);
    }
}

Then in your WebApiConfig do:

    config.Formatters.JsonFormatter.SerializerSettings.TraceWriter = new TraceWriter();

(maybe wrap it in an #if DEBUG)

Entity Framework - Include Multiple Levels of Properties

If I understand you correctly you are asking about including nested properties. If so :

.Include(x => x.ApplicationsWithOverrideGroup.NestedProp)

or

.Include("ApplicationsWithOverrideGroup.NestedProp")  

or

.Include($"{nameof(ApplicationsWithOverrideGroup)}.{nameof(NestedProp)}")  

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

At the latest Google Play Services 15.0.0, it occurs this error when you include entire play service like this

implementation 'com.google.android.gms:play-services:15.0.0'

Instead, you must specific the detail service like Google Drive

com.google.android.gms:play-services-drive:15.0.0

mysql count group by having

Maybe

SELECT count(*) FROM (
    SELECT COUNT(*) FROM Movies GROUP BY ID HAVING count(Genre) = 4
) AS the_count_total

although that would not be the sum of all the movies, just how many have 4 genre's.

So maybe you want

SELECT sum(
    SELECT COUNT(*) FROM Movies GROUP BY ID having Count(Genre) = 4
) as the_sum_total

How to restore to a different database in sql server?

SQL Server 2008 R2:

For an existing database that you wish to "restore: from a backup of a different database follow these steps:

  1. From the toolbar, click the Activity Monitor button.
  2. Click processes. Filter by the database you want to restore. Kill all running processes by right clicking on each process and selecting "kill process".
  3. Right click on the database you wish to restore, and select Tasks-->Restore-->From Database.
  4. Select the "From Device:" radio button.
  5. Select ... and choose the backup file of the other database you wish to restore from.
  6. Select the backup set you wish to restore from by selecting the check box to the left of the backup set.
  7. Select "Options".
  8. Select Overwrite the existing database (WITH REPLACE)
  9. Important: Change the "Restore As" Rows Data file name to the file name of the existing database you wish to overwrite or just give it a new name.
  10. Do the same with the log file file name.
  11. Verify from the Activity Monitor Screen that no new processes were spawned. If they were, kill them.
  12. Click OK.

Java ArrayList clear() function

After data.clear() it will definitely start again from the zero index.

Multiple axis line chart in excel

There is a way of displaying 3 Y axis see here.

Excel supports Secondary Axis, i.e. only 2 Y axis. Other way would be to chart the 3rd one separately, and overlay on top of the main chart.

Using Position Relative/Absolute within a TD?

This trick also suitable, but in this case align properties (middle, bottom etc.) won't be working.

<td style="display: block; position: relative;">
</td>

How to install the current version of Go in Ubuntu Precise

  1. Download say, go1.6beta1.linux-amd64.tar.gz from https://golang.org/dl/ into /tmp

wget https://storage.googleapis.com/golang/go1.6beta1.linux-amd64.tar.gz -o /tmp/go1.6beta1.linux-amd64.tar.gz

  1. un-tar into /usr/local/bin

sudo tar -zxvf go1.6beta1.linux-amd64.tar.gz -C /usr/local/bin/

  1. Set GOROOT, GOPATH, [on ubuntu add following to ~/.bashrc]

mkdir ~/go export GOPATH=~/go export PATH=$PATH:$GOPATH/bin export GOROOT=/usr/local/bin/go export PATH=$PATH:$GOROOT/bin

  1. Verify

go version should show be

go version go1.6beta1 linux/amd64

go env should show be

GOARCH="amd64" GOBIN="" GOEXE="" GOHOSTARCH="amd64" GOHOSTOS="linux" GOOS="linux" GOPATH="/home/vats/go" GORACE="" GOROOT="/usr/local/bin/go" GOTOOLDIR="/usr/local/bin/go/pkg/tool/linux_amd64" GO15VENDOREXPERIMENT="1" CC="gcc" GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0" CXX="g++" CGO_ENABLED="1"

Is there an easy way to strike through text in an app widget?

I know, I am answering an old question, it might be helpful for someone else, for striking out a particular portion of TextView programmatically.

TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Text need to be set here", TextView.BufferType.SPANNABLE);
Spannable spannable = (Spannable) textView.getText();
spannable.setSpan(new StrikethroughSpan(), 5, 8, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);

So, in this example code, 5 is starting position and 8 is ending position of text need to be stricken out, so after running this code we can get the text "need" with striked out. Hope it will helpful for someone else.

ITextSharp insert text to an existing pdf

This worked for me and includes using OutputStream:

PdfReader reader = new PdfReader(new RandomAccessFileOrArray(Request.MapPath("Template.pdf")), null);
    Rectangle size = reader.GetPageSizeWithRotation(1);
    using (Stream outStream = Response.OutputStream)
    {
        Document document = new Document(size);
        PdfWriter writer = PdfWriter.GetInstance(document, outStream);

        document.Open();
        try
        {
            PdfContentByte cb = writer.DirectContent;

            cb.BeginText();
            try
            {
                cb.SetFontAndSize(BaseFont.CreateFont(), 12);
                cb.SetTextMatrix(110, 110);
                cb.ShowText("aaa");
            }
            finally
            {
                cb.EndText();
            }

                PdfImportedPage page = writer.GetImportedPage(reader, 1);
                cb.AddTemplate(page, 0, 0);

        }
        finally
        {
            document.Close();
            writer.Close();
            reader.Close();
        }
    }

Show spinner GIF during an $http request in AngularJS?

This works well for me:

HTML:

  <div id="loader" class="ng-hide" ng-show="req.$$state.pending">
    <img class="ajax-loader" 
         width="200" 
         height="200" 
         src="/images/spinner.gif" />
  </div>

Angular:

  $scope.req = $http.get("/admin/view/"+id).success(function(data) {          
      $scope.data = data;
  });

While the promise returned from $http is pending, ng-show will evaluate it to be "truthy". This is automatically updated once the promise is resolved... which is exactly what we want.

What does \0 stand for?

In C, \0 denotes a character with value zero. The following are identical:

char a = 0;
char b = '\0';

The utility of this escape sequence is greater inside string literals, which are arrays of characters:

char arr[] = "abc\0def\0ghi\0";

(Note that this array has two zero characters at the end, since string literals include a hidden, implicit terminal zero.)

Using curl POST with variables defined in bash script functions

Here's what actually worked for me, after guidance from answers here:

export BASH_VARIABLE="[1,2,3]"
curl http://localhost:8080/path -d "$(cat <<EOF
{
  "name": $BASH_VARIABLE,
  "something": [
    "value1",
    "value2",
    "value3"
  ]
}
EOF
)" -H 'Content-Type: application/json'

Swift programmatically navigate to another view controller/scene

SWIFT 4.x

The Strings in double quotes always confuse me, so I think answer to this question needs some graphical presentation to clear this out.

For a banking app, I have a LoginViewController and a BalanceViewController. Each have their respective screens.

The app starts and shows the Login screen. When login is successful, app opens the Balance screen.

Here is how it looks:

enter image description here

enter image description here

The login success is handled like this:

let storyBoard: UIStoryboard = UIStoryboard(name: "Balance", bundle: nil)
let balanceViewController = storyBoard.instantiateViewController(withIdentifier: "balance") as! BalanceViewController
self.present(balanceViewController, animated: true, completion: nil)

As you can see, the storyboard ID 'balance' in small letters is what goes in the second line of the code, and this is the ID which is defined in the storyboard settings, as in the attached screenshot.

The term 'Balance' with capital 'B' is the name of the storyboard file, which is used in the first line of the code.

We know that using hard coded Strings in code is a very bad practice, but somehow in iOS development it has become a common practice, and Xcode doesn't even warn about them.

Interface or an Abstract Class: which one to use?

The technical differences between an abstract class and an interface are already listed in the other answers precisely. I want to add an explanation to choose between a class and an interface while writing the code for the sake of object oriented programming.

A class should represent an entity whereas an interface should represent the behavior.

Let's take an example. A computer monitor is an entity and should be represented as a class.

class Monitor{
    private int monitorNo;
}

It is designed to provide a display interface to you, so the functionality should be defined by an interface.

interface Display{
    void display();
}

There are many other things to consider as explained in the other answers, but this is the most basic thing which most of the people ignore while coding.

Is recursion ever faster than looping?

Most answers here forget the obvious culprit why recursion is often slower than iterative solutions. It's linked with the build up and tear down of stack frames but is not exactly that. It's generally a big difference in the storage of the auto variable for each recursion. In an iterative algorithm with a loop, the variables are often held in registers and even if they spill, they will reside in the Level 1 cache. In a recursive algorithm, all intermediary states of the variable are stored on the stack, meaning they will engender many more spills to memory. This means that even if it makes the same amount of operations, it will have a lot memory accesses in the hot loop and what makes it worse, these memory operations have a lousy reuse rate making the caches less effective.

TL;DR recursive algorithms have generally a worse cache behavior than iterative ones.

python requests get cookies

If you need the path and thedomain for each cookie, which get_dict() is not exposes, you can parse the cookies manually, for instance:

[
    {'name': c.name, 'value': c.value, 'domain': c.domain, 'path': c.path}
    for c in session.cookies
]

Regular expression which matches a pattern, or is an empty string

I'm not sure why you'd want to validate an optional email address, but I'd suggest you use

^$|^[^@\s]+@[^@\s]+$

meaning

^$        empty string
|         or
^         beginning of string
[^@\s]+   any character but @ or whitespace
@         
[^@\s]+
$         end of string

You won't stop fake emails anyway, and this way you won't stop valid addresses.

A quick and easy way to join array elements with a separator (the opposite of split) in Java

Even easier you can just use Arrays, so you will get a String with the values of the array separated by a ","

String concat = Arrays.toString(myArray);

so you will end up with this: concat = "[a,b,c]"

Update

You can then get rid of the brackets using a sub-string as suggested by Jeff

concat = concat.substring(1, concat.length() -1);

so you end up with concat = "a,b,c"

if you want to use Kotlin:

 val concat = myArray.joinToString(separator = ",") //"a,b,c"

Git: Find the most recent common ancestor of two branches

With gitk you can view the two branches graphically:

gitk branch1 branch2

And then it's easy to find the common ancestor in the history of the two branches.

Difference between static memory allocation and dynamic memory allocation

There are three types of allocation — static, automatic, and dynamic.

Static Allocation means, that the memory for your variables is allocated when the program starts. The size is fixed when the program is created. It applies to global variables, file scope variables, and variables qualified with static defined inside functions.

Automatic memory allocation occurs for (non-static) variables defined inside functions, and is usually stored on the stack (though the C standard doesn't mandate that a stack is used). You do not have to reserve extra memory using them, but on the other hand, have also limited control over the lifetime of this memory. E.g: automatic variables in a function are only there until the function finishes.

void func() {
    int i; /* `i` only exists during `func` */
}

Dynamic memory allocation is a bit different. You now control the exact size and the lifetime of these memory locations. If you don't free it, you'll run into memory leaks, which may cause your application to crash, since at some point of time, system cannot allocate more memory.

int* func() {
    int* mem = malloc(1024);
    return mem;
}

int* mem = func(); /* still accessible */

In the upper example, the allocated memory is still valid and accessible, even though the function terminated. When you are done with the memory, you have to free it:

free(mem);

How can I run dos2unix on an entire directory?

for FILE in /var/www/html/files/*
do
 /usr/bin/dos2unix FILE
done

Trigger back-button functionality on button click in Android

You should use finish() when the user clicks on the button in order to go to the previous activity.

Button backButton = (Button)this.findViewById(R.id.back);
backButton.setOnClickListener(new OnClickListener() {
  @Override
  public void onClick(View v) {
    finish();
  }
});

Alternatively, if you really need to, you can try to trigger your own back key press:

this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));

Execute both of these.

XSL substring and indexOf

The following is the complete example containing both XML and XSLT where substring-before and substring-after are used

<?xml version="1.0" encoding="UTF-8"?>
<persons name="Group_SOEM">
    <person>
        <first>Joe Smith</first>
        <last>Joe Smith</last>
        <address>123 Main St, Anycity</address>
    </person>
</persons>    

The following is XSLT which changes value of first/last name by separating the value by space so that after applying this XSL the first name element will have value "Joe" and last "Smith".

<?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="first">
    <first>
        <xsl:value-of select="substring-before(.,' ')" />
    </first>
</xsl:template> 
<xsl:template match="last">
    <last>
        <xsl:value-of select="substring-after(.,' ')" />
    </last>
</xsl:template> 
<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()" />
    </xsl:copy>
</xsl:template>
</xsl:stylesheet>   

Regex to validate date format dd/mm/yyyy

For those who look at these and get completely confused, here is an excerpt from my script. Unfortunately, all it does is match valid numbers in a date time input, and 31st Feb will be marked as valid, but as so many have said, regex really isn't the best tool to do this test.

To match a date in the format 'yyyy-MM-dd hh:mm' (Or indeed in whatever order you please)

var dateerrors = false;
var yearReg = '(201[4-9]|202[0-9])';            ///< Allows a number between 2014 and 2029
var monthReg = '(0[1-9]|1[0-2])';               ///< Allows a number between 00 and 12
var dayReg = '(0[1-9]|1[0-9]|2[0-9]|3[0-1])';   ///< Allows a number between 00 and 31
var hourReg = '([0-1][0-9]|2[0-3])';            ///< Allows a number between 00 and 24
var minReg = '([0-5][0-9])';                    ///< Allows a number between 00 and 59
var reg = new RegExp('^' + yearReg + '-' + monthReg + '-' + dayReg + ' ' + hourReg + ':' + minReg + '$', 'g');
$('input').filter(function () {return this.id.match(/myhtml_element_with_id_\d+_datetime/);}).each(function (e) {
    if (e > 0) {
        // Don't test the first input. This will use the default
        var val = $(this).val();
        if (val && !val.trim().match(reg)) {
            dateerrors = true;
            return false;
        }
    }
});
if (dateerrors) {
    alert('You must enter a validate date in the format "yyyy-mm-dd HH:MM", e.g. 2019-12-31 19:30');
    return false;
}

The above script starts off by building a regex object. It then finds all of the inputs whose id's match a certain pattern and then loops through these. I don't test the first input I find (if (e > 0)).

A bit of explanation:

var reg = new RegExp('^' + yearReg + '-' + monthReg + '-' + dayReg + ' ' + hourReg + ':' + minReg + '$', 'g');

^ means start of match, whereas $ means end of match.

return this.id.match(/myhtml_element_with_id_\d+_datetime/);

\d+ means match a single or a contiguous sequence of integers, so myhtml_element_with_id_56_datetime and myhtml_element_with_id_2_datetime will match, but myhtml_element_with_id_5a_datetime will not

jQuery 'each' loop with JSON array

Try (untested):

$.getJSON("data.php", function(data){
    $.each(data.justIn, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.recent, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });
    $.each(data.old, function() {
        $.each(this, function(k, v) {
            alert(k + ' ' + v);
        });
    });    
});

I figured, three separate loops since you'll probably want to treat each dataset differently (justIn, recent, old). If not, you can do:

$.getJSON("data.php", function(data){
    $.each(data, function(k, v) {
        alert(k + ' ' + v);
        $.each(v, function(k1, v1) {
            alert(k1 + ' ' + v1);
        });
    });
}); 

How to delete a line from a text file in C#?

string fileIN = @"C:\myTextFile.txt";
string fileOUT = @"C:\myTextFile_Out.txt";
if (File.Exists(fileIN))
{
    string[] data = File.ReadAllLines(fileIN);
    foreach (string line in data)
        if (!line.Equals("my line to remove"))
            File.AppendAllText(fileOUT, line);
    File.Delete(fileIN);
    File.Move(fileOUT, fileIN);
}

Converting cv::Mat to IplImage*

 (you have cv::Mat old)
 IplImage copy = old;
 IplImage* new_image = &copy;

you work with new as an originally declared IplImage*.

Making a DateTime field in a database automatic?

You need to set the "default value" for the date field to getdate(). Any records inserted into the table will automatically have the insertion date as their value for this field.

The location of the "default value" property is dependent on the version of SQL Server Express you are running, but it should be visible if you select the date field of your table when editing the table.

JavaScript: Check if mouse button down?

The following snippet will attempt to execute the "doStuff" function 2 seconds after the mouseDown event occurs in document.body. If the user lifts up the button, the mouseUp event will occur and cancel the delayed execution.

I'd advise using some method for cross-browser event attachment - setting the mousedown and mouseup properties explicitly was done to simplify the example.

function doStuff() {
  // does something when mouse is down in body for longer than 2 seconds
}

var mousedownTimeout;

document.body.onmousedown = function() { 
  mousedownTimeout = window.setTimeout(doStuff, 2000);
}

document.body.onmouseup = function() {
  window.clearTimeout(mousedownTimeout);
}

Creating a BLOB from a Base64 string in JavaScript

If you can stand adding one dependency to your project there's the great blob-util npm package that provides a handy base64StringToBlob function. Once added to your package.json you can use it like this:

import { base64StringToBlob } from 'blob-util';

const contentType = 'image/png';
const b64Data = 'iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==';

const blob = base64StringToBlob(b64Data, contentType);

// Do whatever you need with your blob...

Referencing Row Number in R

Perhaps with dataframes one of the most easy and practical solution is:

data = dplyr::mutate(data, rownum=row_number())

How to export a mysql database using Command Prompt?

I was trying to take the dump of the db which was running on the docker and came up with the below command to achieve the same:

docker exec <container_id/name> /usr/bin/mysqldump -u <db_username> --password=<db_password> db_name > .sql

Hope this helps!

ascending/descending in LINQ - can one change the order via parameter?

You can easily create your own extension method on IEnumerable or IQueryable:

public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
    (this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
    (this IQueryable<TSource> source,
     Expression<Func<TSource, TKey>> keySelector,
     bool descending)
{
    return descending ? source.OrderByDescending(keySelector)
                      : source.OrderBy(keySelector);
}

Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:

var query = dataList.OrderByWithDirection(x => x.Property, direction);

Check if value exists in column in VBA

Just to modify scott's answer to make it a function:

Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant

    Dim LookAtWhat As Integer

    If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart

    With RngIn
        Set FindFirstInRange = .Find(What:=FindString, _
                                     After:=.Cells(.Cells.Count), _
                                     LookIn:=xlValues, _
                                     LookAt:=LookAtWhat, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=UseCase)

        If FindFirstInRange Is Nothing Then FindFirstInRange = False

    End With

End Function

This returns FALSE if the value isn't found, and if it's found, it returns the range.

You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.

I took out the TRIM because you can add that beforehand if you want to.

An example:

MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address

That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:

MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address

You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.

Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.

What is default color for text in textview?

It may not be possible in all situations, but why not simply use the value of a different random TextView that exists in the same Activity and that carries the colour you are looking for?

txtOk.setTextColor(txtSomeOtherText.getCurrentTextColor());

Finding the Eclipse Version Number

(Update September 2012):

MRT points out in the comments that "Eclipse Version" question references a .eclipseproduct in the main folder, and it contains:

name=Eclipse Platform
id=org.eclipse.platform
version=3.x.0

So that seems more straightforward than my original answer below.

Also, Neeme Praks mentions below that there is a eclipse/configuration/config.ini which includes a line like:

eclipse.buildId=4.4.1.M20140925-0400

Again easier to find, as those are Java properties set and found with System.getProperty("eclipse.buildId").


Original answer (April 2009)

For Eclipse Helios 3.6, you can deduce the Eclipse Platform version directly from the About screen:
It is a combination of the Eclipse global version and the build Id:

alt text

Here is an example for Eclipse 3.6M6:
The version would be: 3.6.0.v201003121448, after the version 3.6.0 and the build Id I20100312-1448 (an Integration build from March 12th, 2010 at 14h48

To see it more easily, click on "Plugin Details" and sort by Version.


Note: Eclipse3.6 has a brand new cool logo:

alt text

And you can see the build Id now being displayed during the loading step of the different plugin.

Valid content-type for XML, HTML and XHTML documents

HTML: text/html, full-stop.

XHTML: application/xhtml+xml, or only if following HTML compatbility guidelines, text/html. See the W3 Media Types Note.

XML: text/xml, application/xml (RFC 2376).

There are also many other media types based around XML, for example application/rss+xml or image/svg+xml. It's a safe bet that any unrecognised but registered ending in +xml is XML-based. See the IANA list for registered media types ending in +xml.

(For unregistered x- types, all bets are off, but you'd hope +xml would be respected.)

How do I integrate Ajax with Django applications?

When we use Django:

Server ===> Client(Browser)   
      Send a page

When you click button and send the form,
----------------------------
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      Send a page after doing sth with these data
----------------------------

If you want to keep old data, you can do it without Ajax. (Page will be refreshed)

Server ===> Client(Browser)   
      Send a page
Server <=== Client(Browser)  
      Give data back. (data in form will be lost)
Server ===> Client(Browser)  
      1. Send a page after doing sth with data
      2. Insert data into form and make it like before. 
      After these thing, server will send a html page to client. It means that server do more work, however, the way to work is same.

Or you can do with Ajax (Page will be not refreshed)

--------------------------
<Initialization> 
Server ===> Client(Browser) [from URL1]    
      Give a page                      
--------------------------  
<Communication>
Server <=== Client(Browser)     
      Give data struct back but not to refresh the page.
Server ===> Client(Browser) [from URL2] 
      Give a data struct(such as JSON)
---------------------------------

If you use Ajax, you must do these:

  1. Initial a HTML page using URL1 (we usually initial page by Django template). And then server send client a html page.
  2. Use Ajax to communicate with server using URL2. And then server send client a data struct.

Django is different from Ajax. The reason for this is as follows:

  • The thing return to client is different. The case of Django is HTML page. The case of Ajax is data struct.
  • Django is good at creating something, but it only can create once, it cannot change anything. Django is like anime, consist of many picture. By contrast, Ajax is not good at creating sth but good at change sth in exist html page.

In my opinion, if you would like to use ajax everywhere. when you need to initial a page with data at first, you can use Django with Ajax. But in some case, you just need a static page without anything from server, you need not use Django template.

If you don't think Ajax is the best practice. you can use Django template to do everything, like anime.

(My English is not good)

Is PowerShell ready to replace my Cygwin shell on Windows?

I have only recently started dabbling in PowerShell with any degree of seriousness. Although for the past seven years I've worked in an almost exclusively Windows-based environment, I come from a Unix background and find myself constantly trying to "Unix-fy" my interaction experience on Windows. It's frustrating to say the least.

It's only fair to compare PowerShell to something like Bash, tcsh, or zsh since utilities like grep, sed, awk, find, etc. are not, strictly speaking, part of the shell; they will always, however, be part of any Unix environment. That said, a PowerShell command like Select-String has a very similar function to grep and is bundled as a core module in PowerShell ... so the lines can be a little blurred.

I think the key thing is culture, and the fact that the respective tool-sets will embody their respective cultures:

  • Unix is a file-based, (in general, non Unicode) text-based culture. Configuration files are almost exclusively text files. Windows, on the other hand has always been far more structured in respect of configuration formats--configurations are generally kept in proprietary databases (e.g., the Windows registry) which require specialised tools for their management.
  • The Unix administrative (and, for many years, development) interface has traditionally been the command line and the virtual terminal. Windows started off as a GUI and administrative functions have only recently started moving away from being exclusively GUI-based. We can expect the Unix experience on the command line to be a richer, more mature one given the significant lead it has on PowerShell, and my experience matches this. On this, in my experience:

    • The Unix administrative experience is geared towards making things easy to do in a minimal amount of key strokes; this is probably as a result of the historical situation of having to administer a server over a slow 9600 baud dial-up connection. Now PowerShell does have aliases which go a long way to getting around the rather verbose Verb-Noun standard, but getting to know those aliases is a bit of a pain (anyone know of something better than: alias | where {$_.ResolvedCommandName -eq "<command>"}?).

      An example of the rich way in which history can be manipulated:

      iptables commands are often long-winded and repeating them with slight differences would be a pain if it weren't for just one of many neat features of history manipulation built into Bash, so inserting an iptables rule like the following:

      iptables -I camera-1-internet -s 192.168.0.50 -m state --state NEW -j ACCEPT

      a second time for another camera ("camera-2"), is just a case of issuing:

      !!:s/-1-/-2-/:s/50/51

      which means "perform the previous command, but substitute -1- with -2- and 50 with 51.

    • The Unix experience is optimised for touch-typists; one can pretty much do everything without leaving the "home" position. For example, in Bash, using the Emacs key bindings (yes, Bash also supports vi bindings), cycling through the history is done using Ctrl-P and Ctrl-N whilst moving to the start and end of a line is done using Ctrl-A and Ctrl-E respectively ... and it definitely doesn't end there. Try even the simplest of navigation in the PowerShell console without moving from the home position and you're in trouble.

    • Simple things like versatile paging (a la less) on Unix don't seem to be available out-of-the-box in PowerShell which is a little frustrating, and a rich editor experience doesn't exist either. Of course, one can always download third-party tools that will fill those gaps, but it sure would be nice if these things were just "there" like they are on pretty much any flavour of Unix.
  • The Windows culture, at least in terms of system API's is largely driven by the supporting frameworks, viz., COM and .NET, both of-which are highly structured and object-based. On the other hand, access to Unix APIs has traditionally been through a file interface (/dev and /proc) or (non-object-oriented) C-style library calls. It's no surprise then that the scripting experiences match their respective OS paradigms. PowerShell is by nature structured (everything is an object) and Bash-and-friends file-based. The structured API which is at the disposal of a PowerShell programmer is vast (essentially matching the vastness of the existing set of standard COM and .NET interfaces).

In short, although the scripting capabilities of PowerShell are arguably more powerful than Bash (especially when you consider the availability of the .NET BCL), the interactive experience is significantly weaker, particularly if you're coming at it from an entirely keyboard-driven, console-based perspective (as many Unix-heads are).

Inserting code in this LaTeX document with indentation

Since it wasn't yet mentioned here, it may be worth to add one more option, package spverbatim (no syntax highlighting):

\documentclass{article}
\usepackage{spverbatim}

\begin{document}

\begin{spverbatim}
  Your code here
\end{spverbatim}

\end{document}

Also, if syntax highlighting is not required, package alltt:

\documentclass{article}
\usepackage{alltt}

\begin{document}

\begin{alltt}
  Your code here
\end{alltt}

\end{document}

java.net.BindException: Address already in use: JVM_Bind <null>:80

I do a goofy mistake and It take me 2 hour to solve It.I mentioned it here for other persons may be help them.The mistake was I enable ssl connector and changed both https and http ports to same number .

The best way to remove duplicate values from NSMutableArray in Objective-C?

I know this is an old question, but there is a more elegant way to remove duplicates in a NSArray if you don't care about the order.

If we use Object Operators from Key Value Coding we can do this:

uniquearray = [yourarray valueForKeyPath:@"@distinctUnionOfObjects.self"];

As AnthoPak also noted it is possible to remove duplicates based on a property. An example would be: @distinctUnionOfObjects.name

replacing text in a file with Python

If your file is short (or even not extremely long), you can use the following snippet to replace text in place:

# Replace variables in file
with open('path/to/in-out-file', 'r+') as f:
    content = f.read()
    f.seek(0)
    f.truncate()
    f.write(content.replace('replace this', 'with this'))

Clear terminal in Python

If you are on a Linux/UNIX system then printing the ANSI escape sequence to clear the screen should do the job. You will also want to move cursor to the top of the screen. This will work on any terminal that supports ANSI.

import sys
sys.stderr.write("\x1b[2J\x1b[H")

This will not work on Windows unless ANSI support has been enabled. There may be an equivalent control sequence for Windows, but I do not know.

NodeJS - Error installing with NPM

for me the solution was:

rm -rf  ~/.node_gyp and
sudo npm install -g [email protected]
cd /usr/local/lib sudo ln -s ../../lib/libSystem.B.dylib libgcc_s.10.5.dylib 
brew install gcc
npm install

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

There's no need for all the code mentioned by galambalazs. The cross-browser way to do it in pure JavaScript is simply to test document.readyState:

if (document.readyState === "complete") { init(); }

This is also how jQuery does it.

Depending on where the JavaScript is loaded, this can be done inside an interval:

var readyStateCheckInterval = setInterval(function() {
    if (document.readyState === "complete") {
        clearInterval(readyStateCheckInterval);
        init();
    }
}, 10);

In fact, document.readyState can have three states:

Returns "loading" while the document is loading, "interactive" once it is finished parsing but still loading sub-resources, and "complete" once it has loaded. -- document.readyState at Mozilla Developer Network

So if you only need the DOM to be ready, check for document.readyState === "interactive". If you need the whole page to be ready, including images, check for document.readyState === "complete".

Update using LINQ to SQL

AdventureWorksDataContext db = new AdventureWorksDataContext();
db.Log = Console.Out;

// Get hte first customer record
Customer c = from cust in db.Customers select cust where id = 5;
Console.WriteLine(c.CustomerType);
c.CustomerType = 'I';
db.SubmitChanges(); // Save the changes away

Locate Git installation folder on Mac OS X

If you have fresh installation / update of Xcode, it is possible that your git binary can't be executed (I had mine under /usr/bin/git). To fix this problem just run the Xcode and "Accept" license conditions and try again, it should work.

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Also remember that they all encode different sets of characters, and select the one you need appropriately. encodeURI() encodes fewer characters than encodeURIComponent(), which encodes fewer (and also different, to dannyp's point) characters than escape().

How do I make a LinearLayout scrollable?

try this below code

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/constraintLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context="com.example.blah"
    >

    <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <LinearLayout
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:layout_height="wrap_content"
            android:layout_width="fill_parent"
            android:background="#000044"
            android:orientation="vertical">
            <TextView
                android:id="@+id/title"
                android:text="@string/title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <EditText
                android:id="@+id/editTitle"
                android:text=""
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/description"
                android:text="@string/description"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <EditText
                android:id="@+id/editDescription"
                android:text=""
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/location"
                android:text="@string/location"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <EditText
                android:id="@+id/editLocation"
                android:text=""
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/startTime"
                android:text="@string/startTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <DatePicker
                android:id="@+id/DatePicker01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TimePicker
                android:id="@+id/TimePicker01"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <TextView
                android:id="@+id/endTime"
                android:text="@string/endTime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#ffffff"/>
            <DatePicker
                android:id="@+id/DatePicker02"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />
            <TimePicker
                android:id="@+id/TimePicker02"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
            <Button
                android:id="@+id/buttonCreate"
                android:text="Create"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"/>
        </LinearLayout></ScrollView></RelativeLayout>

How do I call a non-static method from a static method in C#?

Assuming that both data1() and data2() are in the same class, then another alternative is to make data1() static.

private static void data1()
{
}
private static void data2()
{
   data1();
}

Using custom std::set comparator

1. Modern C++20 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s;

We use lambda function as comparator. As usual, comparator should return boolean value, indicating whether the element passed as first argument is considered to go before the second in the specific strict weak ordering it defines.

Online demo

2. Modern C++11 solution

auto cmp = [](int a, int b) { return ... };
std::set<int, decltype(cmp)> s(cmp);

Before C++20 we need to pass lambda as argument to set constructor

Online demo

3. Similar to first solution, but with function instead of lambda

Make comparator as usual boolean function

bool cmp(int a, int b) {
    return ...;
}

Then use it, either this way:

std::set<int, decltype(cmp)*> s(cmp);

Online demo

or this way:

std::set<int, decltype(&cmp)> s(&cmp);

Online demo

4. Old solution using struct with () operator

struct cmp {
    bool operator() (int a, int b) const {
        return ...
    }
};

// ...
// later
std::set<int, cmp> s;

Online demo

5. Alternative solution: create struct from boolean function

Take boolean function

bool cmp(int a, int b) {
    return ...;
}

And make struct from it using std::integral_constant

#include <type_traits>
using Cmp = std::integral_constant<decltype(&cmp), &cmp>;

Finally, use the struct as comparator

std::set<X, Cmp> set;

Online demo

pod has unbound PersistentVolumeClaims

You have to define a PersistentVolume providing disc space to be consumed by the PersistentVolumeClaim.

When using storageClass Kubernetes is going to enable "Dynamic Volume Provisioning" which is not working with the local file system.


To solve your issue:

  • Provide a PersistentVolume fulfilling the constraints of the claim (a size >= 100Mi)
  • Remove the storageClass-line from the PersistentVolumeClaim
  • Remove the StorageClass from your cluster

How do these pieces play together?

At creation of the deployment state-description it is usually known which kind (amount, speed, ...) of storage that application will need.
To make a deployment versatile you'd like to avoid a hard dependency on storage. Kubernetes' volume-abstraction allows you to provide and consume storage in a standardized way.

The PersistentVolumeClaim is used to provide a storage-constraint alongside the deployment of an application.

The PersistentVolume offers cluster-wide volume-instances ready to be consumed ("bound"). One PersistentVolume will be bound to one claim. But since multiple instances of that claim may be run on multiple nodes, that volume may be accessed by multiple nodes.

A PersistentVolume without StorageClass is considered to be static.

"Dynamic Volume Provisioning" alongside with a StorageClass allows the cluster to provision PersistentVolumes on demand. In order to make that work, the given storage provider must support provisioning - this allows the cluster to request the provisioning of a "new" PersistentVolume when an unsatisfied PersistentVolumeClaim pops up.


Example PersistentVolume

In order to find how to specify things you're best advised to take a look at the API for your Kubernetes version, so the following example is build from the API-Reference of K8S 1.17:

apiVersion: v1
kind: PersistentVolume
metadata:
  name: ckan-pv-home
  labels:
    type: local
spec:
  capacity:
    storage: 100Mi
  hostPath:
    path: "/mnt/data/ckan"

The PersistentVolumeSpec allows us to define multiple attributes. I chose a hostPath volume which maps a local directory as content for the volume. The capacity allows the resource scheduler to recognize this volume as applicable in terms of resource needs.


Additional Resources:

Is there an alternative to string.Replace that is case-insensitive?

Expanding on C. Dragon 76's popular answer by making his code into an extension that overloads the default Replace method.

public static class StringExtensions
{
    public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
    {
        StringBuilder sb = new StringBuilder();

        int previousIndex = 0;
        int index = str.IndexOf(oldValue, comparison);
        while (index != -1)
        {
            sb.Append(str.Substring(previousIndex, index - previousIndex));
            sb.Append(newValue);
            index += oldValue.Length;

            previousIndex = index;
            index = str.IndexOf(oldValue, index, comparison);
        }
        sb.Append(str.Substring(previousIndex));
        return sb.ToString();
     }
}

How to center an element horizontally and vertically

_x000D_
_x000D_
    .align {_x000D_
        display: flex;_x000D_
        width: 400px;_x000D_
        height: 400px;_x000D_
        border: solid 1px black;_x000D_
        align-items: center;_x000D_
        justify-content: space-around;_x000D_
    }_x000D_
    .align div:first-child {_x000D_
        width: 20px;_x000D_
        height: 20px;_x000D_
        background-color: red;_x000D_
        position: absolute; _x000D_
    }_x000D_
    .align div {_x000D_
        width: 20px;_x000D_
        height: 20px;_x000D_
        background-color: blue;_x000D_
    }
_x000D_
    <div class='align'>_x000D_
        <div></div>_x000D_
        <div></div>_x000D_
        <div></div>_x000D_
        <div></div>_x000D_
        <div></div>_x000D_
        <div></div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

First child will be aligned vertically and horizontally at center

Convert Pandas DataFrame to JSON format

convert data-frame to list of dictionary

list_dict = []

for index, row in list(df.iterrows()):
    list_dict.append(dict(row))

save file

with open("output.json", mode) as f:
    f.write("\n".join(str(item) for item in list_dict))

How are environment variables used in Jenkins with Windows Batch Command?

I should this On Windows, environment variable expansion is %BUILD_NUMBER%

Detect a finger swipe through JavaScript on the iPhone and Android

I wanted to detect left and right swipe only, but trigger the action only when the touch event ends, so I slightly modified the @givanse's great answer to do that.

Why to do that? If for example, while swiping, the user notices he finally doesn't want to swipe, he can move his finger at the original position (a very popular "dating" phone application does this ;)), and then the "swipe right" event is cancelled.

So in order to avoid a "swipe right" event just because there is a 3px difference horizontally, I added a threshold under which an event is discarded: in order to have a "swipe right" event, the user has to swipe of at least 1/3 of the browser width (of course you can modify this).

All these small details enhance the user experience.

Note that currently, a "touch pinch zoom" might be detected as a swipe if one of the two fingers does a big horizontal move during the pinch zoom.

Here is the (Vanilla JS) code:

var xDown = null, yDown = null, xUp = null, yUp = null;
document.addEventListener('touchstart', touchstart, false);        
document.addEventListener('touchmove', touchmove, false);
document.addEventListener('touchend', touchend, false);
function touchstart(evt) { const firstTouch = (evt.touches || evt.originalEvent.touches)[0]; xDown = firstTouch.clientX; yDown = firstTouch.clientY; }
function touchmove(evt) { if (!xDown || !yDown ) return; xUp = evt.touches[0].clientX; yUp = evt.touches[0].clientY; }
function touchend(evt) { 
    var xDiff = xUp - xDown, yDiff = yUp - yDown;
    if ((Math.abs(xDiff) > Math.abs(yDiff)) && (Math.abs(xDiff) > 0.33 * document.body.clientWidth)) { 
        if (xDiff < 0) 
            document.getElementById('leftnav').click();
        else
            document.getElementById('rightnav').click();
    } 
    xDown = null, yDown = null;
}

Is it possible to assign numeric value to an enum in Java?

Extending Bhesh Gurung's answer for assigning values, you can add explicit method to set value

   public ExitCode setValue( int value){
      //  A(104), B(203);
      switch(value){
        case 104: return ExitCode.A;
        case 203: return ExitCode.B;
        default:
                   return ExitCode.Unknown //Keep an default or error enum handy
      }
   }

From calling application

int i = 104; 
ExitCode serverExitCode = ExitCode.setValue(i);

//You've valid enum from now

[Unable to comment to his answer, hence posting it separately]

Setting the filter to an OpenFileDialog to allow the typical image formats?

Follow this pattern if you browsing for image files:

dialog.Filter =  "Image files (*.jpg, *.jpeg, *.jpe, *.jfif, *.png) | *.jpg; *.jpeg; *.jpe; *.jfif; *.png";

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

select * from sqlite_master where type = 'table' and tbl_name = 'TableName' and sql like '%ColumnName%'

Logic: sql column in sqlite_master contains table definition, so it certainly contains string with column name.

As you are searching for a sub-string, it has its obvious limitations. So I would suggest to use even more restrictive sub-string in ColumnName, for example something like this (subject to testing as '`' character is not always there):

select * from sqlite_master where type = 'table' and tbl_name = 'MyTable' and sql like '%`MyColumn` TEXT%'

How to subtract date/time in JavaScript?

Unless you are subtracting dates on same browser client and don't care about edge cases like day light saving time changes, you are probably better off using moment.js which offers powerful localized APIs. For example, this is what I have in my utils.js:

subtractDates: function(date1, date2) {
    return moment.subtract(date1, date2).milliseconds();
},
millisecondsSince: function(dateSince) {
    return moment().subtract(dateSince).milliseconds();
},

Where is Maven's settings.xml located on Mac OS?

->It is located in $MAVEN_HOME/conf/settings.xml... where $MAVEN_HOME is your environmental variable of Maven that you have downloaded. Else you can do like this also.. ->Path to Maven can also be found from /etc/bashrc file in mac. Get Path to Maven from that file and in that Maven directory you can find conf/ directory inside that directory you can find settings.xml of maven

How can I use Ruby to colorize the text output to a terminal?

You can use ANSI escape sequences to do this on the console. I know this works on Linux and OSX, I'm not sure if the Windows console (cmd) supports ANSI.

I did it in Java, but the ideas are the same.

//foreground color
public static final String BLACK_TEXT()   { return "\033[30m";}
public static final String RED_TEXT()     { return "\033[31m";}
public static final String GREEN_TEXT()   { return "\033[32m";}
public static final String BROWN_TEXT()   { return "\033[33m";}
public static final String BLUE_TEXT()    { return "\033[34m";}
public static final String MAGENTA_TEXT() { return "\033[35m";}
public static final String CYAN_TEXT()    { return "\033[36m";}
public static final String GRAY_TEXT()    { return "\033[37m";}

//background color
public static final String BLACK_BACK()   { return "\033[40m";}
public static final String RED_BACK()     { return "\033[41m";}
public static final String GREEN_BACK()   { return "\033[42m";}
public static final String BROWN_BACK()   { return "\033[43m";}
public static final String BLUE_BACK()    { return "\033[44m";}
public static final String MAGENTA_BACK() { return "\033[45m";}
public static final String CYAN_BACK()    { return "\033[46m";}
public static final String WHITE_BACK()   { return "\033[47m";}

//ANSI control chars
public static final String RESET_COLORS() { return "\033[0m";}
public static final String BOLD_ON()      { return "\033[1m";}
public static final String BLINK_ON()     { return "\033[5m";}
public static final String REVERSE_ON()   { return "\033[7m";}
public static final String BOLD_OFF()     { return "\033[22m";}
public static final String BLINK_OFF()    { return "\033[25m";}
public static final String REVERSE_OFF()  { return "\033[27m";}

Add legend to ggplot2 line plot

I tend to find that if I'm specifying individual colours in multiple geom's, I'm doing it wrong. Here's how I would plot your data:

##Subset the necessary columns
dd_sub = datos[,c(20, 2,3,5)]
##Then rearrange your data frame
library(reshape2)
dd = melt(dd_sub, id=c("fecha"))

All that's left is a simple ggplot command:

ggplot(dd) + geom_line(aes(x=fecha, y=value, colour=variable)) +
  scale_colour_manual(values=c("red","green","blue"))

Example plot

enter image description here

VMware Workstation and Device/Credential Guard are not compatible

install the latest vmware workstation > 15.5.5 version

which has support of Hyper-V Host

With the release of VMware Workstation/Player 15.5. 5 or >, we are very excited and proud to announce support for Windows hosts with Hyper-V mode enabled! As you may know, this is a joint project from both Microsoft and VMware

https://blogs.vmware.com/workstation/2020/05/vmware-workstation-now-supports-hyper-v-mode.html

i installed the VMware.Workstation.Pro.16.1.0

and now it fixed my issue now i am using docker & vmware same time even my window Hyper-V mode is enabled

What's the purpose of the LEA instruction?

Despite all the explanations, LEA is an arithmetic operation:

LEA Rt, [Rs1+a*Rs2+b] =>  Rt = Rs1 + a*Rs2 + b

It's just that its name is extremelly stupid for a shift+add operation. The reason for that was already explained in the top rated answers (i.e. it was designed to directly map high level memory references).

Linq select object from list depending on objects attribute

Your expression is never going to evaluate.

You are comparing a with a property of a.

a is of type Answer. a.Correct, I'm guessing is a boolean.

Long form:-

Answer = answer.SingleOrDefault(a => a.Correct == true);

Short form:-

Answer = answer.SingleOrDefault(a => a.Correct);

Search and replace a line in a file in Python

if you remove the indent at the like below, it will search and replace in multiple line. See below for example.

def replace(file, pattern, subst):
    #Create temp file
    fh, abs_path = mkstemp()
    print fh, abs_path
    new_file = open(abs_path,'w')
    old_file = open(file)
    for line in old_file:
        new_file.write(line.replace(pattern, subst))
    #close temp file
    new_file.close()
    close(fh)
    old_file.close()
    #Remove original file
    remove(file)
    #Move new file
    move(abs_path, file)

Mocking HttpClient in unit tests

Your interface exposes the concrete HttpClient class, therefore any classes that use this interface are tied to it, this means that it cannot be mocked.

HttpClient does not inherit from any interface so you will have to write your own. I suggest a decorator-like pattern:

public interface IHttpHandler
{
    HttpResponseMessage Get(string url);
    HttpResponseMessage Post(string url, HttpContent content);
    Task<HttpResponseMessage> GetAsync(string url);
    Task<HttpResponseMessage> PostAsync(string url, HttpContent content);
}

And your class will look like this:

public class HttpClientHandler : IHttpHandler
{
    private HttpClient _client = new HttpClient();

    public HttpResponseMessage Get(string url)
    {
        return GetAsync(url).Result;
    }

    public HttpResponseMessage Post(string url, HttpContent content)
    {
        return PostAsync(url, content).Result;
    }

    public async Task<HttpResponseMessage> GetAsync(string url)
    {
        return await _client.GetAsync(url);
    }

    public async Task<HttpResponseMessage> PostAsync(string url, HttpContent content)
    {
        return await _client.PostAsync(url, content);
    }
}

The point in all of this is that HttpClientHandler creates its own HttpClient, you could then of course create multiple classes that implement IHttpHandler in different ways.

The main issue with this approach is that you are effectively writing a class that just calls methods in another class, however you could create a class that inherits from HttpClient (See Nkosi's example, it's a much better approach than mine). Life would be much easier if HttpClient had an interface that you could mock, unfortunately it does not.

This example is not the golden ticket however. IHttpHandler still relies on HttpResponseMessage, which belongs to System.Net.Http namespace, therefore if you do need other implementations other than HttpClient, you will have to perform some kind of mapping to convert their responses into HttpResponseMessage objects. This of course is only a problem if you need to use multiple implementations of IHttpHandler but it doesn't look like you do so it's not the end of the world, but it's something to think about.

Anyway, you can simply mock IHttpHandler without having to worry about the concrete HttpClient class as it has been abstracted away.

I recommend testing the non-async methods, as these still call the asynchronous methods but without the hassle of having to worry about unit testing asynchronous methods, see here

Get last dirname/filename in a file path argument in Bash

Bash can get the last part of a path without having to call the external basename:

subdir="/path/to/whatever/${1##*/}"

How to get a ListBox ItemTemplate to stretch horizontally the full width of the ListBox?

I found another solution here, since I ran into both post...

This is from the Myles answer:

<ListBox.ItemContainerStyle> 
    <Style TargetType="ListBoxItem"> 
        <Setter Property="HorizontalContentAlignment" Value="Stretch"></Setter> 
    </Style> 
</ListBox.ItemContainerStyle> 

This worked for me.

Check existence of directory and create if doesn't exist

To find out if a path is a valid directory try:

file.info(cacheDir)[1,"isdir"]

file.info does not care about a slash on the end.

file.exists on Windows will fail for a directory if it ends in a slash, and succeeds without it. So this cannot be used to determine if a path is a directory.

file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache/")
[1] FALSE

file.exists("R:/data/CCAM/CCAMC160b_echam5_A2-ct-uf.-5t05N.190to240E_level1000/cache")
[1] TRUE

file.info(cacheDir)["isdir"]

How to iterate over a string in C?

Replace sizeof with strlen and it should work.

How to create enum like type in TypeScript?

TypeScript 0.9+ has a specification for enums:

enum AnimationType {
    BOUNCE,
    DROP,
}

The final comma is optional.

What does it mean by select 1 from table?

To be slightly more specific, you would use this to do

SELECT 1 FROM MyUserTable WHERE user_id = 33487

instead of doing

SELECT * FROM MyUserTable WHERE user_id = 33487

because you don't care about looking at the results. Asking for the number 1 is very easy for the database (since it doesn't have to do any look-ups).

Get difference between two lists

If you are really looking into performance, then use numpy!

Here is the full notebook as a gist on github with comparison between list, numpy, and pandas.

https://gist.github.com/denfromufa/2821ff59b02e9482be15d27f2bbd4451

enter image description here

How to concatenate strings with padding in sqlite

Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...

SELECT 
  (
    col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
  ) AS my_column 
FROM
  mytable;

Tested on SQLite 3.8.8.3, Thanks!

How do I REALLY reset the Visual Studio window layout?

How about running the following from command line,

Devenv.exe /ResetSettings

You could also save those settings in to a file, like so,

Devenv.exe /ResetSettings "C:\My Files\MySettings.vssettings"

The /ResetSettings switch, Restores Visual Studio default settings. Optionally resets the settings to the specified .vssettings file.

MSDN link

Can we make unsigned byte in Java

There is no unsigned byte in Java, but if you want to display a byte, you can do,

int myInt = 144;

byte myByte = (byte) myInt;

char myChar = (char) (myByte & 0xFF);

System.out.println("myChar :" + Integer.toHexString(myChar));

Output:

myChar : 90

For more information, please check, How to display a hex/byte value in Java.

A url resource that is a dot (%2E)

It is not possible. §2.3 says that "." is an unreserved character and that "URIs that differ in the replacement of an unreserved character with its corresponding percent-encoded US-ASCII octet are equivalent". Therefore, /%2E%2E/ is the same as /../, and that will get normalized away.

(This is a combination of an answer by bobince and a comment by slowpoison.)

Insert line break in wrapped cell via code

Yes there are two way to add a line feed:

  1. Use the existing function from VBA vbCrLf in the string you want to add a line feed, as such:

    Dim text As String

    text = "Hello" & vbCrLf & "World!"

    Worksheets(1).Cells(1, 1) = text

  2. Use the Chr() function and pass the ASCII characters 13 and 10 in order to add a line feed, as shown bellow:

    Dim text As String

    text = "Hello" & Chr(13) & Chr(10) & "World!"

    Worksheets(1).Cells(1, 1) = text

In both cases, you will have the same output in cell (1,1) or A1.