Programs & Examples On #Ibm jdk

How do I prevent Eclipse from hanging on startup?

You can try to start Eclipse first with the -clean option.

On Windows you can add the -clean option to your shortcut for eclipse. On Linux you can simply add it when starting Eclipse from the command line.

Regular expression to match URLs in Java

When using regular expressions from RegexBuddy's library, make sure to use the same matching modes in your own code as the regex from the library. If you generate a source code snippet on the Use tab, RegexBuddy will automatically set the correct matching options in the source code snippet. If you copy/paste the regex, you have to do that yourself.

In this case, as others pointed out, you missed the case insensitivity option.

java.lang.NoClassDefFoundError: org/apache/juli/logging/LogFactory

I copied the contents of the "C:\Program Files\Apache Software Foundation\Tomcat 6.0\conf" directory to the "workspace\Servers\Tomcat v6.0 Server at localhost-config" directory for Eclipse. I refreshed the "Servers\Tomcat v6.0 Server at localhost-config" folder in the Eclipse Project Explorer and then everything was good.

Using a .php file to generate a MySQL dump

You can use the exec() function to execute an external command.

Note: between shell_exec() and exec(), I would choose the second one, which doesn't return the output to the PHP script -- no need for the PHP script to get the whole SQL dump as a string : you only need it written to a file, and this can be done by the command itself.


That external command will :

  • be a call to mysqldump, with the right parameters,
  • and redirect the output to a file.

For example :

mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql


Which means your PHP code would look like this :

exec('mysqldump --user=... --password=... --host=... DB_NAME > /path/to/output/file.sql');


Of course, up to you to use the right connection information, replacing the ... with those.

Get most recent row for given ID

Building on @xQbert's answer's, you can avoid the subquery AND make it generic enough to filter by any ID

SELECT id, signin, signout
FROM dTable
INNER JOIN(
  SELECT id, MAX(signin) AS signin
  FROM dTable
  GROUP BY id
) AS t1 USING(id, signin)

Reading entire html file to String?

There's the IOUtils.toString(..) utility from Apache Commons.

If you're using Guava there's also Files.readLines(..) and Files.toString(..).

How to unstage large number of files without deleting the content

If you want to unstage all the changes use below command,

git reset --soft HEAD

In the case you want to unstage changes and revert them from the working directory,

git reset --hard HEAD

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

How to include libraries in Visual Studio 2012?

In code level also, you could add your lib to the project using the compiler directives #pragma.

example:

#pragma comment( lib, "yourLibrary.lib" )

Can the "IN" operator use LIKE-wildcards (%) in Oracle?

Select * from myTable m
where m.status not like 'Done%' 
and m.status not like 'Finished except%'
and m.status not like 'In Progress%'

aspx page to redirect to a new page

Even if you don't control the server, you can still see the error messages by adding the following line to the Web.config file in your project (bewlow <system.web>):

<customErrors mode="off" />

Quickest way to compare two generic lists for differences

Not for this Problem, but here's some code to compare lists for equal and not! identical objects:

public class EquatableList<T> : List<T>, IEquatable<EquatableList<T>> where    T : IEquatable<T>

/// <summary>
/// True, if this contains element with equal property-values
/// </summary>
/// <param name="element">element of Type T</param>
/// <returns>True, if this contains element</returns>
public new Boolean Contains(T element)
{
    return this.Any(t => t.Equals(element));
}

/// <summary>
/// True, if list is equal to this
/// </summary>
/// <param name="list">list</param>
/// <returns>True, if instance equals list</returns>
public Boolean Equals(EquatableList<T> list)
{
    if (list == null) return false;
    return this.All(list.Contains) && list.All(this.Contains);
}

How to read barcodes with the camera on Android?

Here is a sample code: my app uses ZXing Barcode Scanner.

  1. You need these 2 classes: IntentIntegrator and IntentResult

  2. Call scanner (e.g. OnClickListener, OnMenuItemSelected...), "PRODUCT_MODE" - it scans standard 1D barcodes (you can add more).:

    IntentIntegrator.initiateScan(this, 
               "Warning", 
               "ZXing Barcode Scanner is not installed, download?",
               "Yes", "No",
               "PRODUCT_MODE");
    
  3. Get barcode as a result:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {  
      switch (requestCode) {
      case IntentIntegrator.REQUEST_CODE:
         if (resultCode == Activity.RESULT_OK) {
    
            IntentResult intentResult = 
               IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    
            if (intentResult != null) {
    
               String contents = intentResult.getContents();
               String format = intentResult.getFormatName();
    
               this.elemQuery.setText(contents);
               this.resume = false;
               Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
            } else {
               Log.e("SEARCH_EAN", "IntentResult je NULL!");
            }
         } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.e("SEARCH_EAN", "CANCEL");
         }
      }
    }
    

contents holds barcode number

how to convert .java file to a .class file

To get a .class file you have to compile the .java file.

The command for this is javac. The manual for this is found here (Windows)

In short:

javac File.java

Spring JPA @Query with LIKE

@Query("select b.equipSealRegisterId from EquipSealRegister b where b.sealName like %?1% and b.deleteFlag = '0'" )
    List<String>findBySeal(String sealname);

I have tried this code and it works.

What's the difference between an Angular component and module

A module in Angular 2 is something which is made from components, directives, services etc. One or many modules combine to make an Application. Modules breakup application into logical pieces of code. Each module performs a single task.

Components in Angular 2 are classes where you write your logic for the page you want to display. Components control the view (html). Components communicate with other components and services.

What is the difference between private and protected members of C++ classes?

Protected members can be accessed from derived classes. Private ones can't.

class Base {

private: 
  int MyPrivateInt;
protected: 
  int MyProtectedInt;
public:
  int MyPublicInt;
};

class Derived : Base
{
public:
  int foo1()  { return MyPrivateInt;} // Won't compile!
  int foo2()  { return MyProtectedInt;} // OK  
  int foo3()  { return MyPublicInt;} // OK
};??

class Unrelated 
{
private:
  Base B;
public:
  int foo1()  { return B.MyPrivateInt;} // Won't compile!
  int foo2()  { return B.MyProtectedInt;} // Won't compile
  int foo3()  { return B.MyPublicInt;} // OK
};

In terms of "best practice", it depends. If there's even a faint possibility that someone might want to derive a new class from your existing one and need access to internal members, make them Protected, not Private. If they're private, your class may become difficult to inherit from easily.

How to select a single column with Entity Framework?

Using LINQ your query should look something like this:

public User GetUser(int userID){

return
(
 from p in "MyTable" //(Your Entity Model)
 where p.UserID == userID
 select p.Name
).SingleOrDefault();

}

Of course to do this you need to have an ADO.Net Entity Model in your solution.

How to include scripts located inside the node_modules folder?

I didn't find any clean solutions (I don't want to expose the source of all my node_modules) so I just wrote a Powershell script to copy them:

$deps = "leaflet", "leaflet-search", "material-components-web"

foreach ($dep in $deps) {
    Copy-Item "node_modules/$dep/dist" "static/$dep" -Recurse
}

Maximum call stack size exceeded on npm install

I was facing the same error, I was trying to install jest into to one of the packages in a monorepo project.

If you are using Yarn + Learna to package a monorepo project, you will have to navigate to the package.json inside the target package and then run npm install or npm install <package name>.

How can I add a table of contents to a Jupyter / JupyterLab notebook?

There is an ipython nbextension that constructs a table of contents for a notebook. It seems to only provide navigation, not section folding.

Where is the documentation for the values() method of Enum?

Run this

    for (Method m : sex.class.getDeclaredMethods()) {
        System.out.println(m);
    }

you will see

public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()

These are all public methods that "sex" class has. They are not in the source code, javac.exe added them

Notes:

  1. never use sex as a class name, it's difficult to read your code, we use Sex in Java

  2. when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class

Escape double quote in grep

The problem is that you aren't correctly escaping the input string, try:

echo "\"member\":\"time\"" | grep -e "member\""

Alternatively, you can use unescaped double quotes within single quotes:

echo '"member":"time"' | grep -e 'member"'

It's a matter of preference which you find clearer, although the second approach prevents you from nesting your command within another set of single quotes (e.g. ssh 'cmd').

Android Studio doesn't recognize my device

Although my computer could recognise my phone, I had to install the official drivers from the Samsung developer site to get adb/Android Studio to recognise it:

Samsung Android USB Driver for Windows

How to convert int[] into List<Integer> in Java?

Here is a solution:

int[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };

Integer[] iArray = Arrays.stream(array).boxed().toArray(Integer[]::new);
System.out.println(Arrays.toString(iArray));

List<Integer> list = new ArrayList<>();
Collections.addAll(list, iArray);
System.out.println(list);

Output:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Regex replace (in Python) - a simpler way?

The short version is that you cannot use variable-width patterns in lookbehinds using Python's re module. There is no way to change this:

>>> import re
>>> re.sub("(?<=foo)bar(?=baz)", "quux", "foobarbaz")
'fooquuxbaz'
>>> re.sub("(?<=fo+)bar(?=baz)", "quux", "foobarbaz")

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    re.sub("(?<=fo+)bar(?=baz)", "quux", string)
  File "C:\Development\Python25\lib\re.py", line 150, in sub
    return _compile(pattern, 0).sub(repl, string, count)
  File "C:\Development\Python25\lib\re.py", line 241, in _compile
    raise error, v # invalid expression
error: look-behind requires fixed-width pattern

This means that you'll need to work around it, the simplest solution being very similar to what you're doing now:

>>> re.sub("(fo+)bar(?=baz)", "\\1quux", "foobarbaz")
'fooquuxbaz'
>>>
>>> # If you need to turn this into a callable function:
>>> def replace(start, replace, end, replacement, search):
        return re.sub("(" + re.escape(start) + ")" + re.escape(replace) + "(?=" + re.escape + ")", "\\1" + re.escape(replacement), search)

This doesn't have the elegance of the lookbehind solution, but it's still a very clear, straightforward one-liner. And if you look at what an expert has to say on the matter (he's talking about JavaScript, which lacks lookbehinds entirely, but many of the principles are the same), you'll see that his simplest solution looks a lot like this one.

php $_GET and undefined index

Simple function, works with GET or POST. Plus you can assign a default value.

function GetPost($var,$default='') {
    return isset($_GET[$var]) ? $_GET[$var] : (isset($_POST[$var]) ? $_POST[$var] : $default);
}

Visual studio equivalent of java System.out

You can use Console.WriteLine() to write out any native type. To see the output you must write console application (like in Java), then the output will be displayed in the Command Prompt, or if you are developing a windows GUI application, in Visual Studio you must turn on "Output" panel (under View) to see the commands output.

Bitbucket git credentials if signed up with Google

you don't have a bitbucket password because you log with google, but you can "reset" the password here https://bitbucket.org/account/password/reset/

you will receive an email to setup a new password and that's it.

How to add minutes to current time in swift

Save this little extension:

extension Int {

 var seconds: Int {
    return self
 }

 var minutes: Int {
    return self.seconds * 60
 }

 var hours: Int {
    return self.minutes * 60
 }

 var days: Int {
    return self.hours * 24
 }

 var weeks: Int {
    return self.days * 7
 }

 var months: Int {
    return self.weeks * 4
 }

 var years: Int {
    return self.months * 12
 }
}

Then use it intuitively like:

let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)

Get HTML source of WebElement in Selenium WebDriver using Python

Sure we can get all HTML source code with this script below in Selenium Python:

elem = driver.find_element_by_xpath("//*")
source_code = elem.get_attribute("outerHTML")

If you you want to save it to file:

with open('c:/html_source_code.html', 'w') as f:
    f.write(source_code.encode('utf-8'))

I suggest saving to a file because source code is very very long.

True and False for && logic and || Logic table

I`d like to add to the already good answers:

The symbols '+', '*' and '-' are sometimes used as shorthand in some older textbooks for OR,? and AND,? and NOT,¬ logical operators in Bool`s algebra. In C/C++ of course we use "and","&&" and "or","||" and "not","!".

Watch out: "true + true" evaluates to 2 in C/C++ via internal representation of true and false as 1 and 0, and the implicit cast to int!

int main ()
{
  std::cout <<  "true - true = " << true - true << std::endl;
// This can be used as signum function:
// "(x > 0) - (x < 0)" evaluates to +1 or -1 for numbers.
  std::cout <<  "true - false = " << true - false << std::endl;
  std::cout <<  "false - true = " << false - true << std::endl;
  std::cout <<  "false - false = " << false - false << std::endl << std::endl;

  std::cout <<  "true + true = " << true + true << std::endl;
  std::cout <<  "true + false = " << true + false << std::endl;
  std::cout <<  "false + true = " << false + true << std::endl;
  std::cout <<  "false + false = " << false + false << std::endl << std::endl;

  std::cout <<  "true * true = " << true * true << std::endl;
  std::cout <<  "true * false = " << true * false << std::endl;
  std::cout <<  "false * true = " << false * true << std::endl;
  std::cout <<  "false * false = " << false * false << std::endl << std::endl;

  std::cout <<  "true / true = " << true / true << std::endl;
  //  std::cout <<  true / false << std::endl; ///-Wdiv-by-zero
  std::cout <<  "false / true = " << false / true << std::endl << std::endl;
  //  std::cout <<  false / false << std::endl << std::endl; ///-Wdiv-by-zero

  std::cout <<  "(true || true) = " << (true || true) << std::endl;
  std::cout <<  "(true || false) = " << (true || false) << std::endl;
  std::cout <<  "(false || true) = " << (false || true) << std::endl;
  std::cout <<  "(false || false) = " << (false || false) << std::endl << std::endl;

  std::cout <<  "(true && true) = " << (true && true) << std::endl;
  std::cout <<  "(true && false) = " << (true && false) << std::endl;
  std::cout <<  "(false && true) = " << (false && true) << std::endl;
  std::cout <<  "(false && false) = " << (false && false) << std::endl << std::endl;

}

yields :

true - true = 0
true - false = 1
false - true = -1
false - false = 0

true + true = 2
true + false = 1
false + true = 1
false + false = 0

true * true = 1
true * false = 0
false * true = 0
false * false = 0

true / true = 1
false / true = 0

(true || true) = 1
(true || false) = 1
(false || true) = 1
(false || false) = 0

(true && true) = 1
(true && false) = 0
(false && true) = 0
(false && false) = 0

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

in JDK 8, jdbc odbc bridge is no longer used and thus removed fro the JDK. to use Microsoft Access database in JAVA, you need 5 extra JAR libraries.

1- hsqldb.jar

2- jackcess 2.0.4.jar

3- commons-lang-2.6.jar

4- commons-logging-1.1.1.jar

5- ucanaccess-2.0.8.jar

add these libraries to your java project and start with following lines.

Connection conn=DriverManager.getConnection("jdbc:ucanaccess://<Path to your database i.e. MS Access DB>");
Statement s = conn.createStatement();

path could be like E:/Project/JAVA/DBApp

and then your query to be executed. Like

ResultSet rs = s.executeQuery("SELECT * FROM Course");
while(rs.next())
    System.out.println(rs.getString("Title") + " " + rs.getString("Code") + " " + rs.getString("Credits"));

certain imports to be used. try catch block must be used and some necessary things no to be forgotten.

Remember, no need of bridging drivers like jdbc odbc or any stuff.

What does $(function() {} ); do?

The following is a jQuery function call:

$(...);

Which is the "jQuery function." $ is a function, and $(...) is you calling that function.

The first parameter you've supplied is the following:

function() {}

The parameter is a function that you specified, and the $ function will call the supplied method when the DOM finishes loading.

Parsing string as JSON with single quotes?

If you are sure your JSON is safely under your control (not user input) then you can simply evaluate the JSON. Eval accepts all quote types as well as unquoted property names.

var str = "{'a':1}";
var myObject = (0, eval)('(' + str + ')');

The extra parentheses are required due to how the eval parser works. Eval is not evil when it is used on data you have control over. For more on the difference between JSON.parse and eval() see JSON.parse vs. eval()

How to close form

new WindowSettings();

You just closed a brand new instance of the form that wasn't visible in the first place.

You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.

Could not connect to Redis at 127.0.0.1:6379: Connection refused with homebrew

After installing redis, type from terminal:

redis-server

And Redis-Server will be started

How to implement "select all" check box in HTML?

This is what this will do, for instance if you have 5 checkboxes, and you click check all,it check all, now if you uncheck all the checkbox probably by clicking each 5 checkboxs, by the time you uncheck the last checkbox, the select all checkbox also gets unchecked

$("#select-all").change(function(){
   $(".allcheckbox").prop("checked", $(this).prop("checked"))
  })
  $(".allcheckbox").change(function(){
      if($(this).prop("checked") == false){
          $("#select-all").prop("checked", false)
      }
      if($(".allcheckbox:checked").length == $(".allcheckbox").length){
          $("#select-all").prop("checked", true)
      }
  })

How to print the contents of RDD?

If you want to view the content of a RDD, one way is to use collect():

myRDD.collect().foreach(println)

That's not a good idea, though, when the RDD has billions of lines. Use take() to take just a few to print out:

myRDD.take(n).foreach(println)

Is there a limit on number of tcp/ip connections between machines on linux?

There is a limit, yes. See ulimit.

Also you need to consider the TIMED_WAIT state. Once a TCP socket is closed (by default) the port remains occupied in TIMED_WAIT status for 2 minutes. This value is tunable. This will also "run you out of sockets" even though they are closed.

Run netstat to see the TIMED_WAIT stuff in action.

P.S. The reason for TIMED_WAIT is to handle the case of packets arriving after the socket is closed. This can happen because packets are delayed or the other side just doesn't know that the socket has been closed yet. This allows the OS to silently drop those packets without a chance of "infecting" a different, unrelated socket connection.

SQL Server: Invalid Column Name

I noted that, when executing joins, MSSQL will throw "Invalid Column Name" if the table you are joining on is not next to the table you are joining to. I tried specifying table1.row1 and table3.row3, but was still getting the error; it did not go away until I reordered the tables in the query. Apparently, the order of the tables in the statement matters.

+-------------+    +-------------+    +-------------+    
| table1      |    | table2      |    | table3      |    
+-------------+    +-------------+    +-------------+    
| row1 | col1 |    | row2 | col2 |    | row3 | col3 |    
+------+------+    +------+------+    +------+------+    
| ...  | ...  |    | ...  | ...  |    | ...  | ...  |    
+------+------+    +------+------+    +------+------+    

SELECT * FROM table1, table2 LEFT JOIN table3 ON row1 = row3; --throws an error
SELECT * FROM table2, table1 LEFT JOIN table3 ON row1 = row3; --works as expected

javascript create array from for loop

even shorter if you can lose the yearStart value:

var yearStart = 2000;
var yearEnd = 2040;

var arr = [];

while(yearStart < yearEnd+1){
  arr.push(yearStart++);
}

UPDATE: If you can use the ES6 syntax you can do it the way proposed here:

let yearStart = 2000;
let yearEnd = 2040;
let years = Array(yearEnd-yearStart+1)
    .fill()
    .map(() => yearStart++);

What is correct media query for IPad Pro?

This worked for me

/* Portrait */
@media only screen 
  and (min-device-width: 834px) 
  and (max-device-width: 834px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 2) {

}

/* Landscape */
@media only screen 
  and (min-width: 1112px) 
  and (max-width: 1112px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 2)
 {

}

Remove NaN from pandas series

A small usage of np.nan ! = np.nan

s[s==s]
Out[953]: 
0    1.0
1    2.0
2    3.0
3    4.0
5    5.0
dtype: float64

More Info

np.nan == np.nan
Out[954]: False

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

user: root

password: [blank]

XAMPP v3.2.2

jquery: change the URL address without redirecting?

This is achieved through URL rewriting, not through URL obfuscating, which can't be done.

Another way to do this, as has been mentioned is by changing the hashtag, with

window.location.hash = "/2131/"

How to fix the datetime2 out-of-range conversion error using DbContext and SetInitializer?

In some cases, DateTime.MinValue (or equivalenly, default(DateTime)) is used to indicate an unknown value.

This simple extension method can help handle such situations:

public static class DbDateHelper
{
    /// <summary>
    /// Replaces any date before 01.01.1753 with a Nullable of 
    /// DateTime with a value of null.
    /// </summary>
    /// <param name="date">Date to check</param>
    /// <returns>Input date if valid in the DB, or Null if date is 
    /// too early to be DB compatible.</returns>
    public static DateTime? ToNullIfTooEarlyForDb(this DateTime date)
    {
        return (date >= (DateTime) SqlDateTime.MinValue) ? date : (DateTime?)null;
    }
}

Usage:

 DateTime? dateToPassOnToDb = tooEarlyDate.ToNullIfTooEarlyForDb();

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Your example shows the most simple way of passing PHP variables to JavaScript. You can also use json_encode for more complex things like arrays:

<?php
    $simple = 'simple string';
    $complex = array('more', 'complex', 'object', array('foo', 'bar'));
?>
<script type="text/javascript">
    var simple = '<?php echo $simple; ?>';
    var complex = <?php echo json_encode($complex); ?>;
</script>

Other than that, if you really want to "interact" between PHP and JavaScript you should use Ajax.

Using cookies for this is a very unsafe and unreliable way, as they are stored clientside and therefore open for any manipulation or won't even get accepted/saved. Don't use them for this type of interaction. jQuery.ajax is a good start IMHO.

How to get current available GPUs in tensorflow?

Apart from the excellent explanation by Mrry, where he suggested to use device_lib.list_local_devices() I can show you how you can check for GPU related information from the command line.

Because currently only Nvidia's gpus work for NN frameworks, the answer covers only them. Nvidia has a page where they document how you can use the /proc filesystem interface to obtain run-time information about the driver, any installed NVIDIA graphics cards, and the AGP status.

/proc/driver/nvidia/gpus/0..N/information

Provide information about each of the installed NVIDIA graphics adapters (model name, IRQ, BIOS version, Bus Type). Note that the BIOS version is only available while X is running.

So you can run this from command line cat /proc/driver/nvidia/gpus/0/information and see information about your first GPU. It is easy to run this from python and also you can check second, third, fourth GPU till it will fail.

Definitely Mrry's answer is more robust and I am not sure whether my answer will work on non-linux machine, but that Nvidia's page provide other interesting information, which not many people know about.

c++ Read from .csv file

You can follow this answer to see many different ways to process CSV in C++.

In your case, the last call to getline is actually putting the last field of the first line and then all of the remaining lines into the variable genero. This is because there is no space delimiter found up until the end of file. Try changing the space character into a newline instead:

    getline(file, genero, file.widen('\n'));

or more succinctly:

    getline(file, genero);

In addition, your check for file.good() is premature. The last newline in the file is still in the input stream until it gets discarded by the next getline() call for ID. It is at this point that the end of file is detected, so the check should be based on that. You can fix this by changing your while test to be based on the getline() call for ID itself (assuming each line is well formed).

while (getline(file, ID, ',')) {
    cout << "ID: " << ID << " " ; 

    getline(file, nome, ',') ;
    cout << "User: " << nome << " " ;

    getline(file, idade, ',') ;
    cout << "Idade: " << idade << " "  ; 

    getline(file, genero);
    cout << "Sexo: " <<  genero<< " "  ;
}

For better error checking, you should check the result of each call to getline().

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

Your JSON string is malformed: the type of center is an array of invalid objects. Replace [ and ] with { and } in the JSON string around longitude and latitude so they will be objects:

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : {
                "latitude" : 38.895111, 
                "longitude" : -77.036667
            }
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : {
                "latitude" : 37.783333, 
                "longitude" : -122.416667
            }
    }
]

How to make function decorators and chain them together?

Another way of doing the same thing:

class bol(object):
  def __init__(self, f):
    self.f = f
  def __call__(self):
    return "<b>{}</b>".format(self.f())

class ita(object):
  def __init__(self, f):
    self.f = f
  def __call__(self):
    return "<i>{}</i>".format(self.f())

@bol
@ita
def sayhi():
  return 'hi'

Or, more flexibly:

class sty(object):
  def __init__(self, tag):
    self.tag = tag
  def __call__(self, f):
    def newf():
      return "<{tag}>{res}</{tag}>".format(res=f(), tag=self.tag)
    return newf

@sty('b')
@sty('i')
def sayhi():
  return 'hi'

How to set a cookie for another domain

You cannot set cookies for another domain. Allowing this would present an enormous security flaw.

You need to get b.com to set the cookie. If a.com redirect the user to b.com/setcookie.php?c=value

The setcookie script could contain the following to set the cookie and redirect to the correct page on b.com

<?php
    setcookie('a', $_GET['c']);
    header("Location: b.com/landingpage.php");
?>

Getting the textarea value of a ckeditor textarea with javascript

i found following code working for ckeditor 5

ClassicEditor
    .create( document.querySelector( '#editor' ) )
    .then( editor => {
        editor.model.document.on( 'change:data', () => {
            editorData = editor.getData();
        } );
    } )
    .catch( error => {
        console.error( error );
    } );

How to properly set the 100% DIV height to match document/window height?

I figured it out myself with the help of someone's answer. But he deleted it for some reason.

Here's the solution:

  1. remove all CSS height hacks and 100% heights
  2. Use 2 nested wrappers, one in another, e.g. #wrapper and #truecontent
  3. Get the height of a browser viewport. IF it's larger than #wrapper, then set inline CSS for #wrapper to match the current browser viewport height (while keeping #truecontent intact)
  4. Listen on (window).resize event and ONLY apply inline CSS height IF the viewport is larger than the height of #truecontent, otherwise keep intact

    $(function(){
        var windowH = $(window).height();
        var wrapperH = $('#wrapper').height();
        if(windowH > wrapperH) {                            
            $('#wrapper').css({'height':($(window).height())+'px'});
        }                                                                               
        $(window).resize(function(){
            var windowH = $(window).height();
            var wrapperH = $('#wrapper').height();
            var differenceH = windowH - wrapperH;
            var newH = wrapperH + differenceH;
            var truecontentH = $('#truecontent').height();
            if(windowH > truecontentH) {
                $('#wrapper').css('height', (newH)+'px');
            }
    
        })          
    });
    

What's the proper way to compare a String to an enum value?

Define enum:

public enum Gesture
{
    ROCK, PAPER, SCISSORS;
}

Define a method to check enum content:

private boolean enumContainsValue(String value)
{
    for (Gesture gesture : Gesture.values())
    {
        if (gesture.name().equals(value))
        {
            return true;
        }
    }

    return false;
}

And use it:

String gestureString = "PAPER";

if (enumContainsValue(gestureString))
{
    Gesture gestureId = Gesture.valueOf(gestureString);

    switch (gestureId)
    {
        case ROCK:
            Log.i("TAG", "ROCK");
            break;

        case PAPER:
            Log.i("TAG", "PAPER");
            break;

        case SCISSORS:
            Log.i("TAG", "SCISSORS");
            break;
    }
}

Emulate/Simulate iOS in Linux

The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.

It works pretty good for testing.

Convert a matrix to a 1 dimensional array

you can use as.vector(). It looks like it is the fastest method according to my little benchmark, as follows:

library(microbenchmark)
x=matrix(runif(1e4),100,100) # generate a 100x100 matrix
microbenchmark(y<-as.vector(x),y<-x[1:length(x)],y<-array(x),y<-c(x),times=1e4)

The first solution uses as.vector(), the second uses the fact that a matrix is stored as a contiguous array in memory and length(m) gives the number of elements in a matrix m. The third instantiates an array from x, and the fourth uses the concatenate function c(). I also tried unmatrix from gdata, but it's too slow to be mentioned here.

Here are some of the numerical results I obtained:

> microbenchmark(
        y<-as.vector(x),
        y<-x[1:length(x)],
        y<-array(x),
        y<-c(x),
        times=1e4)

Unit: microseconds
                expr    min      lq     mean  median      uq       max neval
   y <- as.vector(x)  8.251 13.1640 29.02656 14.4865 15.7900 69933.707 10000
 y <- x[1:length(x)] 59.709 70.8865 97.45981 73.5775 77.0910 75042.933 10000
       y <- array(x)  9.940 15.8895 26.24500 17.2330 18.4705  2106.090 10000
           y <- c(x) 22.406 33.8815 47.74805 40.7300 45.5955  1622.115 10000

Flattening a matrix is a common operation in Machine Learning, where a matrix can represent the parameters to learn but one uses an optimization algorithm from a generic library which expects a vector of parameters. So it is common to transform the matrix (or matrices) into such a vector. It's the case with the standard R function optim().

Algorithm to detect overlapping periods

I'm building a booking system and found this page. I'm interested in range intersection only, so I built this structure; it is enough to play with DateTime ranges.

You can check Intersection and check if a specific date is in range, and get the intersection type and the most important: you can get intersected Range.

public struct DateTimeRange
{

    #region Construction
    public DateTimeRange(DateTime start, DateTime end) {
        if (start>end) {
            throw new Exception("Invalid range edges.");
        }
        _Start = start;
        _End = end;
    }
    #endregion

    #region Properties
    private DateTime _Start;

    public DateTime Start {
        get { return _Start; }
        private set { _Start = value; }
    }
    private DateTime _End;

    public DateTime End {
        get { return _End; }
        private set { _End = value; }
    }
    #endregion

    #region Operators
    public static bool operator ==(DateTimeRange range1, DateTimeRange range2) {
        return range1.Equals(range2);
    }

    public static bool operator !=(DateTimeRange range1, DateTimeRange range2) {
        return !(range1 == range2);
    }
    public override bool Equals(object obj) {
        if (obj is DateTimeRange) {
            var range1 = this;
            var range2 = (DateTimeRange)obj;
            return range1.Start == range2.Start && range1.End == range2.End;
        }
        return base.Equals(obj);
    }
    public override int GetHashCode() {
        return base.GetHashCode();
    }
    #endregion

    #region Querying
    public bool Intersects(DateTimeRange range) {
        var type = GetIntersectionType(range);
        return type != IntersectionType.None;
    }
    public bool IsInRange(DateTime date) {
        return (date >= this.Start) && (date <= this.End);
    }
    public IntersectionType GetIntersectionType(DateTimeRange range) {
        if (this == range) {
            return IntersectionType.RangesEqauled;
        }
        else if (IsInRange(range.Start) && IsInRange(range.End)) {
            return IntersectionType.ContainedInRange;
        }
        else if (IsInRange(range.Start)) {
            return IntersectionType.StartsInRange;
        }
        else if (IsInRange(range.End)) {
            return IntersectionType.EndsInRange;
        }
        else if (range.IsInRange(this.Start) && range.IsInRange(this.End)) {
            return IntersectionType.ContainsRange;
        }
        return IntersectionType.None;
    }
    public DateTimeRange GetIntersection(DateTimeRange range) {
        var type = this.GetIntersectionType(range);
        if (type == IntersectionType.RangesEqauled || type==IntersectionType.ContainedInRange) {
            return range;
        }
        else if (type == IntersectionType.StartsInRange) {
            return new DateTimeRange(range.Start, this.End);
        }
        else if (type == IntersectionType.EndsInRange) {
            return new DateTimeRange(this.Start, range.End);
        }
        else if (type == IntersectionType.ContainsRange) {
            return this;
        }
        else {
            return default(DateTimeRange);
        }
    }
    #endregion


    public override string ToString() {
        return Start.ToString() + " - " + End.ToString();
    }
}
public enum IntersectionType
{
    /// <summary>
    /// No Intersection
    /// </summary>
    None = -1,
    /// <summary>
    /// Given range ends inside the range
    /// </summary>
    EndsInRange,
    /// <summary>
    /// Given range starts inside the range
    /// </summary>
    StartsInRange,
    /// <summary>
    /// Both ranges are equaled
    /// </summary>
    RangesEqauled,
    /// <summary>
    /// Given range contained in the range
    /// </summary>
    ContainedInRange,
    /// <summary>
    /// Given range contains the range
    /// </summary>
    ContainsRange,
}

Conversion failed when converting the nvarchar value ... to data type int

You got this Error because you tried to convert column DataType from String to int which is

leagal if and only if

you dont have row in that table with string content inside that column

so just make sure your previously inserted Rows is compatible with the new changes

Wait for async task to finish

How about calling a function from within your callback instead of returning a value in sync_call()?

function sync_call(input) {
    var value;

    // Assume the async call always succeed
    async_call(input, function(result) {
        value = result;
        use_value(value);
    } );
}

What should be the package name of android app?

Presently Package name starting with "com.example" is not allowed to upload in the app -store. Otherwise , all other package names starting with "com" are allowed .

Is there a difference between "throw" and "throw ex"?

Look at here: http://blog-mstechnology.blogspot.de/2010/06/throw-vs-throw-ex.html

Throw:

try 
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw;
}

It preserve the Stack information with Exception

This is called as "Rethrow"

If want to throw new exception,

throw new ApplicationException("operation failed!");

Throw Ex:

try
{
    // do some operation that can fail
}
catch (Exception ex)
{
    // do some local cleanup
    throw ex;
}

It Won't Send Stack information with Exception

This is called as "Breaking the Stack"

If want to throw new exception,

throw new ApplicationException("operation failed!",ex);

How to retrieve data from sqlite database in android and display it in TextView

You are using getData() method as void.

You can not return values from void.

ImportError: No module named 'encodings'

I could also fix this. PYTHONPATH and PYTHONHOME were in cause.

run this in a terminal

   touch ~/.bash_profile
   open ~/.bash_profile

and then delete all useless parts of this file, and save. I do not know how recommended it is to do that !

What is the difference between class and instance methods?

All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:

enter image description here

A class is like the blueprint of a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.

enter image description here

An instance (or an object) is the actual house that you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.

How to Create Multiple Where Clause Query Using Laravel Eloquent?

You may use in several ways,

$results = User::where([
    ['column_name1', '=', $value1],
    ['column_name2', '<', $value2],
    ['column_name3', '>', $value3]
])->get();

You can also use like this,

$results = User::orderBy('id','DESC');
$results = $results->where('column1','=', $value1);
$results = $results->where('column2','<',  $value2);
$results = $results->where('column3','>',  $value3);
$results = $results->get();

Is there a way to follow redirects with command line cURL?

Use the location header flag:

curl -L <URL>

How do I remove version tracking from a project cloned from git?

The easiest way to solve this problem is to use a command line. Type this command

rm -R .git/

OR

rm -rf .git/

How do I iterate over the words of a string?

We can use strtok in c++ ,

#include <iostream>
#include <cstring>
using namespace std;

int main()
{
    char str[]="Mickey M;12034;911416313;M;01a;9001;NULL;0;13;12;0;CPP,C;MSC,3D;FEND,BEND,SEC;";
    char *pch = strtok (str,";,");
    while (pch != NULL)
    {
        cout<<pch<<"\n";
        pch = strtok (NULL, ";,");
    }
    return 0;
}

PHP: How to send HTTP response code?

Unfortunately I found solutions presented by @dualed have various flaws.

  1. Using substr($sapi_type, 0, 3) == 'cgi' is not enogh to detect fast CGI. When using PHP-FPM FastCGI Process Manager, php_sapi_name() returns fpm not cgi

  2. Fasctcgi and php-fpm expose another bug mentioned by @Josh - using header('X-PHP-Response-Code: 404', true, 404); does work properly under PHP-FPM (FastCGI)

  3. header("HTTP/1.1 404 Not Found"); may fail when the protocol is not HTTP/1.1 (i.e. 'HTTP/1.0'). Current protocol must be detected using $_SERVER['SERVER_PROTOCOL'] (available since PHP 4.1.0

  4. There are at least 2 cases when calling http_response_code() result in unexpected behaviour:

    • When PHP encounter an HTTP response code it does not understand, PHP will replace the code with one it knows from the same group. For example "521 Web server is down" is replaced by "500 Internal Server Error". Many other uncommon response codes from other groups 2xx, 3xx, 4xx are handled this way.
    • On a server with php-fpm and nginx http_response_code() function MAY change the code as expected but not the message. This may result in a strange "404 OK" header for example. This problem is also mentioned on PHP website by a user comment http://www.php.net/manual/en/function.http-response-code.php#112423

For your reference here there is the full list of HTTP response status codes (this list includes codes from IETF internet standards as well as other IETF RFCs. Many of them are NOT currently supported by PHP http_response_code function): http://en.wikipedia.org/wiki/List_of_HTTP_status_codes

You can easily test this bug by calling:

http_response_code(521);

The server will send "500 Internal Server Error" HTTP response code resulting in unexpected errors if you have for example a custom client application calling your server and expecting some additional HTTP codes.


My solution (for all PHP versions since 4.1.0):

$httpStatusCode = 521;
$httpStatusMsg  = 'Web server is down';
$phpSapiName    = substr(php_sapi_name(), 0, 3);
if ($phpSapiName == 'cgi' || $phpSapiName == 'fpm') {
    header('Status: '.$httpStatusCode.' '.$httpStatusMsg);
} else {
    $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
    header($protocol.' '.$httpStatusCode.' '.$httpStatusMsg);
}

Conclusion

http_response_code() implementation does not support all HTTP response codes and may overwrite the specified HTTP response code with another one from the same group.

The new http_response_code() function does not solve all the problems involved but make things worst introducing new bugs.

The "compatibility" solution offered by @dualed does not work as expected, at least under PHP-FPM.

The other solutions offered by @dualed also have various bugs. Fast CGI detection does not handle PHP-FPM. Current protocol must be detected.

Any tests and comments are appreciated.

Import and insert sql.gz file into database with putty

Without a separate step to extract the archive:

# import gzipped-mysql dump
gunzip < DUMP_FILE.sql.gz | mysql --user=DB_USER --password DB_NAME

I use the above snippet to re-import mysqldump-backups, and the following for backing it up.

# mysqldump and gzip (-9 ? highest compression)
mysqldump --user=DB_USER --password DB_NAME | gzip -9 > DUMP_FILE.sql.gz

What is WEB-INF used for in a Java EE web application?

You should put in WEB-INF any pages, or pieces of pages, that you do not want to be public. Usually, JSP or facelets are found outside WEB-INF, but in this case they are easily accesssible for any user. In case you have some authorization restrictions, WEB-INF can be used for that.

WEB-INF/lib can contain 3rd party libraries which you do not want to pack at system level (JARs can be available for all the applications running on your server), but only for this particular applciation.

Generally speaking, many configurations files also go into WEB-INF.

As for WEB-INF/classes - it exists in any web-app, because that is the folder where all the compiled sources are placed (not JARS, but compiled .java files that you wrote yourself).

What does "res.render" do, and what does the html file look like?

What does res.render do and what does the html file look like?

res.render() function compiles your template (please don't use ejs), inserts locals there, and creates html output out of those two things.


Answering Edit 2 part.

// here you set that all templates are located in `/views` directory
app.set('views', __dirname + '/views');

// here you set that you're using `ejs` template engine, and the
// default extension is `ejs`
app.set('view engine', 'ejs');

// here you render `orders` template
response.render("orders", {orders: orders_json});

So, the template path is views/ (first part) + orders (second part) + .ejs (third part) === views/orders.ejs


Anyway, express.js documentation is good for what it does. It is API reference, not a "how to use node.js" book.

How do I unbind "hover" in jQuery?

You can remove a specific event handler that was attached by on, using off

$("#ID").on ("eventName", additionalCss, handlerFunction);

// to remove the specific handler
$("#ID").off ("eventName", additionalCss, handlerFunction);

Using this, you will remove only handlerFunction
Another good practice, is to set a nameSpace for multiple attached events

$("#ID").on ("eventName1.nameSpace", additionalCss, handlerFunction1);
$("#ID").on ("eventName2.nameSpace", additionalCss, handlerFunction2);
// ...
$("#ID").on ("eventNameN.nameSpace", additionalCss, handlerFunctionN);

// and to remove handlerFunction from 1 to N, just use this
$("#ID").off(".nameSpace");

Angular2 - Input Field To Accept Only Numbers

  1. <input oninput="this.value=this.value.replace(/[^0-9]/g,'')"

or: 2. in The HTML File :

 <input [(ngModel)]="data" (keypress)="stripText($event)"
     class="form-control">

in The ts File:

stripText(event) {
const seperator  = '^([0-9])';
const maskSeperator =  new RegExp(seperator , 'g');  
let result =maskSeperator.test(event.key);   return result;   }

This 2 solution works

Force to open "Save As..." popup open at text link click for PDF in HTML

A server-side solution is more compatible, until the "download" attribute is implemented in all the browsers.

One Python example could be a custom HTTP request handler for a filestore. The links that point to the filestore are generated like this:

http://www.myfilestore.com/filestore/13/130787e71/download_as/desiredName.pdf

Here is the code:

class HTTPFilestoreHandler(SimpleHTTPRequestHandler):

    def __init__(self, fs_path, *args):
        self.fs_path = fs_path                          # Filestore path
        SimpleHTTPRequestHandler.__init__(self, *args)

    def send_head(self):
        # Overwrite SimpleHTTPRequestHandler.send_head to force download name
        path = self.path
        get_index = (path == '/')
        self.log_message("path: %s" % path)
        if '/download_as/' in path:
            p_parts = path.split('/download_as/')
            assert len(p_parts) == 2, 'Bad download link:' + path
            path, download_as = p_parts
        path = self.translate_path(path )
        f = None
        if os.path.isdir(path):
            if not self.path.endswith('/'):
                # Redirect browser - doing basically what Apache does
                self.send_response(301)
                self.send_header("Location", self.path + "/")
                self.end_headers()
                return None
            else:
                return self.list_directory(path)
        ctype = self.guess_type(path)
        try:
            f = open(path, 'rb')
        except IOError:
            self.send_error(404, "File not found")
            return None
        self.send_response(200)
        self.send_header("Content-type", ctype)
        fs = os.fstat(f.fileno())
        self.send_header("Expires", '0')
        self.send_header("Last-Modified", self.date_time_string(fs.st_mtime))
        self.send_header("Cache-Control", 'must-revalidate, post-check=0, pre-check=0')
        self.send_header("Content-Transfer-Encoding", 'binary')
        if download_as:
            self.send_header("Content-Disposition", 'attachment; filename="%s"' % download_as)
        self.send_header("Content-Length", str(fs[6]))
        self.send_header("Connection", 'close')
        self.end_headers()
        return f


class HTTPFilestoreServer:

    def __init__(self, fs_path, server_address):
        def handler(*args):
            newHandler = HTTPFilestoreHandler(fs_path, *args)
            newHandler.protocol_version = "HTTP/1.0"
        self.server = BaseHTTPServer.HTTPServer(server_address, handler)

    def serve_forever(self, *args):
        self.server.serve_forever(*args)


def start_server(fs_path, ip_address, port):
    server_address = (ip_address, port)
    httpd = HTTPFilestoreServer(fs_path, server_address)

    sa = httpd.server.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    httpd.serve_forever()

ApiNotActivatedMapError for simple html page using google-places-api

I had the same error. To fix the error:

  1. Open the console menu Gallery Menu and select API Manager.
  2. On the left, click Credentials and then click New Credentials.
  3. Click Create Credentials.
  4. Click API KEY.
  5. Click Navigator Key (there are more options; It depends on when consumed).

You must use this new API Navigator Key, generated by the system.

How to specify new GCC path for CMake

Change CMAKE_<LANG>_COMPILER path without triggering a reconfigure

I wanted to compile with an alternate compiler, but also pass -D options on the command-line which would get wiped out by setting a different compiler. This happens because it triggers a re-configure. The trick is to disable the compiler detection with NONE, set the paths with FORCE, then enable_language.

project( sample_project NONE )

set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" FORCE )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" FORCE )

enable_language( C CXX )

Use a Toolchain file

The more sensible choice is to create a toolchain file.

set( CMAKE_SYSTEM_NAME Darwin )

set( COMPILER_BIN /opt/compiler/bin )
set( CMAKE_C_COMPILER ${COMPILER_BIN}/clang CACHE PATH "clang" )
set( CMAKE_CXX_COMPILER ${COMPILER_BIN}/clang++ CACHE PATH "clang++" )

Then you invoke Cmake with an additional flag

cmake -D CMAKE_TOOLCHAIN_FILE=/path/to/toolchain_file.cmake ...

Not class selector in jQuery

You can use the :not filter selector:

$('foo:not(".someClass")')

Or not() method:

$('foo').not(".someClass")

More Info:

Javascript: Call a function after specific time period

You can use JavaScript Timing Events to call function after certain interval of time:

This shows the alert box after 3 seconds:

setInterval(function(){alert("Hello")},3000);

You can use two method of time event in javascript.i.e.

  1. setInterval(): executes a function, over and over again, at specified time intervals
  2. setTimeout() : executes a function, once, after waiting a specified number of milliseconds

Failed to import new Gradle project: failed to find Build Tools revision *.0.0

Try to run gradle at the command line first. It might prompt you to setup and environment variable:

export _JAVA_OPTIONS="-Xms256m -Xmx1024m"

Read more here: 1, 2


Further make sure that the Android SDK build tools (adb, aapt, dx, dx.jar) are available in the PATH. If not you can create symlinks at the appropriate locations. They changed with the release of new SDK versions. Here is a shell script which creates the symlinks within the $ANDROID_HOME folder for you.

How do I create a comma-separated list using a SQL query?

MySQL

  SELECT r.name,
         GROUP_CONCAT(a.name SEPARATOR ',')
    FROM RESOURCES r
    JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
    JOIN APPLICATIONS a ON a.id = ar.app_id
GROUP BY r.name

**


MS SQL Server

SELECT r.name,
       STUFF((SELECT ','+ a.name
               FROM APPLICATIONS a
               JOIN APPLICATIONRESOURCES ar ON ar.app_id = a.id
              WHERE ar.resource_id = r.id
           GROUP BY a.name
            FOR XML PATH(''), TYPE).value('.','VARCHAR(max)'), 1, 1, '')
 FROM RESOURCES r
 GROUP BY deptno;

Oracle

  SELECT r.name,
         LISTAGG(a.name SEPARATOR ',') WITHIN GROUP (ORDER BY a.name)
  FROM RESOURCES r
        JOIN APPLICATIONSRESOURCES ar ON ar.resource_id = r.id
        JOIN APPLICATIONS a ON a.id = ar.app_id
  GROUP BY r.name;

How to write a switch statement in Ruby

Lots of great answers but I thought I would add one factoid.. If you are attempting to compare objects (Classes) make sure you have a space ship method (not a joke) or understand how they are being compared

"Ruby Equality And Object Comparison" is a good discussion on the topic.

Determining the current foreground application from a background task or service

Try the following code:

ActivityManager activityManager = (ActivityManager) newContext.getSystemService( Context.ACTIVITY_SERVICE );
List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses();
for(RunningAppProcessInfo appProcess : appProcesses){
    if(appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
        Log.i("Foreground App", appProcess.processName);
    }
}

Process name is the package name of the app running in foreground. Compare it to the package name of your application. If it is the same then your application is running on foreground.

I hope this answers your question.

How to add label in chart.js for pie chart

It is not necessary to use another library like newChart or use other people's pull requests to pull this off. All you have to do is define an options object and add the label wherever and however you want it in the tooltip.

var optionsPie = {
    tooltipTemplate: "<%= label %> - <%= value %>"
}

If you want the tooltip to be always shown you can make some other edits to the options:

 var optionsPie = {
        tooltipEvents: [],
        showTooltips: true,
        onAnimationComplete: function() {
            this.showTooltip(this.segments, true);
        },
        tooltipTemplate: "<%= label %> - <%= value %>"
    }

In your data items, you have to add the desired label property and value and that's all.

data = [
    {
        value: 480000,
        color:"#F7464A",
        highlight: "#FF5A5E",
        label: "Tobacco"
    }
];

Now, all you have to do is pass the options object after the data to the new Pie like this: new Chart(ctx).Pie(data,optionsPie) and you are done.

This probably works best for pies which are not very small in size.

Pie chart with labels

Display encoded html with razor

Try this:

<div class='content'>    
   @Html.Raw(HttpUtility.HtmlDecode(Model.Content))
</div>

'JSON' is undefined error in JavaScript in Internet Explorer

I had this error 2 times. Each time it was solved by changing the ajax type. Either GET to POST or POST to GET.

$.ajax({
        type:'GET', // or 'POST'
        url: "file.cfm?action=get_table&varb=" + varb
    });

in angularjs how to access the element that triggered the event?

To pass the source element in Angular 5 :

_x000D_
_x000D_
<input #myInput type="text" (change)="someFunction(myInput)">
_x000D_
_x000D_
_x000D_

How to check cordova android version of a cordova/phonegap project?

The current platform version of a cordova app can be checked by the following command

cordova platform version android

And can be upgraded using the command

cordova platform update android

You can replace android by any of your platform choice like "ios" or some else.

This only applies to android platform. I have not checked. You can try replacing android in the code segments to try for other platforms.

What is &amp used for

That's a great example. When &current is parsed into a text node it is converted to ¤t. When parsed into an attribute value, it is parsed as &current.

If you want &current in a text node, you should write &amp;current in your markup.

The gory details are in the HTML5 parsing spec - Named Character Reference State

Why use #define instead of a variable

Most common use (other than to declare constants) is an include guard.

Jest spyOn function called

You were almost done without any changes besides how you spyOn. When you use the spy, you have two options: spyOn the App.prototype, or component component.instance().

const spy = jest.spyOn(Class.prototype, "method")

The order of attaching the spy on the class prototype and rendering (shallow rendering) your instance is important.

const spy = jest.spyOn(App.prototype, "myClickFn");
const instance = shallow(<App />);

The App.prototype bit on the first line there are what you needed to make things work. A JavaScript class doesn't have any of its methods until you instantiate it with new MyClass(), or you dip into the MyClass.prototype. For your particular question, you just needed to spy on the App.prototype method myClickFn.

jest.spyOn(component.instance(), "method")

const component = shallow(<App />);
const spy = jest.spyOn(component.instance(), "myClickFn");

This method requires a shallow/render/mount instance of a React.Component to be available. Essentially spyOn is just looking for something to hijack and shove into a jest.fn(). It could be:

A plain object:

const obj = {a: x => (true)};
const spy = jest.spyOn(obj, "a");

A class:

class Foo {
    bar() {}
}

const nope = jest.spyOn(Foo, "bar");
// THROWS ERROR. Foo has no "bar" method.
// Only an instance of Foo has "bar".
const fooSpy = jest.spyOn(Foo.prototype, "bar");
// Any call to "bar" will trigger this spy; prototype or instance

const fooInstance = new Foo();
const fooInstanceSpy = jest.spyOn(fooInstance, "bar");
// Any call fooInstance makes to "bar" will trigger this spy.

Or a React.Component instance:

const component = shallow(<App />);
/*
component.instance()
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(component.instance(), "myClickFn");

Or a React.Component.prototype:

/*
App.prototype
-> {myClickFn: f(), render: f(), ...etc}
*/
const spy = jest.spyOn(App.prototype, "myClickFn");
// Any call to "myClickFn" from any instance of App will trigger this spy.

I've used and seen both methods. When I have a beforeEach() or beforeAll() block, I might go with the first approach. If I just need a quick spy, I'll use the second. Just mind the order of attaching the spy.

EDIT: If you want to check the side effects of your myClickFn you can just invoke it in a separate test.

const app = shallow(<App />);
app.instance().myClickFn()
/*
Now assert your function does what it is supposed to do...
eg.
expect(app.state("foo")).toEqual("bar");
*/

EDIT: Here is an example of using a functional component. Keep in mind that any methods scoped within your functional component are not available for spying. You would be spying on function props passed into your functional component and testing the invocation of those. This example explores the use of jest.fn() as opposed to jest.spyOn, both of which share the mock function API. While it does not answer the original question, it still provides insight on other techniques that could suit cases indirectly related to the question.

function Component({ myClickFn, items }) {
   const handleClick = (id) => {
       return () => myClickFn(id);
   };
   return (<>
       {items.map(({id, name}) => (
           <div key={id} onClick={handleClick(id)}>{name}</div>
       ))}
   </>);
}

const props = { myClickFn: jest.fn(), items: [/*...{id, name}*/] };
const component = render(<Component {...props} />);
// Do stuff to fire a click event
expect(props.myClickFn).toHaveBeenCalledWith(/*whatever*/);

What version of MongoDB is installed on Ubuntu

ANSWER: Read the instructions #dua

Ok the magic was in this line that I apparently missed when installing was:

$ sudo apt-get install mongodb-10gen=2.4.6

And the full process as described here http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/ is

$ sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
$ echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
$ sudo apt-get update
$ sudo apt-get install mongodb-10gen
$ sudo apt-get install mongodb-10gen=2.2.3
$ echo "mongodb-10gen hold" | sudo dpkg --set-selections
$ sudo service mongodb start

$ mongod --version
db version v2.4.6
Wed Oct 16 12:21:39.938 git version: b9925db5eac369d77a3a5f5d98a145eaaacd9673

IMPORTANT: Make sure you change 2.4.6 to the latest version (or whatever you want to install). Find the latest version number here http://www.mongodb.org/downloads

How do I update a model value in JavaScript in a Razor view?

You could use jQuery and an Ajax call to post the specific update back to your server with Javascript.

It would look something like this:

function updatePostID(val, comment)
{

    var args = {};
    args.PostID = val;
    args.Comment = comment;

    $.ajax({
     type: "POST",
     url: controllerActionMethodUrlHere,
     contentType: "application/json; charset=utf-8",
     data: args,
     dataType: "json",
     success: function(msg) 
     {
        // Something afterwards here

     }
    });

}

MySQL load NULL values from CSV data

The behaviour is different depending upon the database configuration. In the strict mode this would throw an error else a warning. Following query may be used for identifying the database configuration.

mysql> show variables like 'sql_mode';

java.lang.IllegalStateException: The specified child already has a parent

When you override OnCreateView in your RouteSearchFragment class, do you have the

if(view != null) {
    return view; 
}

code segment?

If so, removing the return statement should solve your problem.

You can keep the code and return the view if you don't want to regenerate view data, and onDestroyView() method you remove this view from its parent like so:

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (view != null) {
            ViewGroup parent = (ViewGroup) view.getParent();
            if (parent != null) {
                parent.removeAllViews();
            }
        }
    }

Using the Jersey client to do a POST operation

Starting from Jersey 2.x, the MultivaluedMapImpl class is replaced by MultivaluedHashMap. You can use it to add form data and send it to the server:

    WebTarget webTarget = client.target("http://www.example.com/some/resource");
    MultivaluedMap<String, String> formData = new MultivaluedHashMap<String, String>();
    formData.add("key1", "value1");
    formData.add("key2", "value2");
    Response response = webTarget.request().post(Entity.form(formData));

Note that the form entity is sent in the format of "application/x-www-form-urlencoded".

Converting PHP result array to JSON

$result = mysql_query($query) or die("Data not found."); 
$rows=array(); 
while($r=mysql_fetch_assoc($result))
{ 
$rows[]=$r;
}
header("Content-type:application/json"); 
echo json_encode($rows);

Cross-browser window resize event - JavaScript / jQuery

hope it will help in jQuery

define a function first, if there is an existing function skip to next step.

 function someFun() {
 //use your code
 }

browser resize use like these.

 $(window).on('resize', function () {
    someFun();  //call your function.
 });

OS X Sprite Kit Game Optimal Default Window Size

You should target the smallest, not the largest, supported pixel resolution by the devices your app can run on.

Say if there's an actual Mac computer that can run OS X 10.9 and has a native screen resolution of only 1280x720 then that's the resolution you should focus on. Any higher and your game won't correctly run on this device and you could as well remove that device from your supported devices list.

You can rely on upscaling to match larger screen sizes, but you can't rely on downscaling to preserve possibly important image details such as text or smaller game objects.

The next most important step is to pick a fitting aspect ratio, be it 4:3 or 16:9 or 16:10, that ideally is the native aspect ratio on most of the supported devices. Make sure your game only scales to fit on devices with a different aspect ratio.

You could scale to fill but then you must ensure that on all devices the cropped areas will not negatively impact gameplay or the use of the app in general (ie text or buttons outside the visible screen area). This will be harder to test as you'd actually have to have one of those devices or create a custom build that crops the view accordingly.

Alternatively you can design multiple versions of your game for specific and very common screen resolutions to provide the best game experience from 13" through 27" displays. Optimized designs for iMac (desktop) and a Macbook (notebook) devices make the most sense, it'll be harder to justify making optimized versions for 13" and 15" plus 21" and 27" screens.

But of course this depends a lot on the game. For example a tile-based world game could simply provide a larger viewing area onto the world on larger screen resolutions rather than scaling the view up. Provided that this does not alter gameplay, like giving the player an unfair advantage (specifically in multiplayer).

You should provide @2x images for the Retina Macbook Pro and future Retina Macs.

How to send an HTTP request with a header parameter?

If it says the API key is listed as a header, more than likely you need to set it in the headers option of your http request. Normally something like this :

headers: {'Authorization': '[your API key]'}

Here is an example from another Question

$http({method: 'GET', url: '[the-target-url]', headers: {
  'Authorization': '[your-api-key]'}
});

Edit : Just saw you wanted to store the response in a variable. In this case I would probably just use AJAX. Something like this :

$.ajax({ 
   type : "GET", 
   url : "[the-target-url]", 
   beforeSend: function(xhr){xhr.setRequestHeader('Authorization', '[your-api-key]');},
   success : function(result) { 
       //set your variable to the result 
   }, 
   error : function(result) { 
     //handle the error 
   } 
 }); 

I got this from this question and I'm at work so I can't test it at the moment but looks solid

Edit 2: Pretty sure you should be able to use this line :

headers: {'Authorization': '[your API key]'},

instead of the beforeSend line in the first edit. This may be simpler for you

org.hibernate.MappingException: Unknown entity

In case if you get this exception in SpringBoot application even though the entities are annotated with Entity annotation, it might be due to the spring not aware of where to scan for entities

To explicitly specify the package, add below

@SpringBootApplication
@EntityScan({"model.package.name"})
public class SpringBootApp {...}

note: If you model classes resides in the same or sub packages of SpringBootApplication annotated class, no need to explicitly declare the EntityScan, by default it will scan

Impersonate tag in Web.Config

Put the identity element before the authentication element

How to install PHP mbstring on CentOS 6.2

sudo yum install php<version>w-mbstring

ex. sudo yum install php56w-mbstring

Regex to match only letters

Use a character set: [a-zA-Z] matches one letter from A–Z in lowercase and uppercase. [a-zA-Z]+ matches one or more letters and ^[a-zA-Z]+$ matches only strings that consist of one or more letters only (^ and $ mark the begin and end of a string respectively).

If you want to match other letters than A–Z, you can either add them to the character set: [a-zA-ZäöüßÄÖÜ]. Or you use predefined character classes like the Unicode character property class \p{L} that describes the Unicode characters that are letters.

How to see JavaDoc in IntelliJ IDEA?

There is nice feature which shows quick documentation when your mouse is over element.

IntelliJ 14

Editor / General -> Show quick documentation on mouse move

Older versions

Add the following line to idea.properties file:

auto.show.quick.doc=true

What does 'public static void' mean in Java?

It means that:

  • public - it can be called from anywhere
  • static - it doesn't have any object state, so you can call it without instantiating an object
  • void - it doesn't return anything

You'd think that the lack of a return means it isn't doing much, but it might be saving things in the database, for example.

Angular2 - Focusing a textbox on component load

<input id="name" type="text" #myInput />
{{ myInput.focus() }}

this is the best and simplest way, because code "myInput.focus()" runs after input created

WARNING: this solution is acceptable only if you have single element in the form (user will be not able to select other elements)

Android - How To Override the "Back" button so it doesn't Finish() my Activity?

In Kotlin:

val callback = requireActivity().onBackPressedDispatcher.addCallback(this) {
    // Handle the back button event
}

For more information you can check this.

There is also specific question about overriding back button in Kotlin.

How do I spool to a CSV formatted file using SQLPLUS?

With newer versions of client tools, there are multiple options to format the query output. The rest is to spool it to a file or save the output as a file depending on the client tool. Here are few of the ways:

  • SQL*Plus

Using the SQL*Plus commands you could format to get your desired output. Use SPOOL to spool the output to a file.

For example,

SQL> SET colsep ,
SQL> SET pagesize 20
SQL> SET trimspool ON
SQL> SET linesize 200
SQL> SELECT * FROM scott.emp;

     EMPNO,ENAME     ,JOB      ,       MGR,HIREDATE ,       SAL,      COMM,    DEPTNO
----------,----------,---------,----------,---------,----------,----------,----------
      7369,SMITH     ,CLERK    ,      7902,17-DEC-80,       800,          ,        20
      7499,ALLEN     ,SALESMAN ,      7698,20-FEB-81,      1600,       300,        30
      7521,WARD      ,SALESMAN ,      7698,22-FEB-81,      1250,       500,        30
      7566,JONES     ,MANAGER  ,      7839,02-APR-81,      2975,          ,        20
      7654,MARTIN    ,SALESMAN ,      7698,28-SEP-81,      1250,      1400,        30
      7698,BLAKE     ,MANAGER  ,      7839,01-MAY-81,      2850,          ,        30
      7782,CLARK     ,MANAGER  ,      7839,09-JUN-81,      2450,          ,        10
      7788,SCOTT     ,ANALYST  ,      7566,09-DEC-82,      3000,          ,        20
      7839,KING      ,PRESIDENT,          ,17-NOV-81,      5000,          ,        10
      7844,TURNER    ,SALESMAN ,      7698,08-SEP-81,      1500,          ,        30
      7876,ADAMS     ,CLERK    ,      7788,12-JAN-83,      1100,          ,        20
      7900,JAMES     ,CLERK    ,      7698,03-DEC-81,       950,          ,        30
      7902,FORD      ,ANALYST  ,      7566,03-DEC-81,      3000,          ,        20
      7934,MILLER    ,CLERK    ,      7782,23-JAN-82,      1300,          ,        10

14 rows selected.

SQL>
  • SQL Developer Version pre 4.1

Alternatively, you could use the new /*csv*/ hint in SQL Developer.

/*csv*/

For example, in my SQL Developer Version 3.2.20.10:

enter image description here

Now you could save the output into a file.

  • SQL Developer Version 4.1

New in SQL Developer version 4.1, use the following just like sqlplus command and run as script. No need of the hint in the query.

SET SQLFORMAT csv

Now you could save the output into a file.

How do I restart nginx only after the configuration test was successful on Ubuntu?

You can use signals to control nginx.

According to documentation, you need to send HUP signal to nginx master process.

HUP - changing configuration, keeping up with a changed time zone (only for FreeBSD and Linux), starting new worker processes with a new configuration, graceful shutdown of old worker processes

Check the documentation here: http://nginx.org/en/docs/control.html

You can send the HUP signal to nginx master process PID like this:

kill -HUP $( cat /var/run/nginx.pid )

The command above reads the nginx PID from /var/run/nginx.pid. By default nginx pid is written to /usr/local/nginx/logs/nginx.pid but that can be overridden in config. Check your nginx.config to see where it saves the PID.

WebApi's {"message":"an error has occurred"} on IIS7, not in IIS Express

So i tried all the suggested solutions to no avail. All i did was to set run the app from the server and it displayed the error in full, this should have worked when i set customErrors mode to false but it didn't. The moment i browsed the API form the server i was able to see the problem.

Styling the last td in a table with css

In jQuery, provided the table is created either statically or dynamically prior to the following being executed:

$("table tr td:not(:last-child)").css({ "border-right":"1px solid #aaaaaa" });

Just adds a right border to every cell in a table row except the last cell.

Spring Boot @Value Properties

Make sure your application.properties file is under src/main/resources/application.properties. Is one way to go. Then add @PostConstruct as follows

Sample Application.properties

file.directory = somePlaceOverHere

Sample Java Class

@ComponentScan
public class PrintProperty {

  @Value("${file.directory}")
  private String fileDirectory;

  @PostConstruct
  public void print() {
    System.out.println(fileDirectory);
  }
}

Code above will print out "somePlaceOverhere"

How to use hex color values

Just some addiotion to the first answer

(haven't cehcked the alpha, may need to add an if netHext > 0xffffff):

extension UIColor {

struct COLORS_HEX {
    static let Primary = 0xffffff
    static let PrimaryDark = 0x000000
    static let Accent = 0xe89549
    static let AccentDark = 0xe27b2a
    static let TextWhiteSemiTransparent = 0x80ffffff
}

convenience init(red: Int, green: Int, blue: Int, alphaH: Int) {
    assert(red >= 0 && red <= 255, "Invalid red component")
    assert(green >= 0 && green <= 255, "Invalid green component")
    assert(blue >= 0 && blue <= 255, "Invalid blue component")
    assert(alphaH >= 0 && alphaH <= 255, "Invalid alpha component")

    self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(alphaH) / 255.0)
}

convenience init(netHex:Int) {
    self.init(red:(netHex >> 16) & 0xff, green:(netHex >> 8) & 0xff, blue:netHex & 0xff, alphaH: (netHex >> 24) & 0xff)
}

}

How to determine the IP address of a Solaris system

Try using ifconfig -a. Look for "inet xxx.xxx.xxx.xxx", that is your IP address

SQL query return data from multiple tables

Hopes this makes it find the tables as you're reading through the thing:

jsfiddle

mysql> show columns from colors;                                                         
+-------+-------------+------+-----+---------+----------------+
| Field | Type        | Null | Key | Default | Extra          |
+-------+-------------+------+-----+---------+----------------+           
| id    | int(3)      | NO   | PRI | NULL    | auto_increment |
| color | varchar(15) | YES  |     | NULL    |                |
| paint | varchar(10) | YES  |     | NULL    |                |
+-------+-------------+------+-----+---------+----------------+

How to evaluate a boolean variable in an if block in bash?

bash doesn't know boolean variables, nor does test (which is what gets called when you use [).

A solution would be:

if $myVar ; then ... ; fi

because true and false are commands that return 0 or 1 respectively which is what if expects.

Note that the values are "swapped". The command after if must return 0 on success while 0 means "false" in most programming languages.

SECURITY WARNING: This works because BASH expands the variable, then tries to execute the result as a command! Make sure the variable can't contain malicious code like rm -rf /

Valid values for android:fontFamily and what they map to?

Where do these values come from? The documentation for android:fontFamily does not list this information in any place

These are indeed not listed in the documentation. But they are mentioned here under the section 'Font families'. The document lists every new public API for Android Jelly Bean 4.1.

In the styles.xml file in the application I'm working on somebody listed this as the font family, and I'm pretty sure it's wrong:

Yes, that's wrong. You don't reference the font file, you have to use the font name mentioned in the linked document above. In this case it should have been this:

<item name="android:fontFamily">sans-serif</item>

Like the linked answer already stated, 12 variants are possible:

Added in Android Jelly Bean (4.1) - API 16 :

Regular (default):

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">normal</item> 

Italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">italic</item>

Bold:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold</item>

Bold-italic:

<item name="android:fontFamily">sans-serif</item>
<item name="android:textStyle">bold|italic</item>

Light:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">normal</item>

Light-italic:

<item name="android:fontFamily">sans-serif-light</item>
<item name="android:textStyle">italic</item>

Thin :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">normal</item>

Thin-italic :

<item name="android:fontFamily">sans-serif-thin</item>
<item name="android:textStyle">italic</item>

Condensed regular:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">normal</item>

Condensed italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">italic</item>

Condensed bold:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold</item>

Condensed bold-italic:

<item name="android:fontFamily">sans-serif-condensed</item>
<item name="android:textStyle">bold|italic</item>

Added in Android Lollipop (v5.0) - API 21 :

Medium:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">normal</item>

Medium-italic:

<item name="android:fontFamily">sans-serif-medium</item>
<item name="android:textStyle">italic</item>

Black:

<item name="android:fontFamily">sans-serif-black</item>
<item name="android:textStyle">italic</item>

For quick reference, this is how they all look like:

Twitter bootstrap 3 two columns full height

Modern and very simple solution:

HTML:

<div class="container">
  <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-9"></div>
  </div>
</div>

CSS:

.row{
    display: flex;
}

Redirect From Action Filter Attribute

Alternatively to a redirect, if it is calling your own code, you could use this:

actionContext.Result = new RedirectToRouteResult(
    new RouteValueDictionary(new { controller = "Home", action = "Error" })
);

actionContext.Result.ExecuteResult(actionContext.Controller.ControllerContext);

It is not a pure redirect but gives a similar result without unnecessary overhead.

What is the difference between .*? and .* regular expressions?

On greedy vs non-greedy

Repetition in regex by default is greedy: they try to match as many reps as possible, and when this doesn't work and they have to backtrack, they try to match one fewer rep at a time, until a match of the whole pattern is found. As a result, when a match finally happens, a greedy repetition would match as many reps as possible.

The ? as a repetition quantifier changes this behavior into non-greedy, also called reluctant (in e.g. Java) (and sometimes "lazy"). In contrast, this repetition will first try to match as few reps as possible, and when this doesn't work and they have to backtrack, they start matching one more rept a time. As a result, when a match finally happens, a reluctant repetition would match as few reps as possible.

References


Example 1: From A to Z

Let's compare these two patterns: A.*Z and A.*?Z.

Given the following input:

eeeAiiZuuuuAoooZeeee

The patterns yield the following matches:

Let's first focus on what A.*Z does. When it matched the first A, the .*, being greedy, first tries to match as many . as possible.

eeeAiiZuuuuAoooZeeee
   \_______________/
    A.* matched, Z can't match

Since the Z doesn't match, the engine backtracks, and .* must then match one fewer .:

eeeAiiZuuuuAoooZeeee
   \______________/
    A.* matched, Z still can't match

This happens a few more times, until finally we come to this:

eeeAiiZuuuuAoooZeeee
   \__________/
    A.* matched, Z can now match

Now Z can match, so the overall pattern matches:

eeeAiiZuuuuAoooZeeee
   \___________/
    A.*Z matched

By contrast, the reluctant repetition in A.*?Z first matches as few . as possible, and then taking more . as necessary. This explains why it finds two matches in the input.

Here's a visual representation of what the two patterns matched:

eeeAiiZuuuuAoooZeeee
   \__/r   \___/r      r = reluctant
    \____g____/        g = greedy

Example: An alternative

In many applications, the two matches in the above input is what is desired, thus a reluctant .*? is used instead of the greedy .* to prevent overmatching. For this particular pattern, however, there is a better alternative, using negated character class.

The pattern A[^Z]*Z also finds the same two matches as the A.*?Z pattern for the above input (as seen on ideone.com). [^Z] is what is called a negated character class: it matches anything but Z.

The main difference between the two patterns is in performance: being more strict, the negated character class can only match one way for a given input. It doesn't matter if you use greedy or reluctant modifier for this pattern. In fact, in some flavors, you can do even better and use what is called possessive quantifier, which doesn't backtrack at all.

References


Example 2: From A to ZZ

This example should be illustrative: it shows how the greedy, reluctant, and negated character class patterns match differently given the same input.

eeAiiZooAuuZZeeeZZfff

These are the matches for the above input:

Here's a visual representation of what they matched:

         ___n
        /   \              n = negated character class
eeAiiZooAuuZZeeeZZfff      r = reluctant
  \_________/r   /         g = greedy
   \____________/g

Related topics

These are links to questions and answers on stackoverflow that cover some topics that may be of interest.

One greedy repetition can outgreed another

Can't choose class as main class in IntelliJ

Select the folder containing the package tree of these classes, right-click and choose "Mark Directory as -> Source Root"

Handling very large numbers in Python

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int type has been dropped completely.

That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.

You can find all the gory details in PEP 0237.

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

Pie chart with jQuery

Flot

Limitations: lines, points, filled areas, bars, pie and combinations of these

From an interaction perspective, Flot by far will get you as close as possible to Flash graphing as you can get with jQuery. Whilst the graph output is pretty slick, and great looking, you can also interact with data points. What I mean by this is you can have the ability to hover over a data point and get visual feedback on the value of that point in the graph.

The trunk version of flot supports pie charts.

Flot Zoom capability.

On top of this, you also have the ability to select a chunk of the graph to get data back for a particular “zone”. As a secondary feature to this “zoning”, you can also select an area on a graph and zoom in to see the data points a little more closely. Very cool.


Sparklines

Limitations: Pie, Line, Bar, Combination

Sparklines is my favourite mini graphing tool out there. Really great for dashboard style graphs (think Google Analytics dashboard next time you login). Because they’re so tiny, they can be included in line (as in the example above). Another nice idea which can be used in all graphing plugins is the self-refresh capabilities. Their Mouse-Speed demo shows you the power of live charting at its best.


Query Chart 0.21

Limitations: Area, Line, Bar and combinations of these

jQuery Chart 0.21 isn’t the nicest looking charting plugin out there it has to be said. It’s pretty basic in functionality when it comes to the charts it can handle, however it can be flexible if you can put in some time and effort into it.

Adding values into a chart is relatively simple:

.chartAdd({

    "label"  : "Leads",
    "type"   : "Line",
    "color"  : "#008800",
    "values" : ["100","124","222","44","123","23","99"]
});

jQchart

Limitations: Bar, Line

jQchart is an odd one, they’ve built in animation transistions and drag/drop functionality into the chart, however it’s a little clunky – and seemingly pointless. It does generate nice looking charts if you get the CSS setup right, but there are better out there.


TufteGraph

Limitations: Bar and Stacked Bar

Tuftegraph sells itself as “pretty bar graphs that you would show your mother”. It comes close, Flot is prettier, but Tufte does lend itself to be very lightweight. Although with that comes restrictions – there are few options to choose from, so you get what you’re given. Check it out for a quick win bar chart.

write() versus writelines() and concatenated strings

if you just want to save and load a list try Pickle

Pickle saving:

with open("yourFile","wb")as file:
 pickle.dump(YourList,file)

and loading:

with open("yourFile","rb")as file:
 YourList=pickle.load(file)

How can I display an image from a file in Jupyter Notebook?

Courtesy of this page, I found this worked when the suggestions above didn't:

import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
    a = np.uint8(a)
    f = StringIO()
    PIL.Image.fromarray(a).save(f, fmt)
    IPython.display.display(IPython.display.Image(data=f.getvalue()))

How do I access named capturing groups in a .NET Regex?

The following code sample, will match the pattern even in case of space characters in between. i.e. :

<td><a href='/path/to/file'>Name of File</a></td>

as well as:

<td> <a      href='/path/to/file' >Name of File</a>  </td>

Method returns true or false, depending on whether the input htmlTd string matches the pattern or no. If it matches, the out params contain the link and name respectively.

/// <summary>
/// Assigns proper values to link and name, if the htmlId matches the pattern
/// </summary>
/// <returns>true if success, false otherwise</returns>
public static bool TryGetHrefDetails(string htmlTd, out string link, out string name)
{
    link = null;
    name = null;

    string pattern = "<td>\\s*<a\\s*href\\s*=\\s*(?:\"(?<link>[^\"]*)\"|(?<link>\\S+))\\s*>(?<name>.*)\\s*</a>\\s*</td>";

    if (Regex.IsMatch(htmlTd, pattern))
    {
        Regex r = new Regex(pattern,  RegexOptions.IgnoreCase | RegexOptions.Compiled);
        link = r.Match(htmlTd).Result("${link}");
        name = r.Match(htmlTd).Result("${name}");
        return true;
    }
    else
        return false;
}

I have tested this and it works correctly.

Count number of rows within each group

You can use by functions as by(df1$Year, df1$Month, count) that will produce a list of needed aggregation.

The output will look like,

df1$Month: Feb
     x freq
1 2012    1
2 2013    1
3 2014    5
--------------------------------------------------------------- 
df1$Month: Jan
     x freq
1 2012    5
2 2013    2
--------------------------------------------------------------- 
df1$Month: Mar
     x freq
1 2012    1
2 2013    3
3 2014    2
> 

How can I limit the visible options in an HTML <select> dropdown?

<p>Which one true?</p>
<select id="sel">
    <option>-</option>
    <option>A</option>
    <option>B</option>
    <option>C</option>
</select>

( display just first option of all options)

document.getElementById("sel").options.length=1; 

How to generate entire DDL of an Oracle schema (scriptable)?

The output of this query is very clean (original here)

clear screen
accept uname prompt 'Enter User Name : '
accept outfile prompt  ' Output filename : '

spool &&outfile..gen

SET LONG 20000 LONGCHUNKSIZE 20000 PAGESIZE 0 LINESIZE 1000 FEEDBACK OFF VERIFY OFF TRIMSPOOL ON

BEGIN
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'SQLTERMINATOR', true);
   DBMS_METADATA.set_transform_param (DBMS_METADATA.session_transform, 'PRETTY', true);
END;
/

SELECT dbms_metadata.get_ddl('USER','&&uname') FROM dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('SYSTEM_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('ROLE_GRANT','&&uname') from dual;
SELECT DBMS_METADATA.GET_GRANTED_DDL('OBJECT_GRANT','&&uname') from dual;

spool off

Batch files: List all files in a directory with relative paths

Of course, you may write a recursive algorithm in Batch that gives you exact control of what you do in every nested subdirectory:

@echo off
set mypath=
call :treeProcess
goto :eof

:treeProcess
setlocal
for %%f in (*.txt) do echo %mypath%%%f
for /D %%d in (*) do (
    set mypath=%mypath%%%d\
    cd %%d
    call :treeProcess
    cd ..
)
endlocal
exit /b

Have a variable in images path in Sass?

We can use relative path instead of absolute path:

$assetPath: '~src/assets/images/';
$logo-img: '#{$assetPath}logo.png';
@mixin logo {
  background-image: url(#{$logo-img});
}

.logo {
    max-width: 65px;
    @include logo;
 }

How do I upgrade the Python installation in Windows 10?

Python 2.x and Python 3.x are different. If you would like to download a newer version of Python 2, you could just download and install the newer version.

If you want to install Python 3, you could install Python 3 separately then change the path for Python 2.x to Python 3.x in Control Panel > All Control Panel Items > System > Advanced System Settings > Environment Variables.

How to open a specific port such as 9090 in Google Compute Engine

You need to:

  1. Go to cloud.google.com

  2. Go to my Console

  3. Choose your Project

  4. Choose Networking > VPC network

  5. Choose "Firewalls rules"

  6. Choose "Create Firewall Rule"

  7. To apply the rule to select VM instances, select Targets > "Specified target tags", and enter into "Target tags" the name of the tag. This tag will be used to apply the new firewall rule onto whichever instance you'd like. Then, make sure the instances have the network tag applied.

  8. To allow incoming TCP connections to port 9090, in "Protocols and Ports" enter tcp:9090

  9. Click Create

I hope this helps you.

Update Please refer to docs to customize your rules.

How to check whether a Button is clicked by using JavaScript

All the answers here discuss about onclick method, however you can also use addEventListener().

Syntax of addEventListener()

document.getElementById('button').addEventListener("click",{function defination});

The function defination above is known as anonymous function.

If you don't want to use anonymous functions you can also use function refrence.

function functionName(){
//function defination
}



document.getElementById('button').addEventListener("click",functionName);

You can check the detail differences between onclick() and addEventListener() in this answer here.

Replace new line/return with space using regex

This should take care of space, tab and newline:

data = data.replaceAll("[ \t\n\r]*", " ");

Why dict.get(key) instead of dict[key]?

Why dict.get(key) instead of dict[key]?

0. Summary

Comparing to dict[key], dict.get provides a fallback value when looking up for a key.

1. Definition

get(key[, default]) 4. Built-in Types — Python 3.6.4rc1 documentation

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

d = {"Name": "Harry", "Age": 17}
In [4]: d['gender']
KeyError: 'gender'
In [5]: d.get('gender', 'Not specified, please add it')
Out[5]: 'Not specified, please add it'

2. Problem it solves.

If without default value, you have to write cumbersome codes to handle such an exception.

def get_harry_info(key):
    try:
        return "{}".format(d[key])
    except KeyError:
        return 'Not specified, please add it'
In [9]: get_harry_info('Name')
Out[9]: 'Harry'
In [10]: get_harry_info('Gender')
Out[10]: 'Not specified, please add it'

As a convenient solution, dict.get introduces an optional default value avoiding above unwiedly codes.

3. Conclusion

dict.get has an additional default value option to deal with exception if key is absent from the dictionary

SQL Data Reader - handling Null column values

I think you would want to use:

SqlReader.IsDBNull(indexFirstName)

jquery remove "selected" attribute of option?

It's something in the way jQuery translates to IE8, not necessarily the browser itself.

I was able to work around by going old school and breaking out of jQuery for one line:

document.getElementById('myselect').selectedIndex = -1;

Notification bar icon turns white in Android 5 Lollipop

This is the code Android uses to display notification icons:

// android_frameworks_base/packages/SystemUI/src/com/android/systemui/
//   statusbar/BaseStatusBar.java

if (entry.targetSdk >= Build.VERSION_CODES.LOLLIPOP) {
    entry.icon.setColorFilter(mContext.getResources().getColor(android.R.color.white));
} else {
    entry.icon.setColorFilter(null);
}

So you need to set the target sdk version to something <21 and the icons will stay colored. This is an ugly workaround but it does what it is expected to do. Anyway, I really suggest following Google's Design Guidelines: "Notification icons must be entirely white."

Here is how you can implement it:

If you are using Gradle/Android Studio to build your apps, use build.gradle:

defaultConfig {
    targetSdkVersion 20
}

Otherwise (Eclipse etc) use AndroidManifest.xml:

<uses-sdk android:minSdkVersion="..." android:targetSdkVersion="20" />

Check if input is number or letter javascript

You can use the isNaN function to determine if a value does not convert to a number. Example as below:

function checkInp()
{
  var x=document.forms["myForm"]["age"].value;
  if (isNaN(x)) 
  {
    alert("Must input numbers");
    return false;
  }
}

Which Python memory profiler is recommended?

guppy3 is quite simple to use. At some point in your code, you have to write the following:

from guppy import hpy
h = hpy()
print(h.heap())

This gives you some output like this:

Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
0  35144  27  2140412  26   2140412  26 str
1  38397  29  1309020  16   3449432  42 tuple
2    530   0   739856   9   4189288  50 dict (no owner)

You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.

There is a graphical browser as well, written in Tk.

For Python 2.x, use Heapy.

How to trim a string to N chars in Javascript?

Just another suggestion, removing any trailing white-space

limitStrLength = (text, max_length) => {
    if(text.length > max_length - 3){
        return text.substring(0, max_length).trimEnd() + "..."
    }
    else{
        return text
    }

LINQ Inner-Join vs Left-Join

You need to get the joined objects into a set and then apply DefaultIfEmpty as JPunyon said:

Person magnus = new Person { Name = "Hedlund, Magnus" };
Person terry = new Person { Name = "Adams, Terry" };
Person charlotte = new Person { Name = "Weiss, Charlotte" };

Pet barley = new Pet { Name = "Barley", Owner = terry };
List<Person> people = new List<Person> { magnus, terry, charlotte };
List<Pet> pets = new List<Pet>{barley};

var results =
    from person in people
    join pet in pets on person.Name equals pet.Owner.Name into ownedPets
    from ownedPet in ownedPets.DefaultIfEmpty(new Pet())
    orderby person.Name
    select new { OwnerName = person.Name, ownedPet.Name };


foreach (var item in results)
{
    Console.WriteLine(
        String.Format("{0,-25} has {1}", item.OwnerName, item.Name ) );
}

Outputs:

Adams, Terry              has Barley
Hedlund, Magnus           has
Weiss, Charlotte          has

java collections - keyset() vs entrySet() in map

Every call to the Iterator.next() moves the iterator to the next element. If you want to use the current element in more than one statement or expression, you have to store it in a local variable. Or even better, why don't you simply use a for-each loop?

for (String key : map.keySet()) {
    System.out.println(key + ":" + map.get(key));
}

Moreover, loop over the entrySet is faster, because you don't query the map twice for each key. Also Map.Entry implementations usually implement the toString() method, so you don't have to print the key-value pair manually.

for (Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry);
}

How do you set the document title in React?

You can use the following below with document.title = 'Home Page'

import React from 'react'
import { Component } from 'react-dom'


class App extends Component{
  componentDidMount(){
    document.title = "Home Page"
  }

  render(){
    return(
      <p> Title is now equal to Home Page </p>
    )
  }
}

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

or You can use this npm package npm i react-document-title

import React from 'react'
import { Component } from 'react-dom'
import DocumentTitle from 'react-document-title';


class App extends Component{


  render(){
    return(
      <DocumentTitle title='Home'>
        <h1>Home, sweet home.</h1>
      </DocumentTitle>
    )
  }
}

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

Happy Coding!!!

for-in statement

edit 2018: This is outdated, js and typescript now have for..of loops.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html


The book "TypeScript Revealed" says

"You can iterate through the items in an array by using either for or for..in loops as demonstrated here:

// standard for loop
for (var i = 0; i < actors.length; i++)
{
  console.log(actors[i]);
}

// for..in loop
for (var actor in actors)
{
  console.log(actor);
}

"

Turns out, the second loop does not pass the actors in the loop. So would say this is plain wrong. Sadly it is as above, loops are untouched by typescript.

map and forEach often help me and are due to typescripts enhancements on function definitions more approachable, lke at the very moment:

this.notes = arr.map(state => new Note(state));

My wish list to TypeScript;

  1. Generic collections
  2. Iterators (IEnumerable, IEnumerator interfaces would be best)

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

C pointer to array/array of pointers disambiguation

I guess the second declaration is confusing to many. Here's an easy way to understand it.

Lets have an array of integers, i.e. int B[8].

Let's also have a variable A which points to B. Now, value at A is B, i.e. (*A) == B. Hence A points to an array of integers. In your question, arr is similar to A.

Similarly, in int* (*C) [8], C is a pointer to an array of pointers to integer.

graphing an equation with matplotlib

Your guess is right: the code is trying to evaluate x**3+2*x-4 immediately. Unfortunately you can't really prevent it from doing so. The good news is that in Python, functions are first-class objects, by which I mean that you can treat them like any other variable. So to fix your function, we could do:

import numpy as np  
import matplotlib.pyplot as plt  

def graph(formula, x_range):  
    x = np.array(x_range)  
    y = formula(x)  # <- note now we're calling the function 'formula' with x
    plt.plot(x, y)  
    plt.show()  

def my_formula(x):
    return x**3+2*x-4

graph(my_formula, range(-10, 11))

If you wanted to do it all in one line, you could use what's called a lambda function, which is just a short function without a name where you don't use def or return:

graph(lambda x: x**3+2*x-4, range(-10, 11))

And instead of range, you can look at np.arange (which allows for non-integer increments), and np.linspace, which allows you to specify the start, stop, and the number of points to use.

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

how can scrapy be used to scrape this dynamic data so that I can use it?

I wonder why no one has posted the solution using Scrapy only.

Check out the blog post from Scrapy team SCRAPING INFINITE SCROLLING PAGES . The example scraps http://spidyquotes.herokuapp.com/scroll website which uses infinite scrolling.

The idea is to use Developer Tools of your browser and notice the AJAX requests, then based on that information create the requests for Scrapy.

import json
import scrapy


class SpidyQuotesSpider(scrapy.Spider):
    name = 'spidyquotes'
    quotes_base_url = 'http://spidyquotes.herokuapp.com/api/quotes?page=%s'
    start_urls = [quotes_base_url % 1]
    download_delay = 1.5

    def parse(self, response):
        data = json.loads(response.body)
        for item in data.get('quotes', []):
            yield {
                'text': item.get('text'),
                'author': item.get('author', {}).get('name'),
                'tags': item.get('tags'),
            }
        if data['has_next']:
            next_page = data['page'] + 1
            yield scrapy.Request(self.quotes_base_url % next_page)

Docker compose, running containers in net:host

you can try just add

network_mode: "host"

example :

version: '2'
services:
  feedx:
    build: web
    ports:
    - "127.0.0.1:8000:8000"
    network_mode: "host"

list option available

network_mode: "bridge"
network_mode: "host"
network_mode: "none"
network_mode: "service:[service name]"
network_mode: "container:[container name/id]"

https://docs.docker.com/compose/compose-file/#network_mode

Get file name from URL

String fileName = url.substring( url.lastIndexOf('/')+1, url.length() );

String fileNameWithoutExtn = fileName.substring(0, fileName.lastIndexOf('.'));

How can I get phone serial number (IMEI)

public String getIMEI(Context context){

    TelephonyManager mngr = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE); 
    String imei = mngr.getDeviceId();
    return imei;

}

Calling async method on button click

This is what's killing you:

task.Wait();

That's blocking the UI thread until the task has completed - but the task is an async method which is going to try to get back to the UI thread after it "pauses" and awaits an async result. It can't do that, because you're blocking the UI thread...

There's nothing in your code which really looks like it needs to be on the UI thread anyway, but assuming you really do want it there, you should use:

private async void Button_Click(object sender, RoutedEventArgs 
{
    Task<List<MyObject>> task = GetResponse<MyObject>("my url");
    var items = await task;
    // Presumably use items here
}

Or just:

private async void Button_Click(object sender, RoutedEventArgs 
{
    var items = await GetResponse<MyObject>("my url");
    // Presumably use items here
}

Now instead of blocking until the task has completed, the Button_Click method will return after scheduling a continuation to fire when the task has completed. (That's how async/await works, basically.)

Note that I would also rename GetResponse to GetResponseAsync for clarity.

What are best practices for REST nested resources?

I've read all of the above answers but it seems like they have no common strategy. I found a good article about best practices in Design API from Microsoft Documents. I think you should refer.

In more complex systems, it can be tempting to provide URIs that enable a client to navigate through several levels of relationships, such as /customers/1/orders/99/products. However, this level of complexity can be difficult to maintain and is inflexible if the relationships between resources change in the future. Instead, try to keep URIs relatively simple. Once an application has a reference to a resource, it should be possible to use this reference to find items related to that resource. The preceding query can be replaced with the URI /customers/1/orders to find all the orders for customer 1, and then /orders/99/products to find the products in this order.

.

Tip

Avoid requiring resource URIs more complex than collection/item/collection.

Maintain/Save/Restore scroll position when returning to a ListView

For some looking for a solution to this problem, the root of the issue may be where you are setting your list views adapter. After you set the adapter on the listview, it resets the scroll position. Just something to consider. I moved setting the adapter into my onCreateView after we grab the reference to the listview, and it solved the problem for me. =)

Optimum way to compare strings in JavaScript?

Well in JavaScript you can check two strings for values same as integers so yo can do this:

  • "A" < "B"
  • "A" == "B"
  • "A" > "B"

And therefore you can make your own function that checks strings the same way as the strcmp().

So this would be the function that does the same:

function strcmp(a, b)
{   
    return (a<b?-1:(a>b?1:0));  
}

Convert string to binary then back again using PHP

That's funny how Stefan Gehrig his answer is actually the correct one. You don't need to convert a string into a "011010101" string to store it in BINARY field in a database. Anyway since this is the first answer that comes up when you google for "php convert string to binary string". Here is my contribution to this problem.

The most voted answer by Francois Deschenes goes wrong for long strings (either bytestrings or bitstrings) that is because

base_convert() may lose precision on large numbers due to properties related to the internal "double" or "float" type used. Please see the Floating point numbers section in the manual for more specific information and limitations.

From: https://secure.php.net/manual/en/function.base-convert.php

To work around this limitation you can chop up the input string into chunks. The functions below implement this technique.

<?php

function bytesToBits(string $bytestring) {
  if ($bytestring === '') return '';

  $bitstring = '';
  foreach (str_split($bytestring, 4) as $chunk) {
    $bitstring .= str_pad(base_convert(unpack('H*', $chunk)[1], 16, 2), strlen($chunk) * 8, '0', STR_PAD_LEFT);
  }

  return $bitstring;
}

function bitsToBytes(string $bitstring) {
  if ($bitstring === '') return '';

  // We want all bits to be right-aligned
  $bitstring_len = strlen($bitstring);
  if ($bitstring_len % 8 > 0) {
    $bitstring = str_pad($bitstring, intdiv($bitstring_len + 8, 8) * 8, '0', STR_PAD_LEFT);
  }

  $bytestring = '';
  foreach (str_split($bitstring, 32) as $chunk) {
    $bytestring .= pack('H*', str_pad(base_convert($chunk, 2, 16), strlen($chunk) / 4, '0', STR_PAD_LEFT));
  }

  return $bytestring;
}

for ($i = 0; $i < 10000; $i++) {
  $bytestring_in = substr(hash('sha512', uniqid('', true)), 0, rand(0, 128));
  $bits = bytesToBits($bytestring_in);
  $bytestring_out = bitsToBytes($bits);
  if ($bytestring_in !== $bytestring_out) {
    printf("IN  : %s\n", $bytestring_in);
    printf("BITS: %s\n", $bits);
    printf("OUT : %s\n", $bytestring_out);
    var_dump($bytestring_in, $bytestring_out); // printf() doesn't show some characters ..
    die('Error in functions [1].');
  }
}


for ($i = 0; $i < 10000; $i++) {
  $len = rand(0, 128);
  $bitstring_in = '';
  for ($j = 0; $j <= $len; $j++) {
    $bitstring_in .= (string) rand(0,1);
  }
  $bytes = bitsToBytes($bitstring_in);
  $bitstring_out = bytesToBits($bytes);

  // since converting to byte we always have a multitude of 4, so we need to correct the bitstring_in to compare ..
  $bitstring_in_old = $bitstring_in;
  $bitstring_in_len = strlen($bitstring_in);
  if ($bitstring_in_len % 8 > 0) {
    $bitstring_in = str_pad($bitstring_in, intdiv($bitstring_in_len + 8, 8) * 8, '0', STR_PAD_LEFT);
  }

  if ($bitstring_in !== $bitstring_out) {
    printf("IN1  : %s\n", $bitstring_in_old);
    printf("IN2  : %s\n", $bitstring_in);
    printf("BYTES: %s\n", $bytes);
    printf("OUT  : %s\n", $bitstring_out);
    var_dump($bytes); // printf() doesn't show some characters ..
    die('Error in functions [2].');
  }
}

echo 'All ok!' . PHP_EOL;

Note that if you insert a bitstring that is not a multitude of 8 (example: "101") you will not be able to recover the original bitstring when you converted to bytestring. From the bytestring converting back, uyou will get "00000101" which is numerically the same (unsigned 8 bit integer) but has a different string length. Therefor if the bitstring length is important to you you should save the length in a separate variable and chop of the first part of the string after converting.

$bits_in = "101";
$bits_in_len = strlen($bits_in); // <-- keep track if input length
$bits_out = bytesToBits(bitsToBytes("101"));
var_dump($bits_in, $bits_out, substr($bits_out, - $bits_in_len)); // recover original length with substr

Fastest way to serialize and deserialize .NET objects

The binary serializer included with .net should be faster that the XmlSerializer. Or another serializer for protobuf, json, ...

But for some of them you need to add Attributes, or some other way to add metadata. For example ProtoBuf uses numeric property IDs internally, and the mapping needs to be somehow conserved by a different mechanism. Versioning isn't trivial with any serializer.

The server response was: 5.7.0 Must issue a STARTTLS command first. i16sm1806350pag.18 - gsmtp

Loginto your gmail account https://myaccount.google.com/u/4/security-checkup/4

enter image description here

(See photo) review all locations Google may have blocked for "unknown" or suspicious activity.

Is it safe to use Project Lombok?

I'm not recommend it. I used to use it, but then when I work with NetBeans 7.4 it was messing my codes. I've to remove lombok in all of files in my projects. There is delombok, but how can I be sure it would not screw my codes. I have to spends days just to remove lombok and back to ordinary Java styles. I just too spicy...

How can I save a screenshot directly to a file in Windows?

Thanks to TheSoftwareJedi for providing useful information about snapping tool in Windows 7. Shortcut to open Snipping tool : Go to Start, type sni And you will find the name in the list "Snipping Tool"

enter image description here

How to change ReactJS styles dynamically?

Ok, finally found the solution.

Probably due to lack of experience with ReactJS and web development...

    var Task = React.createClass({
    render: function() {
      var percentage = this.props.children + '%';
      ....
        <div className="ui-progressbar-value ui-widget-header ui-corner-left" style={{width : percentage}}/>
      ...

I created the percentage variable outside in the render function.

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

I just came across this tonight. Can't say if they are legit, how long in business, and whether they'll be around long, but seems interesting. I may give them a try, and will post update if I do.

Per the website, they say they offer hourly pay-as-you-go and weekly/monthly plans, plus there's a free trial.

http://www.macincloud.com

Per @Iterator, posting update on my findings for this service, moving out from my comments:

I did the trial/evaluation. The trial can be misleading on how the trial works. You may need to signup to see prices but the trial so far, per the trial software download, doesn't appear to be time limited. It's just feature restricted. You signup to get your own account, but you actually use a generic trial login account to do the trial, not your own account. Your own account is used when you actually pay for the service. The trial limits what you can do, install, save, etc. but good enough to give you an idea of how things work. So it doesn't hurt to signup to evaluate and not pay anything.

Persistence of data is offered via saving files to DropBox (pre-installed, you just need login/configure), etc. There is no concept of AMIs, EBS, or some VM image. Their service is actually like a shared website hosting solution, where users timeshare a Mac machine (like timesharing a Unix/Linux server), and I think they limit or periodically purge what you put on the machine, or perhaps rather they don't backup your files, hence use of DropBox to do the backup. One should contact them to clarify this if desired.

They have various pricing options, as you mention the all day pass, monthly plans at $20, and their is a pay as you go plan at $1/hr. I'd probably go with pay as you go based on my usage. The pay as you go is based on prepaid credits (1 credit = 1 hour, billed at 30 credit increments). One caveat is that you need to periodically use the plan at least once every 60 days for the pay as you go plan or else you lose unused credits. So that's like minimum of spending 1 credit /1 hour every 60 days.

One last comment for now, from my evaluation, you'll need high bandwidth to use the service effectively. It's usable over 1.5 Mbps DSL but kind of slow in response. You'd want to use it from a corporate network with Gbps bandwidth for optimal use. Or at least a higher speed cable/DSL broadband connection. On my last test ~3Mbps seemed sufficient on the low bandwidth profile (they have multiple bandwidth connection profiles, low, medium, high, optimized for some bandwidth ranges). I didn't test on the higher ones. Your mileage may vary.

Javascript AES encryption

Use CryptoJS

Here's the code: https://github.com/odedhb/AES-encrypt

And here's an online working example: https://odedhb.github.io/AES-encrypt/

Error using eclipse for Android - No resource found that matches the given name

I renamed the file in res/values "strings.xml" to "string.xml" (no 's' on the end), cleaned and rebuilt without error.

What's the best way to add a full screen background image in React Native

The width and height with value null doesn't work for me, then I thought to use top, bottom, left, and right position and it worked. Example:

bg: {
        position: 'absolute',
        top: 0,
        bottom: 0,
        left: 0,
        right: 0,
        resizeMode: 'stretch',
},

And the JSX:

<Image style={styles.bg} source={{uri: 'IMAGE URI'}} />

Get startup type of Windows service using PowerShell

If you update to PowerShell 5 you can query all of the services on the machine and display Name and StartType and sort it by StartType for easy viewing:

Get-Service |Select-Object -Property Name,StartType |Sort-Object -Property StartType

Is there a way to only install the mysql client (Linux)?

there are two ways to install mysql client on centOS.

1. First method (download rpm package)

download rpm package from mysql website https://downloads.mysql.com/archives/community/ enter image description here

if you download this rpm package like picture, it's filename like mysql-community-client-8.0.21-1.el8.x86_64.rpm.

then execute sudo rpm -ivh --nodeps --force mysql-community-client-8.0.21-1.el8.x86_64.rpm can install the rpm package the parameters -ivh means install, print output, don't verify and check.

if raise error, maybe version conflict, you can execute rpm -pa | grep mysql to find conflicting package, then execute rpm -e --nodeps <package name> to remove them, and install once more.

finnaly, you can execute which mysql, it's success if print /usr/bin/mysql.

2.Second method (Set repo of yum)

Please refer to this official website:

MySQL Yum Repository

A Quick Guide to Using the MySQL Yum Repository

Type safety: Unchecked cast

Another solution, if you find yourself casting the same object a lot and you don't want to litter your code with @SupressWarnings("unchecked"), would be to create a method with the annotation. This way you're centralizing the cast, and hopefully reducing the possibility for error.

@SuppressWarnings("unchecked")
public static List<String> getFooStrings(Map<String, List<String>> ctx) {
    return (List<String>) ctx.get("foos");
}

Onclick event to remove default value in a text input field

<input name="Name" value="Enter Your Name" onfocus="freez(this)" onblur="freez(this)">


function freez(obj)
{
 if(obj.value=='')
 {
   obj.value='Enter Your Name';
 }else if(obj.value=='Enter Your Name')
 {
   obj.value='';
 }
} 

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I like this better than any of the previous answers. It shows how to use the YAML format and lets you use a variable to specify the bucket.

    - PolicyName: "AllowIncomingBucket"
      PolicyDocument:
        Version: "2012-10-17"
        Statement:
          - Effect: "Allow"
            Action: "s3:*"
            Resource:
              - !Ref S3BucketArn
              - !Join ["/", [!Ref S3BucketArn, '*']]

Is System.nanoTime() completely useless?

Since Java 7, System.nanoTime() is guaranteed to be safe by JDK specification. System.nanoTime()'s Javadoc makes it clear that all observed invocations within a JVM (that is, across all threads) are monotonic:

The value returned represents nanoseconds since some fixed but arbitrary origin time (perhaps in the future, so values may be negative). The same origin is used by all invocations of this method in an instance of a Java virtual machine; other virtual machine instances are likely to use a different origin.

JVM/JDK implementation is responsible for ironing out the inconsistencies that could be observed when underlying OS utilities are called (e. g. those mentioned in Tom Anderson's answer).

The majority of other old answers to this question (written in 2009–2012) express FUD that was probably relevant for Java 5 or Java 6 but is no longer relevant for modern versions of Java.

It's worth mentioning, however, that despite JDK guarantees nanoTime()'s safety, there have been several bugs in OpenJDK making it to not uphold this guarantee on certain platforms or under certain circumstances (e. g. JDK-8040140, JDK-8184271). There are no open (known) bugs in OpenJDK wrt nanoTime() at the moment, but a discovery of a new such bug or a regression in a newer release of OpenJDK shouldn't shock anybody.

With that in mind, code that uses nanoTime() for timed blocking, interval waiting, timeouts, etc. should preferably treat negative time differences (timeouts) as zeros rather than throw exceptions. This practice is also preferable because it is consistent with the behaviour of all timed wait methods in all classes in java.util.concurrent.*, for example Semaphore.tryAcquire(), Lock.tryLock(), BlockingQueue.poll(), etc.

Nonetheless, nanoTime() should still be preferred for implementing timed blocking, interval waiting, timeouts, etc. to currentTimeMillis() because the latter is a subject to the "time going backward" phenomenon (e. g. due to server time correction), i. e. currentTimeMillis() is not suitable for measuring time intervals at all. See this answer for more information.

Instead of using nanoTime() for code execution time measurements directly, specialized benchmarking frameworks and profilers should preferably be used, for example JMH and async-profiler in wall-clock profiling mode.

It is more efficient to use if-return-return or if-else-return?

Since the return statement terminates the execution of the current function, the two forms are equivalent (although the second one is arguably more readable than the first).

The efficiency of both forms is comparable, the underlying machine code has to perform a jump if the if condition is false anyway.

Note that Python supports a syntax that allows you to use only one return statement in your case:

return A+1 if A > B else A-1

What tool can decompile a DLL into C++ source code?

The closest you will ever get to doing such thing is a dissasembler, or debug info (Log2Vis.pdb).

jQuery - find child with a specific class

$(this).find(".bgHeaderH2").html();

or

$(this).find(".bgHeaderH2").text();

The value violated the integrity constraints for the column

the point can be if you are not using valid login for linked server. Problem is on destination server side.

There are few steps to try:

  1. Align db user and login on destination server: alter user [DBUSER_of_linkedserverlogin] with login = [linkedserverlogin]

  2. recreate login on destination server used by linked server.

  3. Backup table and recreate it.

2nd resolved my issue with "The value violated the integrity constraints for the column.".

Leverage browser caching, how on apache or .htaccess?

This is what I use to control headers/caching, I'm not an Apache pro, so let me know if there is room for improvement, but I know that this has been working well on all of my sites for some time now.

Mod_expires

http://httpd.apache.org/docs/2.2/mod/mod_expires.html

This module controls the setting of the Expires HTTP header and the max-age directive of the Cache-Control HTTP header in server responses. The expiration date can set to be relative to either the time the source file was last modified, or to the time of the client access.

These HTTP headers are an instruction to the client about the document's validity and persistence. If cached, the document may be fetched from the cache rather than from the source until this time has passed. After that, the cache copy is considered "expired" and invalid, and a new copy must be obtained from the source.

# BEGIN Expires
<ifModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 seconds"
ExpiresByType text/html "access plus 1 seconds"
ExpiresByType image/gif "access plus 2592000 seconds"
ExpiresByType image/jpeg "access plus 2592000 seconds"
ExpiresByType image/png "access plus 2592000 seconds"
ExpiresByType text/css "access plus 604800 seconds"
ExpiresByType text/javascript "access plus 216000 seconds"
ExpiresByType application/x-javascript "access plus 216000 seconds"
</ifModule>
# END Expires

Mod_headers

http://httpd.apache.org/docs/2.2/mod/mod_headers.html

This module provides directives to control and modify HTTP request and response headers. Headers can be merged, replaced or removed.

# BEGIN Caching
<ifModule mod_headers.c>
<filesMatch "\.(ico|pdf|flv|jpg|jpeg|png|gif|swf)$">
Header set Cache-Control "max-age=2592000, public"
</filesMatch>
<filesMatch "\.(css)$">
Header set Cache-Control "max-age=604800, public"
</filesMatch>
<filesMatch "\.(js)$">
Header set Cache-Control "max-age=216000, private"
</filesMatch>
<filesMatch "\.(xml|txt)$">
Header set Cache-Control "max-age=216000, public, must-revalidate"
</filesMatch>
<filesMatch "\.(html|htm|php)$">
Header set Cache-Control "max-age=1, private, must-revalidate"
</filesMatch>
</ifModule>
# END Caching

error code 1292 incorrect date value mysql

Insert date in the following format yyyy-MM-dd example,

INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) 
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', '[email protected]', 'http://www.hcentrale.it/', 'Trento', 'TN')

Jackson how to transform JsonNode to ArrayNode without casting?

I would assume at the end of the day you want to consume the data in the ArrayNode by iterating it. For that:

Iterator<JsonNode> iterator = datasets.withArray("datasets").elements();
while (iterator.hasNext()) 
        System.out.print(iterator.next().toString() + " "); 

or if you're into streams and lambda functions:

import com.google.common.collect.Streams;
Streams.stream(datasets.withArray("datasets").elements())
    .forEach( item -> System.out.print(item.toString()) )

How to list the properties of a JavaScript object?

Building on the accepted answer.

If the Object has properties you want to call say .properties() try!

var keys = Object.keys(myJSONObject);

for (var j=0; j < keys.length; j++) {
  Object[keys[j]].properties();
}

XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode

The accepted answer will return all the parent nodes too. To get only the actual nodes with ABC even if the string is after
:

//*[text()[contains(.,'ABC')]]/text()[contains(.,"ABC")]

How to create custom view programmatically in swift having controls text field, button etc

The CGRectZero constant is equal to a rectangle at position (0,0) with zero width and height. This is fine to use, and actually preferred, if you use AutoLayout, since AutoLayout will then properly place the view.

But, I expect you do not use AutoLayout. So the most simple solution is to specify the size of the custom view by providing a frame explicitly:

customView = MyCustomView(frame: CGRect(x: 0, y: 0, width: 200, height: 50))
self.view.addSubview(customView)

Note that you also need to use addSubview otherwise your view is not added to the view hierarchy.

How to get client's IP address using JavaScript?

It can't be done with Javascript alone (unless the clients have a browser plugin as described above). It can't be done with Flash on the client either. But it can be done on the client using a Java applet (and javascript can talk to that), although it will prompt for full permissions. e.g. See http://www.findmyrouter.net

All possible array initialization syntaxes

For Class initialization:
var page1 = new Class1();
var page2 = new Class2();
var pages = new UIViewController[] { page1, page2 };

Disable elastic scrolling in Safari

None of the above solutions worked for me, however instead I wrapped my content in a div (#outer-wrap) and then used the following CSS:

body {
   overflow: hidden;
}
#outer-wrap {
    -webkit-overflow-scrolling: touch;
     height: 100vh;
     overflow: auto;
}

Obviously only works in browsers that support viewport widths/heights of course.

Writing BMP image in pure c/c++ without other libraries

I just wanted to share an improved version of Minhas Kamal's code because although it worked well enough for most applications, I had a few issues with it still. Two highly important things to remember:

  1. The code (at the time of writing) calls free() on two static arrays. This will cause your program to crash. So I commented out those lines.
  2. NEVER assume that your pixel data's pitch is always (Width*BytesPerPixel). It's best to let the user specify the pitch value. Example: when manipulating resources in Direct3D, the RowPitch is never guaranteed to be an even multiple of the byte depth being used. This can cause errors in your generated bitmaps (especially at odd resolutions such as 1366x768).

Below, you can see my revisions to his code:

const int bytesPerPixel = 4; /// red, green, blue
const int fileHeaderSize = 14;
const int infoHeaderSize = 40;

void generateBitmapImage(unsigned char *image, int height, int width, int pitch, const char* imageFileName);
unsigned char* createBitmapFileHeader(int height, int width, int pitch, int paddingSize);
unsigned char* createBitmapInfoHeader(int height, int width);



void generateBitmapImage(unsigned char *image, int height, int width, int pitch, const char* imageFileName) {

    unsigned char padding[3] = { 0, 0, 0 };
    int paddingSize = (4 - (/*width*bytesPerPixel*/ pitch) % 4) % 4;

    unsigned char* fileHeader = createBitmapFileHeader(height, width, pitch, paddingSize);
    unsigned char* infoHeader = createBitmapInfoHeader(height, width);

    FILE* imageFile = fopen(imageFileName, "wb");

    fwrite(fileHeader, 1, fileHeaderSize, imageFile);
    fwrite(infoHeader, 1, infoHeaderSize, imageFile);

    int i;
    for (i = 0; i < height; i++) {
        fwrite(image + (i*pitch /*width*bytesPerPixel*/), bytesPerPixel, width, imageFile);
        fwrite(padding, 1, paddingSize, imageFile);
    }

    fclose(imageFile);
    //free(fileHeader);
    //free(infoHeader);
}

unsigned char* createBitmapFileHeader(int height, int width, int pitch, int paddingSize) {
    int fileSize = fileHeaderSize + infoHeaderSize + (/*bytesPerPixel*width*/pitch + paddingSize) * height;

    static unsigned char fileHeader[] = {
        0,0, /// signature
        0,0,0,0, /// image file size in bytes
        0,0,0,0, /// reserved
        0,0,0,0, /// start of pixel array
    };

    fileHeader[0] = (unsigned char)('B');
    fileHeader[1] = (unsigned char)('M');
    fileHeader[2] = (unsigned char)(fileSize);
    fileHeader[3] = (unsigned char)(fileSize >> 8);
    fileHeader[4] = (unsigned char)(fileSize >> 16);
    fileHeader[5] = (unsigned char)(fileSize >> 24);
    fileHeader[10] = (unsigned char)(fileHeaderSize + infoHeaderSize);

    return fileHeader;
}

unsigned char* createBitmapInfoHeader(int height, int width) {
    static unsigned char infoHeader[] = {
        0,0,0,0, /// header size
        0,0,0,0, /// image width
        0,0,0,0, /// image height
        0,0, /// number of color planes
        0,0, /// bits per pixel
        0,0,0,0, /// compression
        0,0,0,0, /// image size
        0,0,0,0, /// horizontal resolution
        0,0,0,0, /// vertical resolution
        0,0,0,0, /// colors in color table
        0,0,0,0, /// important color count
    };

    infoHeader[0] = (unsigned char)(infoHeaderSize);
    infoHeader[4] = (unsigned char)(width);
    infoHeader[5] = (unsigned char)(width >> 8);
    infoHeader[6] = (unsigned char)(width >> 16);
    infoHeader[7] = (unsigned char)(width >> 24);
    infoHeader[8] = (unsigned char)(height);
    infoHeader[9] = (unsigned char)(height >> 8);
    infoHeader[10] = (unsigned char)(height >> 16);
    infoHeader[11] = (unsigned char)(height >> 24);
    infoHeader[12] = (unsigned char)(1);
    infoHeader[14] = (unsigned char)(bytesPerPixel * 8);

    return infoHeader;
}

Postgres DB Size Command

You can use below query to find the size of all databases of PostgreSQL.

Reference is taken from this blog.

SELECT 
    datname AS DatabaseName
    ,pg_catalog.pg_get_userbyid(datdba) AS OwnerName
    ,CASE 
        WHEN pg_catalog.has_database_privilege(datname, 'CONNECT')
        THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(datname))
        ELSE 'No Access For You'
    END AS DatabaseSize
FROM pg_catalog.pg_database
ORDER BY 
    CASE 
        WHEN pg_catalog.has_database_privilege(datname, 'CONNECT')
        THEN pg_catalog.pg_database_size(datname)
        ELSE NULL
    END DESC;

In Python how should I test if a variable is None, True or False

I would like to stress that, even if there are situations where if expr : isn't sufficient because one wants to make sure expr is True and not just different from 0/None/whatever, is is to be prefered from == for the same reason S.Lott mentionned for avoiding == None.

It is indeed slightly more efficient and, cherry on the cake, more human readable.

In [1]: %timeit (1 == 1) == True
38.1 ns ± 0.116 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]: %timeit (1 == 1) is True
33.7 ns ± 0.141 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Change GitHub Account username

Yes, this is an old question. But it's misleading, as this was the first result in my search, and both the answers aren't correct anymore.

You can change your Github account name at any time.

To do this, click your profile picture > Settings > Account Settings > Change Username.

Links to your repositories will redirect to the new URLs, but they should be updated on other sites because someone who chooses your abandoned username can override the links. Links to your profile page will be 404'd.

For more information, see the official help page.

And furthermore, if you want to change your username to something else, but that specific username is being taken up by someone else who has been completely inactive for the entire time their account has existed, you can report their account for name squatting.

Filter LogCat to get only the messages from My Application in Android?

This works for me with USB debugging, use your device's own logcat directly via shell

  1. Connect the device and use:

    adb shell

  2. Use the logcat when connected:

    logcat | grep com.yourapp.packagename

Python Create unix timestamp five minutes in the future

Another way is to use calendar.timegm:

future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
return calendar.timegm(future.timetuple())

It's also more portable than %s flag to strftime (which doesn't work on Windows).