Programs & Examples On #Webdav

WebDAV (World Wide Web Distributed Authoring and Versioning) is the Internet Engineering Task Force (IETF) standard for collaborative authoring on the Web

405 method not allowed Web API

check in your project .csproj file and change

<IISUrl>http://localhost:PORT/</IISUrl>

to your website url like this

<IISUrl>http://example.com:applicationName/</IISUrl>

How do I programmatically "restart" an Android app?

The only code that did not trigger "Your app has closed unexpectedly" is as follows. It's also non-deprecated code that doesn't require an external library. It also doesn't require a timer.

public static void triggerRebirth(Context context, Class myClass) {
    Intent intent = new Intent(context, myClass);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    context.startActivity(intent);
    Runtime.getRuntime().exit(0);
}

Changing the space between each item in Bootstrap navbar

With regard to bootstrap, the correct answer is using spacing utilities as mentioned by loopasam in a previous comment. Following is an example of using padding for both left and right.

<a href="#" class="nav-item nav-link px-3">Blog</a>

How to convert seconds to time format?

something like this?

if(is_numeric($time)){
    $value = array(
        "years" => 0, "days" => 0, "hours" => 0,
        "minutes" => 0, "seconds" => 0,
    );
    if($time >= 31556926){
        $value["years"] = floor($time/31556926);
        $time = ($time%31556926);
    }
    if($time >= 86400){
        $value["days"] = floor($time/86400);
        $time = ($time%86400);
    }
    if($time >= 3600){
        $value["hours"] = floor($time/3600);
        $time = ($time%3600);
    }
    if($time >= 60){
        $value["minutes"] = floor($time/60);
        $time = ($time%60);
    }

    $value["seconds"] = floor($time);
    return (array) $value;
    
} else{
    return (bool) FALSE;
}

grabbed from: http://www.ckorp.net/sec2time.php

How to scroll to an element?

Just a heads up, I couldn't get these solutions to work on Material UI components. Looks like they don't have the current property.

I just added an empty div amongst my components and set the ref prop on that.

How to get the full URL of a Drupal page?

The following is more Drupal-ish:

url(current_path(), array('absolute' => true)); 

Return Type for jdbcTemplate.queryForList(sql, object, classType)

queryForList returns a List of LinkedHashMap objects.

You need to cast it first like this:


    List list = jdbcTemplate.queryForList(...);
    for (Object o : list) {
       Map m = (Map) o;
       ...
    }

Vuex - passing multiple parameters to mutation

In simple terms you need to build your payload into a key array

payload = {'key1': 'value1', 'key2': 'value2'}

Then send the payload directly to the action

this.$store.dispatch('yourAction', payload)

No change in your action

yourAction: ({commit}, payload) => {
  commit('YOUR_MUTATION',  payload )
},

In your mutation call the values with the key

'YOUR_MUTATION' (state,  payload ){
  state.state1 = payload.key1
  state.state2 =  payload.key2
},

How can I add items to an empty set in python

When you assign a variable to empty curly braces {} eg: new_set = {}, it becomes a dictionary. To create an empty set, assign the variable to a 'set()' ie: new_set = set()

Find all elements on a page whose element ID contains a certain text using jQuery

$('*[id*=mytext]:visible').each(function() {
    $(this).doStuff();
});

Note the asterisk '*' at the beginning of the selector matches all elements.

See the Attribute Contains Selectors, as well as the :visible and :hidden selectors.

How do I check if a variable exists?

I will assume that the test is going to be used in a function, similar to user97370's answer. I don't like that answer because it pollutes the global namespace. One way to fix it is to use a class instead:

class InitMyVariable(object):
  my_variable = None

def __call__(self):
  if self.my_variable is None:
   self.my_variable = ...

I don't like this, because it complicates the code and opens up questions such as, should this confirm to the Singleton programming pattern? Fortunately, Python has allowed functions to have attributes for a while, which gives us this simple solution:

def InitMyVariable():
  if InitMyVariable.my_variable is None:
    InitMyVariable.my_variable = ...
InitMyVariable.my_variable = None

How can I URL encode a string in Excel VBA?

For the sake of bringing this up to date, since Excel 2013 there is now a built-in way of encoding URLs using the worksheet function ENCODEURL.

To use it in your VBA code you just need to call

EncodedUrl = WorksheetFunction.EncodeUrl(InputString)

Documentation

Check if a JavaScript string is a URL

This function disallows localhost and only allows URLs for web pages (ie, only allows http or https protocol).

It also only allows safe characters as defined here: https://www.urlencoder.io/learn/

function isValidWebUrl(url) {
   let regEx = /^https?:\/\/(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)$/gm;
   return regEx.test(url);
}

how to modify an existing check constraint?

No. If such a feature existed it would be listed in this syntax illustration. (Although it's possible there is an undocumented SQL feature, or maybe there is some package that I'm not aware of.)

How to debug a referenced dll (having pdb)

The following solution worked for me. It involves copy pasting the .dll and .pdb files properly from project A to B: https://stackoverflow.com/a/16546777/5351410

Python check if website exists

It's better to check that status code is < 400, like it was done here. Here is what do status codes mean (taken from wikipedia):

  • 1xx - informational
  • 2xx - success
  • 3xx - redirection
  • 4xx - client error
  • 5xx - server error

If you want to check if page exists and don't want to download the whole page, you should use Head Request:

import httplib2
h = httplib2.Http()
resp = h.request("http://www.google.com", 'HEAD')
assert int(resp[0]['status']) < 400

taken from this answer.

If you want to download the whole page, just make a normal request and check the status code. Example using requests:

import requests

response = requests.get('http://google.com')
assert response.status_code < 400

See also similar topics:

Hope that helps.

How to change the color of winform DataGridview header?

If you want to change a color to single column try this:

 dataGridView1.EnableHeadersVisualStyles = false;
 dataGridView1.Columns[0].HeaderCell.Style.BackColor = Color.Magenta;
 dataGridView1.Columns[1].HeaderCell.Style.BackColor = Color.Yellow;

Display JSON as HTML

First take the JSON string and make real objects out of it. Loop though all of the properties of the object, placing the items in an unordered list. Every time you get to a new object, make a new list.

batch to copy files with xcopy

You must specify your file in the copy:

xcopy C:\source\myfile.txt C:\target

Or if you want to copy all txt files for example

xcopy C:\source\*.txt C:\target

Are PHP Variables passed by value or by reference?

For anyone who comes across this in the future, I want to share this gem from the PHP docs, posted by an anonymous user:

There seems to be some confusion here. The distinction between pointers and references is not particularly helpful. The behavior in some of the "comprehensive" examples already posted can be explained in simpler unifying terms. Hayley's code, for example, is doing EXACTLY what you should expect it should. (Using >= 5.3)

First principle: A pointer stores a memory address to access an object. Any time an object is assigned, a pointer is generated. (I haven't delved TOO deeply into the Zend engine yet, but as far as I can see, this applies)

2nd principle, and source of the most confusion: Passing a variable to a function is done by default as a value pass, ie, you are working with a copy. "But objects are passed by reference!" A common misconception both here and in the Java world. I never said a copy OF WHAT. The default passing is done by value. Always. WHAT is being copied and passed, however, is the pointer. When using the "->", you will of course be accessing the same internals as the original variable in the caller function. Just using "=" will only play with copies.

3rd principle: "&" automatically and permanently sets another variable name/pointer to the same memory address as something else until you decouple them. It is correct to use the term "alias" here. Think of it as joining two pointers at the hip until forcibly separated with "unset()". This functionality exists both in the same scope and when an argument is passed to a function. Often the passed argument is called a "reference," due to certain distinctions between "passing by value" and "passing by reference" that were clearer in C and C++.

Just remember: pointers to objects, not objects themselves, are passed to functions. These pointers are COPIES of the original unless you use "&" in your parameter list to actually pass the originals. Only when you dig into the internals of an object will the originals change.

And here's the example they provide:

<?php

//The two are meant to be the same
$a = "Clark Kent"; //a==Clark Kent
$b = &$a; //The two will now share the same fate.

$b="Superman"; // $a=="Superman" too.
echo $a;
echo $a="Clark Kent"; // $b=="Clark Kent" too.
unset($b); // $b divorced from $a
$b="Bizarro";
echo $a; // $a=="Clark Kent" still, since $b is a free agent pointer now.

//The two are NOT meant to be the same.
$c="King";
$d="Pretender to the Throne";
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByValue($c, $d);
echo $c."\n"; // $c=="King"
echo $d."\n"; // $d=="Pretender to the Throne"
swapByRef($c, $d);
echo $c."\n"; // $c=="Pretender to the Throne"
echo $d."\n"; // $d=="King"

function swapByValue($x, $y){
$temp=$x;
$x=$y;
$y=$temp;
//All this beautiful work will disappear
//because it was done on COPIES of pointers.
//The originals pointers still point as they did.
}

function swapByRef(&$x, &$y){
$temp=$x;
$x=$y;
$y=$temp;
//Note the parameter list: now we switched 'em REAL good.
}

?>

I wrote an extensive, detailed blog post on this subject for JavaScript, but I believe it applies equally well to PHP, C++, and any other language where people seem to be confused about pass by value vs. pass by reference.

Clearly, PHP, like C++, is a language that does support pass by reference. By default, objects are passed by value. When working with variables that store objects, it helps to see those variables as pointers (because that is fundamentally what they are, at the assembly level). If you pass a pointer by value, you can still "trace" the pointer and modify the properties of the object being pointed to. What you cannot do is have it point to a different object. Only if you explicitly declare a parameter as being passed by reference will you be able to do that.

Getting a list of all subdirectories in the current directory

Function to return a List of all subdirectories within a given file path. Will search through the entire file tree.

import os

def get_sub_directory_paths(start_directory, sub_directories):
    """
    This method iterates through all subdirectory paths of a given 
    directory to collect all directory paths.

    :param start_directory: The starting directory path.
    :param sub_directories: A List that all subdirectory paths will be 
        stored to.
    :return: A List of all sub-directory paths.
    """

    for item in os.listdir(start_directory):
        full_path = os.path.join(start_directory, item)

        if os.path.isdir(full_path):
            sub_directories.append(full_path)

            # Recursive call to search through all subdirectories.
            get_sub_directory_paths(full_path, sub_directories)

return sub_directories

Using File.listFiles with FileNameExtensionFilter

With java lambdas (available since java 8) you can simply convert javax.swing.filechooser.FileFilter to java.io.FileFilter in one line.

javax.swing.filechooser.FileFilter swingFilter = new FileNameExtensionFilter("jpeg files", "jpeg");
java.io.FileFilter ioFilter = file -> swingFilter.accept(file);
new File("myDirectory").listFiles(ioFilter);

CSS: Center block, but align contents to the left

Is this what you are looking for? Flexbox...

_x000D_
_x000D_
.container{_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
  justify-content: center;_x000D_
  align-content: center;_x000D_
  align-items: center;_x000D_
}_x000D_
.inside{_x000D_
  height:100px;_x000D_
  width:100px;_x000D_
  background:gray;_x000D_
  border:1px solid;_x000D_
}
_x000D_
<section class="container">_x000D_
  <section class="inside">_x000D_
    A_x000D_
  </section>_x000D_
  <section class="inside">_x000D_
    B_x000D_
  </section>_x000D_
  <section class="inside">_x000D_
    C_x000D_
  </section>_x000D_
</section>
_x000D_
_x000D_
_x000D_

MySQl Error #1064

maybe you forgot to add ";" after this line of code:

`quantity` INT NOT NULL)

Add a linebreak in an HTML text area

If you're inserting text from a database or such (which one usually do), convert all "<br />"'s to &vbCrLf. Works great for me :)

How can I check if char* variable points to empty string?

if (!*ptr) { /* empty string  */}

similarly

if (*ptr)  { /* not empty */ }

How to convert an integer to a character array using C

The easy way is by using sprintf. I know others have suggested itoa, but a) it isn't part of the standard library, and b) sprintf gives you formatting options that itoa doesn't.

How do I configure HikariCP in my Spring Boot app in my application.properties files?

Here is the good news. HikariCP is the default connection pool now with Spring Boot 2.0.0.

Spring Boot 2.0.0 Release Notes

The default database pooling technology in Spring Boot 2.0 has been switched from Tomcat Pool to HikariCP. We’ve found that Hakari offers superior performance, and many of our users prefer it over Tomcat Pool.

What are the advantages and disadvantages of recursion?

All algorithms can be defined recursively. That makes it much, much easier to visualize and prove.

Some algorithms (e.g., the Ackermann Function) cannot (easily) be specified iteratively.

A recursive implementation will use more memory than a loop if tail call optimization can't be performed. While iteration may use less memory than a recursive function that can't be optimized, it has some limitations in its expressive power.

Android Center text on canvas

This worked for me :

 paint.setTextAlign(Paint.Align.CENTER);
        int xPos = (newWidth / 2);
        int yPos = (newHeight / 2);
        canvas.drawText("Hello", xPos, yPos, paint);

if anyone finds any problem please ket me know

Center text in table cell

How about simply (Please note, come up with a better name for the class name this is simply an example):

.centerText{
   text-align: center;
}


<div>
   <table style="width:100%">
   <tbody>
   <tr>
      <td class="centerText">Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td class="centerText">Cell 3</td>
      <td>Cell 4</td>
    </tr>
    </tbody>
    </table>
</div>

Example here

You can place the css in a separate file, which is recommended. In my example, I created a file called styles.css and placed my css rules in it. Then include it in the html document in the <head> section as follows:

<head>
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>

The alternative, not creating a seperate css file, not recommended at all... Create <style> block in your <head> in the html document. Then just place your rules there.

<head>
 <style type="text/css">
   .centerText{
       text-align: center;
    }
 </style>
</head>

How to not wrap contents of a div?

If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width CSS property.

You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:

<div id="container" style="float: left">
  <div id="spacer" style="height: 1px; width: 300px"></div>
  <button>Button 1 text</button>
  <button>Button 2 text</button>
</div>

log4net hierarchy and logging levels

Try like this, it worked for me

<root>
  <!--<level value="ALL" />-->
  <level value="ERROR" />
  <level value="INFO" />
  <level value="WARN" />     
</root>

This logs 3 types of errors - error, info, and warning

Parsing domain from a URL

$domain = parse_url($url, PHP_URL_HOST);
echo implode('.', array_slice(explode('.', $domain), -2, 2))

How do I break a string in YAML over multiple lines?

You might not believe it, but YAML can do multi-line keys too:

?
 >
 multi
 line
 key
:
  value

Does Eclipse have line-wrap

Update 2016

As mentioned by ralfstx's answer, Eclipse 4.6 M4 Neon (or more) has a word-wrap feature!
(Nov 2015, for release mid 2016). In any editor view, type:

Alt+Shift+Y

https://www.eclipse.org/eclipse/news/4.6/M4/images/word-wrap.png

(Sadik confirms in the comments it works with Eclipse 2019-09)

By default, text editors are opened with word wrap disabled.
This can be changed with the Enable word wrap when opening an editor option on the General > Editors > Text Editors preference page.

Manually toggle word wrap by clicking in the editor window and pressing (Shift+Alt+Y).
On Mac OS X, press (Cmd-Opt-Y). [Updated May 2017]

The famous bug 35779 is finally closed by r/#/c/61972/ last November.

There are however a few new bugs:

As long as we are unable to provide acceptable editor performance for big files after toggling editor word wrap state on, we should make sure users can't set WW preference 1 always on by default and wonder why the editors are slow during resizing/zooming.

(2020) MarcGuay adds in the comments:

If you want the wrapping to be persistent/automatic, the cdhq plugin seems to still work with the 2019-03 version of Eclipse.
After installing you can turn it on via Window->Preferences->Word Wrap.


Update 2014

The de.cdhq.eclipse.wordwrap Word-Wrap Eclipse plug-in just got updated, and does provide good wrapping, as illustrated in the project page:

http://dev.cdhq.de/eclipse/word-wrap/img/01_wrappingOff.gifhttp://dev.cdhq.de/eclipse/word-wrap/img/02_wrappingOn_full.gif


Original answer May 2010

Try the Eclipse Word-Wrap Plug-In here.

Just for the record, while Eclipse Colorer might bring wrapping for xml files, Eclipse has not in general a soft wrapping feature for Text editor.

Soft and hard. Soft will just warp the text at the right window border without adding new line numbers (so there are gaps in the list of numbers when you enable them).

This is one of the most upvoted bugs in Eclipse history: bug 35779 (9 years and counting, 200+ votes)

Update February 2013:

That bug references an old Word wrap plugin, but Oak mentions in his answer (upvoted) a new plugin for recent (Juno+) versions of Eclipse (so 3.8.x, 4.x, may have been seen working with 3.7)
That plugin is from Florian Weßling, who just updated it (March 2013)

Right click in an opened file and select "Toggle Word Wrap" (shortcut ctrl+alt+e)

before
words wrapped

Render HTML in React Native

i uses Js function replace simply.

<Text>{item.excerpt.rendered.replace(/<\/?[^>]+(>|$)/g, "")}</Text>

Why can a function modify some arguments as perceived by the caller, but not others?

It´s because a list is a mutable object. You´re not setting x to the value of [0,1,2,3], you´re defining a label to the object [0,1,2,3].

You should declare your function f() like this:

def f(n, x=None):
    if x is None:
        x = []
    ...

How do I move a file from one location to another in Java?

You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:

  1. read the source file into memory
  2. write the content to a file at the new location
  3. delete the source file

File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Well, a for or while loop differs from a do while loop. A do while executes the statements atleast once, even if the condition turns out to be false.

The for loop you specified is absolutely correct.

Although i will do all the loops for you once again.

int sum = 0;
// for loop

for (int i = 1; i<= 100; i++){
    sum = sum + i;
}
System.out.println(sum);

// while loop

sum = 0;
int j = 1;

while(j<=100){
    sum = sum + j;
    j++;
}

System.out.println(sum);

// do while loop

sum = 0;
j = 1;

do{
    sum = sum + j;
    j++;
}
while(j<=100);

System.out.println(sum);

In the last case condition j <= 100 is because, even if the condition of do while turns false, it will still execute once but that doesn't matter in this case as the condition turns true, so it continues to loop just like any other loop statement.

Convert HTML Character Back to Text Using Java Standard Library

I think the Apache Commons Lang library's StringEscapeUtils.unescapeHtml3() and unescapeHtml4() methods are what you are looking for. See https://commons.apache.org/proper/commons-text/javadocs/api-release/org/apache/commons/text/StringEscapeUtils.html.

How to show one layout on top of the other programmatically in my case?

Use a FrameLayout with two children. The two children will be overlapped. This is recommended in one of the tutorials from Android actually, it's not a hack...

Here is an example where a TextView is displayed on top of an ImageView:

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

  <ImageView  
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 

    android:scaleType="center"
    android:src="@drawable/golden_gate" />

  <TextView
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_marginBottom="20dip"
    android:layout_gravity="center_horizontal|bottom"

    android:padding="12dip"

    android:background="#AA000000"
    android:textColor="#ffffffff"

    android:text="Golden Gate" />

</FrameLayout>

Here is the result

CryptographicException 'Keyset does not exist', but only through WCF

I just reinstalled my certificate in local machine and then it is working fine

"Object doesn't support this property or method" error in IE11

This unfortunately breaks other things. Here is the fix I found on another site that seemed to work for me:

I'd say leave the X-UA-Compatible as "IE=8" and add the following code to the bottom of your master page:

<script language="javascript">
    /* IE11 Fix for SP2010 */
    if (typeof(UserAgentInfo) != 'undefined' && !window.addEventListener) 
    {
        UserAgentInfo.strBrowser=1; 
    } 
</script>

This fixes a bug in core.js which incorrectly calculates that sets UserAgentInfo.strBrowse=3 for IE11 and thus supporting addEventListener. I'm not entirely sure on the details other than that but the combination of keeping IE=8 and using this script is working for me. Fingers crossed until I find the next IE11/SharePoint "bug"!

Debugging PHP Mail() and/or PHPMailer

It looks like the class.phpmailer.php file is corrupt. I would download the latest version and try again.

I've always used phpMailer's SMTP feature:

$mail->IsSMTP();
$mail->Host = "localhost";

And if you need debug info:

$mail->SMTPDebug  = 2; // enables SMTP debug information (for testing)
                       // 1 = errors and messages
                       // 2 = messages only

Why am I getting "Cannot Connect to Server - A network-related or instance-specific error"?

I resolved this problem by setting the project that makes use of Entity Framework as the start-up project and then run the "update-database" command.

How to call a method with a separate thread in Java?

Create a class that implements the Runnable interface. Put the code you want to run in the run() method - that's the method that you must write to comply to the Runnable interface. In your "main" thread, create a new Thread class, passing the constructor an instance of your Runnable, then call start() on it. start tells the JVM to do the magic to create a new thread, and then call your run method in that new thread.

public class MyRunnable implements Runnable {

    private int var;

    public MyRunnable(int var) {
        this.var = var;
    }

    public void run() {
        // code in the other thread, can reference "var" variable
    }
}

public class MainThreadClass {
    public static void main(String args[]) {
        MyRunnable myRunnable = new MyRunnable(10);
        Thread t = new Thread(myRunnable)
        t.start();
    }    
}

Take a look at Java's concurrency tutorial to get started.

If your method is going to be called frequently, then it may not be worth creating a new thread each time, as this is an expensive operation. It would probably be best to use a thread pool of some sort. Have a look at Future, Callable, Executor classes in the java.util.concurrent package.

How to determine whether a given Linux is 32 bit or 64 bit?

In Bash, using integer overflow:

if ((1 == 1<<32)); then
  echo 32bits
else
  echo 64bits
fi

It's much more efficient than invoking another process or opening files.

Where to change the value of lower_case_table_names=2 on windows xampp

If you have the file my-default.ini rename it to my.ini

Check if a row exists, otherwise insert

i'm writing my solution. my method doesn't stand 'if' or 'merge'. my method is easy.

INSERT INTO TableName (col1,col2)
SELECT @par1, @par2
   WHERE NOT EXISTS (SELECT col1,col2 FROM TableName
                     WHERE col1=@par1 AND col2=@par2)

For Example:

INSERT INTO Members (username)
SELECT 'Cem'
   WHERE NOT EXISTS (SELECT username FROM Members
                     WHERE username='Cem')

Explanation:

(1) SELECT col1,col2 FROM TableName WHERE col1=@par1 AND col2=@par2 It selects from TableName searched values

(2) SELECT @par1, @par2 WHERE NOT EXISTS It takes if not exists from (1) subquery

(3) Inserts into TableName (2) step values

How do I return a proper success/error message for JQuery .ajax() using PHP?

You need to provide the right content type if you're using JSON dataType. Before echo-ing the json, put the correct header.

<?php    
    header('Content-type: application/json');
    echo json_encode($response_array);
?>

Additional fix, you should check whether the query succeed or not.

if(mysql_query($query)){
    $response_array['status'] = 'success';  
}else {
    $response_array['status'] = 'error';  
}

On the client side:

success: function(data) {
    if(data.status == 'success'){
        alert("Thank you for subscribing!");
    }else if(data.status == 'error'){
        alert("Error on query!");
    }
},

Hope it helps.

Limiting the number of characters per line with CSS

That's not possible with CSS, you will have to use the Javascript for that. Although you can set the width of the p to as much as 30 characters and next letters will automatically come down but again this won't be that accurate and will vary if the characters are in capital.

jquery datatables default sort

There are a couple of options:

  1. Just after initialising DataTables, remove the sorting classes on the TD element in the TBODY.

  2. Disable the sorting classes using http://datatables.net/ref#bSortClasses . Problem with this is that it will disable the sort classes for user sort requests - which might or might not be what you want.

  3. Have your server output the table in your required sort order, and don't apply a default sort on the table (aaSorting:[]).

Generate list of all possible permutations of a string

permute (ABC) -> A.perm(BC) -> A.perm[B.perm(C)] -> A.perm[(*BC), (CB*)] -> [(*ABC), (BAC), (BCA*), (*ACB), (CAB), (CBA*)] To remove duplicates when inserting each alphabet check to see if previous string ends with the same alphabet (why? -exercise)

public static void main(String[] args) {

    for (String str : permStr("ABBB")){
        System.out.println(str);
    }
}

static Vector<String> permStr(String str){

    if (str.length() == 1){
        Vector<String> ret = new Vector<String>();
        ret.add(str);
        return ret;
    }

    char start = str.charAt(0);
    Vector<String> endStrs = permStr(str.substring(1));
    Vector<String> newEndStrs = new Vector<String>();
    for (String endStr : endStrs){
        for (int j = 0; j <= endStr.length(); j++){
            if (endStr.substring(0, j).endsWith(String.valueOf(start)))
                break;
            newEndStrs.add(endStr.substring(0, j) + String.valueOf(start) + endStr.substring(j));
        }
    }
    return newEndStrs;
}

Prints all permutations sans duplicates

Is it possible to set UIView border properties from interface builder?

while this might set the properties, it doesnt actually reflect in IB. So if you're essentially writing code in IB, you might as well then do it in your source code

changing visibility using javascript

function loadpage (page_request, containerid)
{
  var loading = document.getElementById ( "loading" ) ;

  // when connecting to server
  if ( page_request.readyState == 1 )
      loading.style.visibility = "visible" ;

  // when loaded successfully
  if (page_request.readyState == 4 && (page_request.status==200 || window.location.href.indexOf("http")==-1))
  {
      document.getElementById(containerid).innerHTML=page_request.responseText ;
      loading.style.visibility = "hidden" ;
  }
}

python: order a list of numbers without built-in sort, min, max function

Here is something that i have been trying.(Insertion sort- not the best way to sort but does the work)

def sort(list):
    for index in range(1,len(list)):
        value = list[index]
        i = index-1
        while i>=0:
            if value < list[i]:
                list[i+1] = list[i]
                list[i] = value
                i -= 1
            else:
                break

setImmediate vs. nextTick

I think I can illustrate this quite nicely. Since nextTick is called at the end of the current operation, calling it recursively can end up blocking the event loop from continuing. setImmediate solves this by firing in the check phase of the event loop, allowing event loop to continue normally.

   +-----------------------+
+->¦        timers         ¦
¦  +-----------------------+
¦  +-----------------------+
¦  ¦     I/O callbacks     ¦
¦  +-----------------------+
¦  +-----------------------+
¦  ¦     idle, prepare     ¦
¦  +-----------------------+      +---------------+
¦  +-----------------------+      ¦   incoming:   ¦
¦  ¦         poll          ¦<-----¦  connections, ¦
¦  +-----------------------+      ¦   data, etc.  ¦
¦  +-----------------------+      +---------------+
¦  ¦        check          ¦
¦  +-----------------------+
¦  +-----------------------+
+--¦    close callbacks    ¦
   +-----------------------+

source: https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/

Notice that the check phase is immediately after the poll phase. This is because the poll phase and I/O callbacks are the most likely places your calls to setImmediate are going to run. So ideally most of those calls will actually be pretty immediate, just not as immediate as nextTick which is checked after every operation and technically exists outside of the event loop.

Let's take a look at a little example of the difference between setImmediate and process.nextTick:

function step(iteration) {
  if (iteration === 10) return;
  setImmediate(() => {
    console.log(`setImmediate iteration: ${iteration}`);
    step(iteration + 1); // Recursive call from setImmediate handler.
  });
  process.nextTick(() => {
    console.log(`nextTick iteration: ${iteration}`);
  });
}
step(0);

Let's say we just ran this program and are stepping through the first iteration of the event loop. It will call into the step function with iteration zero. It will then register two handlers, one for setImmediate and one for process.nextTick. We then recursively call this function from the setImmediate handler which will run in the next check phase. The nextTick handler will run at the end of the current operation interrupting the event loop, so even though it was registered second it will actually run first.

The order ends up being: nextTick fires as current operation ends, next event loop begins, normal event loop phases execute, setImmediate fires and recursively calls our step function to start the process all over again. Current operation ends, nextTick fires, etc.

The output of the above code would be:

nextTick iteration: 0
setImmediate iteration: 0
nextTick iteration: 1
setImmediate iteration: 1
nextTick iteration: 2
setImmediate iteration: 2
nextTick iteration: 3
setImmediate iteration: 3
nextTick iteration: 4
setImmediate iteration: 4
nextTick iteration: 5
setImmediate iteration: 5
nextTick iteration: 6
setImmediate iteration: 6
nextTick iteration: 7
setImmediate iteration: 7
nextTick iteration: 8
setImmediate iteration: 8
nextTick iteration: 9
setImmediate iteration: 9

Now let's move our recursive call to step into our nextTick handler instead of the setImmediate.

function step(iteration) {
  if (iteration === 10) return;
  setImmediate(() => {
    console.log(`setImmediate iteration: ${iteration}`);
  });
  process.nextTick(() => {
    console.log(`nextTick iteration: ${iteration}`);
    step(iteration + 1); // Recursive call from nextTick handler.
  });
}
step(0);

Now that we have moved the recursive call to step into the nextTick handler things will behave in a different order. Our first iteration of the event loop runs and calls step registering a setImmedaite handler as well as a nextTick handler. After the current operation ends our nextTick handler fires which recursively calls step and registers another setImmediate handler as well as another nextTick handler. Since a nextTick handler fires after the current operation, registering a nextTick handler within a nextTick handler will cause the second handler to run immediately after the current handler operation finishes. The nextTick handlers will keep firing, preventing the current event loop from ever continuing. We will get through all our nextTick handlers before we see a single setImmediate handler fire.

The output of the above code ends up being:

nextTick iteration: 0
nextTick iteration: 1
nextTick iteration: 2
nextTick iteration: 3
nextTick iteration: 4
nextTick iteration: 5
nextTick iteration: 6
nextTick iteration: 7
nextTick iteration: 8
nextTick iteration: 9
setImmediate iteration: 0
setImmediate iteration: 1
setImmediate iteration: 2
setImmediate iteration: 3
setImmediate iteration: 4
setImmediate iteration: 5
setImmediate iteration: 6
setImmediate iteration: 7
setImmediate iteration: 8
setImmediate iteration: 9

Note that had we not interrupted the recursive call and aborted it after 10 iterations then the nextTick calls would keep recursing and never letting the event loop continue to the next phase. This is how nextTick can become blocking when used recursively whereas setImmediate will fire in the next event loop and setting another setImmediate handler from within one won't interrupt the current event loop at all, allowing it to continue executing phases of the event loop as normal.

Hope that helps!

PS - I agree with other commenters that the names of the two functions could easily be swapped since nextTick sounds like it's going to fire in the next event loop rather than the end of the current one, and the end of the current loop is more "immediate" than the beginning of the next loop. Oh well, that's what we get as an API matures and people come to depend on existing interfaces.

Android 8: Cleartext HTTP traffic not permitted

My problem in Android 9 was navigating on a webview over domains with http The solution from this answer

<application 
    android:networkSecurityConfig="@xml/network_security_config"
    ...>

and:

res/xml/network_security_config.xml

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <certificates src="system" />
        </trust-anchors>
    </base-config>
</network-security-config>

What is the correct way to read from NetworkStream in .NET

Networking code is notoriously difficult to write, test and debug.

You often have lots of things to consider such as:

  • what "endian" will you use for the data that is exchanged (Intel x86/x64 is based on little-endian) - systems that use big-endian can still read data that is in little-endian (and vice versa), but they have to rearrange the data. When documenting your "protocol" just make it clear which one you are using.

  • are there any "settings" that have been set on the sockets which can affect how the "stream" behaves (e.g. SO_LINGER) - you might need to turn certain ones on or off if your code is very sensitive

  • how does congestion in the real world which causes delays in the stream affect your reading/writing logic

If the "message" being exchanged between a client and server (in either direction) can vary in size then often you need to use a strategy in order for that "message" to be exchanged in a reliable manner (aka Protocol).

Here are several different ways to handle the exchange:

  • have the message size encoded in a header that precedes the data - this could simply be a "number" in the first 2/4/8 bytes sent (dependent on your max message size), or could be a more exotic "header"

  • use a special "end of message" marker (sentinel), with the real data encoded/escaped if there is the possibility of real data being confused with an "end of marker"

  • use a timeout....i.e. a certain period of receiving no bytes means there is no more data for the message - however, this can be error prone with short timeouts, which can easily be hit on congested streams.

  • have a "command" and "data" channel on separate "connections"....this is the approach the FTP protocol uses (the advantage is clear separation of data from commands...at the expense of a 2nd connection)

Each approach has its pros and cons for "correctness".

The code below uses the "timeout" method, as that seems to be the one you want.

See http://msdn.microsoft.com/en-us/library/bk6w7hs8.aspx. You can get access to the NetworkStream on the TCPClient so you can change the ReadTimeout.

string SendCmd(string cmd, string ip, int port)
{
  var client = new TcpClient(ip, port);
  var data = Encoding.GetEncoding(1252).GetBytes(cmd);
  var stm = client.GetStream();
  // Set a 250 millisecond timeout for reading (instead of Infinite the default)
  stm.ReadTimeout = 250;
  stm.Write(data, 0, data.Length);
  byte[] resp = new byte[2048];
  var memStream = new MemoryStream();
  int bytesread = stm.Read(resp, 0, resp.Length);
  while (bytesread > 0)
  {
      memStream.Write(resp, 0, bytesread);
      bytesread = stm.Read(resp, 0, resp.Length);
  }
  return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}

As a footnote for other variations on this writing network code...when doing a Read where you want to avoid a "block", you can check the DataAvailable flag and then ONLY read what is in the buffer checking the .Length property e.g. stm.Read(resp, 0, stm.Length);

When to use 'raise NotImplementedError'?

As the documentation states [docs],

In user defined base classes, abstract methods should raise this exception when they require derived classes to override the method, or while the class is being developed to indicate that the real implementation still needs to be added.

Note that although the main stated use case this error is the indication of abstract methods that should be implemented on inherited classes, you can use it anyhow you'd like, like for indication of a TODO marker.

jQuery Refresh/Reload Page if Ajax Success after time

if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}

GUI-based or Web-based JSON editor that works like property explorer

Generally when I want to create a JSON or YAML string, I start out by building the Perl data structure, and then running a simple conversion on it. You could put a UI in front of the Perl data structure generation, e.g. a web form.

Converting a structure to JSON is very straightforward:

use strict;
use warnings;
use JSON::Any;

my $data = { arbitrary structure in here };
my $json_handler = JSON::Any->new(utf8=>1);
my $json_string = $json_handler->objToJson($data);

Validating with an XML schema in Python

I am assuming you mean using XSD files. Surprisingly there aren't many python XML libraries that support this. lxml does however. Check Validation with lxml. The page also lists how to use lxml to validate with other schema types.

Android: How to set password property in an edit text?

I found when doing this that in order to set the gravity to center, and still have your password hint show when using inputType, the android:gravity="Center" must be at the end of your XML line.

<EditText android:textColor="#000000" android:id="@+id/editText2" 
    android:layout_width="fill_parent" android:hint="Password" 
    android:background="@drawable/rounded_corner" 
    android:layout_height="fill_parent" 
    android:nextFocusDown="@+id/imageButton1" 
    android:nextFocusRight="@+id/imageButton1" 
    android:nextFocusLeft="@+id/editText1"
    android:nextFocusUp="@+id/editText1" 
    android:inputType="textVisiblePassword" 
    android:textColorHint="#999999" 
    android:textSize="16dp" 
    android:gravity="center">
</EditText>

Selecting/excluding sets of columns in pandas

In a similar vein, when reading a file, one may wish to exclude columns upfront, rather than wastefully reading unwanted data into memory and later discarding them.

As of pandas 0.20.0, usecols now accepts callables.1 This update allows more flexible options for reading columns:

skipcols = [...]
read_csv(..., usecols=lambda x: x not in skipcols)

The latter pattern is essentially the inverse of the traditional usecols method - only specified columns are skipped.


Given

Data in a file

import numpy as np
import pandas as pd


df = pd.DataFrame(np.random.randn(100, 4), columns=list('ABCD'))

filename = "foo.csv"
df.to_csv(filename)

Code

skipcols = ["B", "D"]
df1 = pd.read_csv(filename, usecols=lambda x: x not in skipcols, index_col=0)
df1

Output

          A         C
0  0.062350  0.076924
1 -0.016872  1.091446
2  0.213050  1.646109
3 -1.196928  1.153497
4 -0.628839 -0.856529
...

Details

A DataFrame was written to a file. It was then read back as a separate DataFrame, now skipping unwanted columns (B and D).

Note that for the OP's situation, since data is already created, the better approach is the accepted answer, which drops unwanted columns from an extant object. However, the technique presented here is most useful when directly reading data from files into a DataFrame.

A request was raised for a "skipcols" option in this issue and was addressed in a later issue.

Connect to Active Directory via LDAP

ldapConnection is the server adres: ldap.example.com Ldap.Connection.Path is the path inside the ADS that you like to use insert in LDAP format.

OU=Your_OU,OU=other_ou,dc=example,dc=com

You start at the deepest OU working back to the root of the AD, then add dc=X for every domain section until you have everything including the top level domain

Now i miss a parameter to authenticate, this works the same as the path for the username

CN=username,OU=users,DC=example,DC=com

Introduction to LDAP

Regular expression to get a string between two strings in Javascript

The method match() searches a string for a match and returns an Array object.

// Original string
var str = "My cow always gives milk";

// Using index [0] would return<br/>
// "**cow always gives milk**"
str.match(/cow(.*)milk/)**[0]**


// Using index **[1]** would return
// "**always gives**"
str.match(/cow(.*)milk/)[1]

Is there a better way to compare dictionary values

If your dictionaries are deeply nested and if they contain different types of collections, you could convert them to json string and compare.

import json
match = (json.dumps(dict1) == json.dumps(dict2))

caveat- this solution may not work if your dictionaries have binary strings in the values as this is not json serializable

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

This sounds weird and I don't know why, but in my case that was happening because my ConnectionString was using "." in "data source" attribute. Once I changed it to "localhost" it workded like a charm. No other change was needed.

How to find if directory exists in Python

Python 3.4 introduced the pathlib module into the standard library, which provides an object oriented approach to handle filesystem paths. The is_dir() and exists() methods of a Path object can be used to answer the question:

In [1]: from pathlib import Path

In [2]: p = Path('/usr')

In [3]: p.exists()
Out[3]: True

In [4]: p.is_dir()
Out[4]: True

Paths (and strings) can be joined together with the / operator:

In [5]: q = p / 'bin' / 'vim'

In [6]: q
Out[6]: PosixPath('/usr/bin/vim') 

In [7]: q.exists()
Out[7]: True

In [8]: q.is_dir()
Out[8]: False

Pathlib is also available on Python 2.7 via the pathlib2 module on PyPi.

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

Put your prompt in the 1st option and disable it:

<selection>
    <option disabled selected>”Select a language”</option>
    <option>English</option>
    <option>Spanish</option>
</selection>

The first option will automatically be the selected default (what you see first when you look at the drop-down) but adding the selected attribute is more clear and actually needed when the first field is a disabled field.

The disabled attribute will make the option be un-selectable/grayed out.


Other answers suggest setting disabled=“disabled” but that’s only necessary if you need to parse as XHTML, which is basically a more strict version of HTML. disabled on it’s on is enough for standard HTML.


If you want to make the selection “required” (without accepting the “Select a language” option as an accepted answer):

Add the required attribute to selection and set the first option’s value to the empty string ””.

<selection required>
    <option disabled value=“”>Select a language</option>
    <option>English</option>
    <option>Spanish</option>
</selection>

Format XML string to print friendly XML string

.NET 2.0 ignoring name resolving, and with proper resource-disposal, indentation, preserve-whitespace and custom encoding:

public static string Beautify(System.Xml.XmlDocument doc)
{
    string strRetValue = null;
    System.Text.Encoding enc = System.Text.Encoding.UTF8;
    // enc = new System.Text.UTF8Encoding(false);

    System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings();
    xmlWriterSettings.Encoding = enc;
    xmlWriterSettings.Indent = true;
    xmlWriterSettings.IndentChars = "    ";
    xmlWriterSettings.NewLineChars = "\r\n";
    xmlWriterSettings.NewLineHandling = System.Xml.NewLineHandling.Replace;
    //xmlWriterSettings.OmitXmlDeclaration = true;
    xmlWriterSettings.ConformanceLevel = System.Xml.ConformanceLevel.Document;


    using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
    {
        using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(ms, xmlWriterSettings))
        {
            doc.Save(writer);
            writer.Flush();
            ms.Flush();

            writer.Close();
        } // End Using writer

        ms.Position = 0;
        using (System.IO.StreamReader sr = new System.IO.StreamReader(ms, enc))
        {
            // Extract the text from the StreamReader.
            strRetValue = sr.ReadToEnd();

            sr.Close();
        } // End Using sr

        ms.Close();
    } // End Using ms


    /*
    System.Text.StringBuilder sb = new System.Text.StringBuilder(); // Always yields UTF-16, no matter the set encoding
    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create(sb, settings))
    {
        doc.Save(writer);
        writer.Close();
    } // End Using writer
    strRetValue = sb.ToString();
    sb.Length = 0;
    sb = null;
    */

    xmlWriterSettings = null;
    return strRetValue;
} // End Function Beautify

Usage:

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
xmlDoc.XmlResolver = null;
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load("C:\Test.svg");
string SVG = Beautify(xmlDoc);

How to sort an array of integers correctly

Update! Scroll to bottom of answer for smartSort prop additive that gives even more fun!
Sorts arrays of anything!

My personal favorite form of this function allows for a param for Ascending, or Descending:

function intArraySort(c, a) {
    function d(a, b) { return b - a; }
    "string" == typeof a && a.toLowerCase();
    switch (a) {
        default: return c.sort(function(a, b) { return a - b; });
        case 1:
                case "d":
                case "dc":
                case "desc":
                return c.sort(d)
    }
};

Usage as simple as:

var ara = function getArray() {
        var a = Math.floor(Math.random()*50)+1, b = [];
        for (i=0;i<=a;i++) b.push(Math.floor(Math.random()*50)+1);
        return b;
    }();

//    Ascending
intArraySort(ara);
console.log(ara);

//    Descending
intArraySort(ara, 1);
console.log(ara);

//    Ascending
intArraySort(ara, 'a');
console.log(ara);

//    Descending
intArraySort(ara, 'dc');
console.log(ara);

//    Ascending
intArraySort(ara, 'asc');
console.log(ara);

jsFiddle


Or Code Snippet Example Here!

_x000D_
_x000D_
function intArraySort(c, a) {_x000D_
 function d(a, b) { return b - a }_x000D_
 "string" == typeof a && a.toLowerCase();_x000D_
 switch (a) {_x000D_
  default: return c.sort(function(a, b) { return a - b });_x000D_
  case 1:_x000D_
  case "d":_x000D_
  case "dc":_x000D_
  case "desc":_x000D_
  return c.sort(d)_x000D_
 }_x000D_
};_x000D_
_x000D_
function tableExample() {_x000D_
 var d = function() {_x000D_
   var a = Math.floor(50 * Math.random()) + 1,_x000D_
    b = [];_x000D_
   for (i = 0; i <= a; i++) b.push(Math.floor(50 * Math.random()) + 1);_x000D_
   return b_x000D_
  },_x000D_
  a = function(a) {_x000D_
   var b = $("<tr/>"),_x000D_
    c = $("<th/>").prependTo(b);_x000D_
   $("<td/>", {_x000D_
    text: intArraySort(d(), a).join(", ")_x000D_
   }).appendTo(b);_x000D_
   switch (a) {_x000D_
    case 1:_x000D_
    case "d":_x000D_
    case "dc":_x000D_
    case "desc":_x000D_
     c.addClass("desc").text("Descending");_x000D_
     break;_x000D_
    default:_x000D_
     c.addClass("asc").text("Ascending")_x000D_
   }_x000D_
   return b_x000D_
  };_x000D_
 return $("tbody").empty().append(a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1), a(), a(1))_x000D_
};_x000D_
_x000D_
tableExample();
_x000D_
table { border-collapse: collapse; }_x000D_
th, td { border: 1px solid; padding: .25em .5em; vertical-align: top; }_x000D_
.asc { color: red; }_x000D_
.desc { color: blue }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<table><tbody></tbody></table>
_x000D_
_x000D_
_x000D_


.smartSort('asc' | 'desc')

Now have even more fun with a sorting method that sorts an array full of multiple items! Doesn't currently cover "associative" (aka, string keys), but it does cover about every type of value! Not only will it sort the multiple values asc or desc accordingly, but it will also maintain constant "position" of "groups" of values. In other words; ints are always first, then come strings, then arrays (yes, i'm making this multidimensional!), then Objects (unfiltered, element, date), & finally undefineds and nulls!

"Why?" you ask. Why not!

Now comes in 2 flavors! The first of which requires newer browsers as it uses Object.defineProperty to add the method to the Array.protoype Object. This allows for ease of natural use, such as: myArray.smartSort('a'). If you need to implement for older browsers, or you simply don't like modifying native Objects, scroll down to Method Only version.

/* begin */
/* KEY NOTE! Requires EcmaScript 5.1 (not compatible with older browsers) */
;;(function(){if(Object.defineProperty&&!Array.prototype.smartSort){var h=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a>b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("a");b instanceof Array&&b.smartSort("a");if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("a"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("a"),a.id==e[0]?1:-1;e=[a.tagName, b.tagName].smartSort("a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("a"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d"); return a[d].tagName==c[0]?1:-1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]>g[1]},k=function(a,b){if(null== a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.smartSort("d");b instanceof Array&&b.smartSort("d");if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=e.concat(g).smartSort("a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=[a[c],b[c]].smartSort("d"),a[c]==d[0]?-1:1;var f=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=[a.id,b.id].smartSort("d"),a.id==e[0]?-1:1;e=[a.tagName,b.tagName].smartSort("d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);e.concat(g).smartSort("a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=[a[d].id,b[f].id].smartSort("d"),a[d].id==c[0]?-1:1;c=[a[d].tagName,b[f].tagName].smartSort("d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=[a[d],b[f]].smartSort("d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1;if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=[a[Object.keys(a)[0]],b[Object.keys(b)[0]]].smartSort("d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]};Object.defineProperty(Array.prototype,"smartSort",{value:function(){return arguments&& (!arguments.length||1==arguments.length&&/^a([sc]{2})?$|^d([esc]{3})?$/i.test(arguments[0]))?this.sort(!arguments.length||/^a([sc]{2})?$/i.test(arguments[0])?h:k):this.sort()}})}})();
/* end */

jsFiddle Array.prototype.smartSort('asc|desc')


Use is simple! First make some crazy array like:

window.z = [ 'one', undefined, $('<span />'), 'two', null, 2, $('<div />', { id: 'Thing' }), $('<div />'), 4, $('<header />') ];
z.push(new Date('1/01/2011'));
z.push('three');
z.push(undefined);
z.push([ 'one', 'three', 'four' ]);
z.push([ 'one', 'three', 'five' ]);
z.push({ a: 'a', b: 'b' });
z.push({ name: 'bob', value: 'bill' });
z.push(new Date());
z.push({ john: 'jill', jack: 'june' });
z.push([ 'abc', 'def', [ 'abc', 'def', 'cba' ], [ 'cba', 'def', 'bca' ], 'cba' ]);
z.push([ 'cba', 'def', 'bca' ]);
z.push({ a: 'a', b: 'b', c: 'c' });
z.push({ a: 'a', b: 'b', c: 'd' });

Then simply sort it!

z.smartSort('asc'); // Ascending
z.smartSort('desc'); // Descending

Method Only

Same as the preceding, except as just a simple method!

/* begin */
/* KEY NOTE! Method `smartSort` is appended to native `window` for global use. If you'd prefer a more local scope, simple change `window.smartSort` to `var smartSort` and place inside your class/method */
window.smartSort=function(){if(arguments){var a,b,c;for(c in arguments)arguments[c]instanceof Array&&(a=arguments[c],void 0==b&&(b="a")),"string"==typeof arguments[c]&&(b=/^a([sc]{2})?$/i.test(arguments[c])?"a":"d");if(a instanceof Array)return a.sort("a"==b?smartSort.asc:smartSort.desc)}return this.sort()};smartSort.asc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return a-b;if(/^stringstring$/ig.test(e))return a> b;if(/(string|number){2}/ig.test(e))return/string/i.test(c)?1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.asc);b instanceof Array&&b.sort(smartSort.asc);if(a instanceof Date&&b instanceof Date)return a-b;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c], b[c]],"a"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"a"),a.id==e[0]?1:-1;e=smartSort([a.tagName,b.tagName],"a");return a.tagName==e[0]?1:-1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g), "a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&&b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"a"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"a");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"a"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1; if(b.hasOwnProperty(f)&&b[f]instanceof Element||!a.hasOwnProperty(d))return-1;if(!b.hasOwnProperty(d))return 1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"a");return a[Object.keys(a)[0]]==c[0]?1:-1}g=[a,b].sort();return g[0]>g[1]};smartSort.desc=function(a,b){if(null==a||void 0==a)return 1;if(null==b||void 0==b)return-1;var c=typeof a,e=c+typeof b;if(/^numbernumber$/ig.test(e))return b-a;if(/^stringstring$/ig.test(e))return b>a;if(/(string|number){2}/ig.test(e))return/string/i.test(c)? 1:-1;if(/number/ig.test(e)&&/object/ig.test(e)||/string/ig.test(e)&&/object/ig.test(e))return/object/i.test(c)?1:-1;if(/^objectobject$/ig.test(e)){a instanceof Array&&a.sort(smartSort.desc);b instanceof Array&&b.sort(smartSort.desc);if(a instanceof Date&&b instanceof Date)return b-a;if(a instanceof Array&&b instanceof Array){var e=Object.keys(a),g=Object.keys(b),e=smartSort(e.concat(g),"a"),d;for(d in e)if(c=e[d],a[c]!=b[c])return d=smartSort([a[c],b[c]],"d"),a[c]==d[0]?-1:1;var f=smartSort([a[Object.keys(a)[0]], b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==f[0]?-1:1}if(a instanceof Element&&b instanceof Element){if(a.tagName==b.tagName)return e=smartSort([a.id,b.id],"d"),a.id==e[0]?-1:1;e=smartSort([a.tagName,b.tagName],"d");return a.tagName==e[0]?-1:1}if(a instanceof Date||b instanceof Date)return a instanceof Date?1:-1;if(a instanceof Array||b instanceof Array)return a instanceof Array?-1:1;e=Object.keys(a);g=Object.keys(b);smartSort(e.concat(g),"a");for(c=0;20>c;c++){d=e[c];f=g[c];if(a.hasOwnProperty(d)&& b.hasOwnProperty(f)){if(a[d]instanceof Element&&b[f]instanceof Element){if(a[d].tagName==b[f].tagName)return c=smartSort([a[d].id,b[f].id],"d"),a[d].id==c[0]?-1:1;c=smartSort([a[d].tagName,b[f].tagName],"d");return a[d].tagName==c[0]?-1:1}if(a[d]instanceof Element||b[f]instanceof Element)return a[d]instanceof Element?1:-1;if(a[d]!=b[f])return c=smartSort([a[d],b[f]],"d"),a[d]==c[0]?-1:1}if(a.hasOwnProperty(d)&&a[d]instanceof Element)return 1;if(b.hasOwnProperty(f)&&b[f]instanceof Element)return-1; if(!a.hasOwnProperty(d))return 1;if(!b.hasOwnProperty(d))return-1}c=smartSort([a[Object.keys(a)[0]],b[Object.keys(b)[0]]],"d");return a[Object.keys(a)[0]]==c[0]?-1:1}g=[a,b].sort();return g[0]<g[1]}
/* end */

Use:

z = smartSort(z, 'asc'); // Ascending
z = smartSort(z, 'desc'); // Descending

jsFiddle Method smartSort(Array, "asc|desc")

How can I print out just the index of a pandas dataframe?

You can access the index attribute of a df using .index:

In [277]:

df = pd.DataFrame({'a':np.arange(10), 'b':np.random.randn(10)})
df
Out[277]:
   a         b
0  0  0.293422
1  1 -1.631018
2  2  0.065344
3  3 -0.417926
4  4  1.925325
5  5  0.167545
6  6 -0.988941
7  7 -0.277446
8  8  1.426912
9  9 -0.114189
In [278]:

df.index
Out[278]:
Int64Index([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype='int64')

Adding multiple columns AFTER a specific column in MySQL

I have done this code in case anyone faced my problem of adding lots of fields fast using MySQl code hope it helps , u can run this code on any online php compiler as well if u are too busy!

$fields = array(

        'col_one' ,
        'col_two' ,
        'col_three'

    );

    $startF = 'after_col';
    $table = 'table_name';

    $output = 'ALTER TABLE ' .$table.'<br>';
    for($i=0 ; $i<count($fields) ; $i++){
        if($i==0){
            $output.= 'ADD COLUMN '.$fields[$i].' VARCHAR(15) AFTER '.$startF.',' . '<br>';

        }else{
            $output.= 'ADD COLUMN '.$fields[$i].' VARCHAR(15) AFTER '.$fields[$i-1].',' . '<br>';

        }
    }

// extra fields without the array

    $output.= 'ADD COLUMN col_four VARCHAR(255) AFTER any_col_u_want,  '. '<br>';
    $output.= 'ADD COLUMN col_five VARCHAR(255) AFTER col_four,  '. '<br>';
    $output.= 'ADD COLUMN col_six VARCHAR(255) AFTER col_five'. '<br>';



    echo $output;

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

What are the -Xms and -Xmx parameters when starting JVM?

-Xms initial heap size for the startup, however, during the working process the heap size can be less than -Xms due to users' inactivity or GC iterations. This is not a minimal required heap size.

-Xmx maximal heap size

LaTeX package for syntax highlighting of code in various languages

I recommend Pygments. It accepts a piece of code in any language and outputs syntax highlighted LaTeX code. It uses fancyvrb and color packages to produce its output. I personally prefer it to the listing package. I think fancyvrb creates much prettier results.

ssh: The authenticity of host 'hostname' can't be established

Add these to your /etc/ssh/ssh_config

Host *
UserKnownHostsFile=/dev/null
StrictHostKeyChecking=no

Nested routes with react router v4 / v5

A complete answer for React Router v6 or version 6 just in case needed.

import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";

/*Routes is used to be Switch*/
const Router = () => {

  return (
    <Routes>
      <Route path="/" element={<LandingPage />} />
      <Route path="games" element={<Games />} />
      <Route path="game-details/:id" element={<GameDetails />} />
      <Route path="dashboard" element={<Dashboard />}>
        <Route path="/" element={<DashboardDefaultContent />} />
        <Route path="inbox" element={<Inbox />} />
        <Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
        <Route path="*" element={<NotFound />} />
      </Route>
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";

const Dashboard = () => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      <Outlet />
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-6-demo

How to switch text case in visual studio code

Now an uppercase and lowercase switch can be done simultaneously in the selected strings via a regular expression replacement (regex, CtrlH + AltR), according to v1.47.3 June 2020 release:

Replacing different text cases in one selection

This is done through 4 "Single character" character classes (Perl documentation), namely, for the matched group following it:

  • \l <=> [[:lower:]]: first character becomes lowercase
  • \u <=> [[:upper:]]: first character becomes uppercase
  • \L <=> [^[:lower:]]: all characters become lowercase
  • \U <=> [^[:upper:]]: all characters become uppercase

$0 matches all selected groups, while $1 matches the 1st group, $2 the 2nd one, etc.

Hit the Match Case button at the left of the search bar (or AltC) and, borrowing some examples from an old Sublime Text answer, now this is possible:

  1. Capitalize words
  • Find: (\s)([a-z]) (\s matches spaces and new lines, i.e. " venuS" => " VenuS")
  • Replace: $1\u$2
  1. Uncapitalize words
  • Find: (\s)([A-Z])
  • Replace: $1\l$2
  1. Remove a single camel case (e.g. cAmelCAse => camelcAse => camelcase)
  • Find: ([a-z])([A-Z])
  • Replace: $1\l$2
  1. Lowercase all from an uppercase letter within words (e.g. LowerCASe => Lowercase)
  • Find: (\w)([A-Z]+)
  • Replace: $1\L$2
  • Alternate Replace: \L$0
  1. Uppercase all from a lowercase letter within words (e.g. upperCASe => uPPERCASE)
  • Find: (\w)([A-Z]+)
  • Replace: $1\U$2
  1. Uppercase previous (e.g. upperCase => UPPERCase)
  • Find: (\w+)([A-Z])
  • Replace: \U$1$2
  1. Lowercase previous (e.g. LOWERCase => lowerCase)
  • Find: (\w+)([A-Z])
  • Replace: \L$1$2
  1. Uppercase the rest (e.g. upperCase => upperCASE)
  • Find: ([A-Z])(\w+)
  • Replace: $1\U$2
  1. Lowercase the rest (e.g. lOWERCASE => lOwercase)
  • Find: ([A-Z])(\w+)
  • Replace: $1\L$2
  1. Shift-right-uppercase (e.g. Case => cAse => caSe => casE)
  • Find: ([a-z\s])([A-Z])(\w)
  • Replace: $1\l$2\u$3
  1. Shift-left-uppercase (e.g. CasE => CaSe => CAse => Case)
  • Find: (\w)([A-Z])([a-z\s])
  • Replace: \u$1\l$2$3

Correct way to delete cookies server-side

Use Max-Age=-1 rather than "Expires". It is shorter, less picky about the syntax, and Max-Age takes precedence over Expires anyway.

Sorting table rows according to table header column using javascript or jquery

I think this might help you:
Here is the JSFiddle demo:

And here is the code:

_x000D_
_x000D_
var stIsIE = /*@cc_on!@*/ false;_x000D_
sorttable = {_x000D_
  init: function() {_x000D_
    if (arguments.callee.done) return;_x000D_
    arguments.callee.done = true;_x000D_
    if (_timer) clearInterval(_timer);_x000D_
    if (!document.createElement || !document.getElementsByTagName) return;_x000D_
    sorttable.DATE_RE = /^(\d\d?)[\/\.-](\d\d?)[\/\.-]((\d\d)?\d\d)$/;_x000D_
    forEach(document.getElementsByTagName('table'), function(table) {_x000D_
      if (table.className.search(/\bsortable\b/) != -1) {_x000D_
        sorttable.makeSortable(table);_x000D_
      }_x000D_
    });_x000D_
  },_x000D_
  makeSortable: function(table) {_x000D_
    if (table.getElementsByTagName('thead').length == 0) {_x000D_
      the = document.createElement('thead');_x000D_
      the.appendChild(table.rows[0]);_x000D_
      table.insertBefore(the, table.firstChild);_x000D_
    }_x000D_
    if (table.tHead == null) table.tHead = table.getElementsByTagName('thead')[0];_x000D_
    if (table.tHead.rows.length != 1) return;_x000D_
    sortbottomrows = [];_x000D_
    for (var i = 0; i < table.rows.length; i++) {_x000D_
      if (table.rows[i].className.search(/\bsortbottom\b/) != -1) {_x000D_
        sortbottomrows[sortbottomrows.length] = table.rows[i];_x000D_
      }_x000D_
    }_x000D_
    if (sortbottomrows) {_x000D_
      if (table.tFoot == null) {_x000D_
        tfo = document.createElement('tfoot');_x000D_
        table.appendChild(tfo);_x000D_
      }_x000D_
      for (var i = 0; i < sortbottomrows.length; i++) {_x000D_
        tfo.appendChild(sortbottomrows[i]);_x000D_
      }_x000D_
      delete sortbottomrows;_x000D_
    }_x000D_
    headrow = table.tHead.rows[0].cells;_x000D_
    for (var i = 0; i < headrow.length; i++) {_x000D_
      if (!headrow[i].className.match(/\bsorttable_nosort\b/)) {_x000D_
        mtch = headrow[i].className.match(/\bsorttable_([a-z0-9]+)\b/);_x000D_
        if (mtch) {_x000D_
          override = mtch[1];_x000D_
        }_x000D_
        if (mtch && typeof sorttable["sort_" + override] == 'function') {_x000D_
          headrow[i].sorttable_sortfunction = sorttable["sort_" + override];_x000D_
        } else {_x000D_
          headrow[i].sorttable_sortfunction = sorttable.guessType(table, i);_x000D_
        }_x000D_
        headrow[i].sorttable_columnindex = i;_x000D_
        headrow[i].sorttable_tbody = table.tBodies[0];_x000D_
        dean_addEvent(headrow[i], "click", sorttable.innerSortFunction = function(e) {_x000D_
_x000D_
          if (this.className.search(/\bsorttable_sorted\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted',_x000D_
              'sorttable_sorted_reverse');_x000D_
            this.removeChild(document.getElementById('sorttable_sortfwdind'));_x000D_
            sortrevind = document.createElement('span');_x000D_
            sortrevind.id = "sorttable_sortrevind";_x000D_
            sortrevind.innerHTML = stIsIE ? '&nbsp<font face="webdings">5</font>' : '&nbsp;&#x25B4;';_x000D_
            this.appendChild(sortrevind);_x000D_
            return;_x000D_
          }_x000D_
          if (this.className.search(/\bsorttable_sorted_reverse\b/) != -1) {_x000D_
            sorttable.reverse(this.sorttable_tbody);_x000D_
            this.className = this.className.replace('sorttable_sorted_reverse',_x000D_
              'sorttable_sorted');_x000D_
            this.removeChild(document.getElementById('sorttable_sortrevind'));_x000D_
            sortfwdind = document.createElement('span');_x000D_
            sortfwdind.id = "sorttable_sortfwdind";_x000D_
            sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
            this.appendChild(sortfwdind);_x000D_
            return;_x000D_
          }_x000D_
          theadrow = this.parentNode;_x000D_
          forEach(theadrow.childNodes, function(cell) {_x000D_
            if (cell.nodeType == 1) {_x000D_
              cell.className = cell.className.replace('sorttable_sorted_reverse', '');_x000D_
              cell.className = cell.className.replace('sorttable_sorted', '');_x000D_
            }_x000D_
          });_x000D_
          sortfwdind = document.getElementById('sorttable_sortfwdind');_x000D_
          if (sortfwdind) {_x000D_
            sortfwdind.parentNode.removeChild(sortfwdind);_x000D_
          }_x000D_
          sortrevind = document.getElementById('sorttable_sortrevind');_x000D_
          if (sortrevind) {_x000D_
            sortrevind.parentNode.removeChild(sortrevind);_x000D_
          }_x000D_
_x000D_
          this.className += ' sorttable_sorted';_x000D_
          sortfwdind = document.createElement('span');_x000D_
          sortfwdind.id = "sorttable_sortfwdind";_x000D_
          sortfwdind.innerHTML = stIsIE ? '&nbsp<font face="webdings">6</font>' : '&nbsp;&#x25BE;';_x000D_
          this.appendChild(sortfwdind);_x000D_
          row_array = [];_x000D_
          col = this.sorttable_columnindex;_x000D_
          rows = this.sorttable_tbody.rows;_x000D_
          for (var j = 0; j < rows.length; j++) {_x000D_
            row_array[row_array.length] = [sorttable.getInnerText(rows[j].cells[col]), rows[j]];_x000D_
          }_x000D_
          row_array.sort(this.sorttable_sortfunction);_x000D_
          tb = this.sorttable_tbody;_x000D_
          for (var j = 0; j < row_array.length; j++) {_x000D_
            tb.appendChild(row_array[j][1]);_x000D_
          }_x000D_
          delete row_array;_x000D_
        });_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
_x000D_
  guessType: function(table, column) {_x000D_
    sortfn = sorttable.sort_alpha;_x000D_
    for (var i = 0; i < table.tBodies[0].rows.length; i++) {_x000D_
      text = sorttable.getInnerText(table.tBodies[0].rows[i].cells[column]);_x000D_
      if (text != '') {_x000D_
        if (text.match(/^-?[£$¤]?[\d,.]+%?$/)) {_x000D_
          return sorttable.sort_numeric;_x000D_
        }_x000D_
        possdate = text.match(sorttable.DATE_RE)_x000D_
        if (possdate) {_x000D_
          first = parseInt(possdate[1]);_x000D_
          second = parseInt(possdate[2]);_x000D_
          if (first > 12) {_x000D_
            return sorttable.sort_ddmm;_x000D_
          } else if (second > 12) {_x000D_
            return sorttable.sort_mmdd;_x000D_
          } else {_x000D_
            sortfn = sorttable.sort_ddmm;_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
    }_x000D_
    return sortfn;_x000D_
  },_x000D_
  getInnerText: function(node) {_x000D_
    if (!node) return "";_x000D_
    hasInputs = (typeof node.getElementsByTagName == 'function') &&_x000D_
      node.getElementsByTagName('input').length;_x000D_
    if (node.getAttribute("sorttable_customkey") != null) {_x000D_
      return node.getAttribute("sorttable_customkey");_x000D_
    } else if (typeof node.textContent != 'undefined' && !hasInputs) {_x000D_
      return node.textContent.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.innerText != 'undefined' && !hasInputs) {_x000D_
      return node.innerText.replace(/^\s+|\s+$/g, '');_x000D_
    } else if (typeof node.text != 'undefined' && !hasInputs) {_x000D_
      return node.text.replace(/^\s+|\s+$/g, '');_x000D_
    } else {_x000D_
      switch (node.nodeType) {_x000D_
        case 3:_x000D_
          if (node.nodeName.toLowerCase() == 'input') {_x000D_
            return node.value.replace(/^\s+|\s+$/g, '');_x000D_
          }_x000D_
        case 4:_x000D_
          return node.nodeValue.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        case 1:_x000D_
        case 11:_x000D_
          var innerText = '';_x000D_
          for (var i = 0; i < node.childNodes.length; i++) {_x000D_
            innerText += sorttable.getInnerText(node.childNodes[i]);_x000D_
          }_x000D_
          return innerText.replace(/^\s+|\s+$/g, '');_x000D_
          break;_x000D_
        default:_x000D_
          return '';_x000D_
      }_x000D_
    }_x000D_
  },_x000D_
  reverse: function(tbody) {_x000D_
    // reverse the rows in a tbody_x000D_
    newrows = [];_x000D_
    for (var i = 0; i < tbody.rows.length; i++) {_x000D_
      newrows[newrows.length] = tbody.rows[i];_x000D_
    }_x000D_
    for (var i = newrows.length - 1; i >= 0; i--) {_x000D_
      tbody.appendChild(newrows[i]);_x000D_
    }_x000D_
    delete newrows;_x000D_
  },_x000D_
  sort_numeric: function(a, b) {_x000D_
    aa = parseFloat(a[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(aa)) aa = 0;_x000D_
    bb = parseFloat(b[0].replace(/[^0-9.-]/g, ''));_x000D_
    if (isNaN(bb)) bb = 0;_x000D_
    return aa - bb;_x000D_
  },_x000D_
  sort_alpha: function(a, b) {_x000D_
    if (a[0] == b[0]) return 0;_x000D_
    if (a[0] < b[0]) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_ddmm: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    m = mtch[2];_x000D_
    d = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  sort_mmdd: function(a, b) {_x000D_
    mtch = a[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt1 = y + m + d;_x000D_
    mtch = b[0].match(sorttable.DATE_RE);_x000D_
    y = mtch[3];_x000D_
    d = mtch[2];_x000D_
    m = mtch[1];_x000D_
    if (m.length == 1) m = '0' + m;_x000D_
    if (d.length == 1) d = '0' + d;_x000D_
    dt2 = y + m + d;_x000D_
    if (dt1 == dt2) return 0;_x000D_
    if (dt1 < dt2) return -1;_x000D_
    return 1;_x000D_
  },_x000D_
  shaker_sort: function(list, comp_func) {_x000D_
    var b = 0;_x000D_
    var t = list.length - 1;_x000D_
    var swap = true;_x000D_
    while (swap) {_x000D_
      swap = false;_x000D_
      for (var i = b; i < t; ++i) {_x000D_
        if (comp_func(list[i], list[i + 1]) > 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i + 1];_x000D_
          list[i + 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      t--;_x000D_
_x000D_
      if (!swap) break;_x000D_
_x000D_
      for (var i = t; i > b; --i) {_x000D_
        if (comp_func(list[i], list[i - 1]) < 0) {_x000D_
          var q = list[i];_x000D_
          list[i] = list[i - 1];_x000D_
          list[i - 1] = q;_x000D_
          swap = true;_x000D_
        }_x000D_
      }_x000D_
      b++;_x000D_
_x000D_
    }_x000D_
  }_x000D_
}_x000D_
if (document.addEventListener) {_x000D_
  document.addEventListener("DOMContentLoaded", sorttable.init, false);_x000D_
}_x000D_
/* for Internet Explorer */_x000D_
/*@cc_on @*/_x000D_
/*@if (@_win32)_x000D_
    document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");_x000D_
    var script = document.getElementById("__ie_onload");_x000D_
    script.onreadystatechange = function() {_x000D_
        if (this.readyState == "complete") {_x000D_
            sorttable.init(); // call the onload handler_x000D_
        }_x000D_
    };_x000D_
/*@end @*/_x000D_
/* for Safari */_x000D_
if (/WebKit/i.test(navigator.userAgent)) { // sniff_x000D_
  var _timer = setInterval(function() {_x000D_
    if (/loaded|complete/.test(document.readyState)) {_x000D_
      sorttable.init(); // call the onload handler_x000D_
    }_x000D_
  }, 10);_x000D_
}_x000D_
/* for other browsers */_x000D_
window.onload = sorttable.init;_x000D_
_x000D_
function dean_addEvent(element, type, handler) {_x000D_
  if (element.addEventListener) {_x000D_
    element.addEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (!handler.$$guid) handler.$$guid = dean_addEvent.guid++;_x000D_
    if (!element.events) element.events = {};_x000D_
    var handlers = element.events[type];_x000D_
    if (!handlers) {_x000D_
      handlers = element.events[type] = {};_x000D_
      if (element["on" + type]) {_x000D_
        handlers[0] = element["on" + type];_x000D_
      }_x000D_
    }_x000D_
    handlers[handler.$$guid] = handler;_x000D_
    element["on" + type] = handleEvent;_x000D_
  }_x000D_
};_x000D_
dean_addEvent.guid = 1;_x000D_
_x000D_
function removeEvent(element, type, handler) {_x000D_
  if (element.removeEventListener) {_x000D_
    element.removeEventListener(type, handler, false);_x000D_
  } else {_x000D_
    if (element.events && element.events[type]) {_x000D_
      delete element.events[type][handler.$$guid];_x000D_
    }_x000D_
  }_x000D_
};_x000D_
_x000D_
function handleEvent(event) {_x000D_
  var returnValue = true;_x000D_
  event = event || fixEvent(((this.ownerDocument || this.document || this).parentWindow || window).event);_x000D_
  var handlers = this.events[event.type];_x000D_
  for (var i in handlers) {_x000D_
    this.$$handleEvent = handlers[i];_x000D_
    if (this.$$handleEvent(event) === false) {_x000D_
      returnValue = false;_x000D_
    }_x000D_
  }_x000D_
  return returnValue;_x000D_
};_x000D_
_x000D_
function fixEvent(event) {_x000D_
  event.preventDefault = fixEvent.preventDefault;_x000D_
  event.stopPropagation = fixEvent.stopPropagation;_x000D_
  return event;_x000D_
};_x000D_
fixEvent.preventDefault = function() {_x000D_
  this.returnValue = false;_x000D_
};_x000D_
fixEvent.stopPropagation = function() {_x000D_
  this.cancelBubble = true;_x000D_
}_x000D_
if (!Array.forEach) {_x000D_
  Array.forEach = function(array, block, context) {_x000D_
    for (var i = 0; i < array.length; i++) {_x000D_
      block.call(context, array[i], i, array);_x000D_
    }_x000D_
  };_x000D_
}_x000D_
Function.prototype.forEach = function(object, block, context) {_x000D_
  for (var key in object) {_x000D_
    if (typeof this.prototype[key] == "undefined") {_x000D_
      block.call(context, object[key], key, object);_x000D_
    }_x000D_
  }_x000D_
};_x000D_
String.forEach = function(string, block, context) {_x000D_
  Array.forEach(string.split(""), function(chr, index) {_x000D_
    block.call(context, chr, index, string);_x000D_
  });_x000D_
};_x000D_
var forEach = function(object, block, context) {_x000D_
  if (object) {_x000D_
    var resolve = Object;_x000D_
    if (object instanceof Function) {_x000D_
      resolve = Function;_x000D_
    } else if (object.forEach instanceof Function) {_x000D_
      object.forEach(block, context);_x000D_
      return;_x000D_
    } else if (typeof object == "string") {_x000D_
      resolve = String;_x000D_
    } else if (typeof object.length == "number") {_x000D_
      resolve = Array;_x000D_
    }_x000D_
    resolve.forEach(object, block, context);_x000D_
  }_x000D_
}
_x000D_
table.sortable thead {_x000D_
  background-color: #eee;_x000D_
  color: #666666;_x000D_
  font-weight: bold;_x000D_
  cursor: default;_x000D_
}
_x000D_
<table class="sortable">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>S.L.</th>_x000D_
      <th>name</th>_x000D_
      <th>Goal</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>Ronaldo</td>_x000D_
      <td>120</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>2</td>_x000D_
      <td>Messi</td>_x000D_
      <td>66</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>3</td>_x000D_
      <td>Ribery</td>_x000D_
      <td>10</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>Bale</td>_x000D_
      <td>22</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

JS is used here without any other JQuery Plugin.

How to remove decimal values from a value of type 'double' in Java

Alternatively, you can use the method int integerValue = (int)Math.round(double a);

Pandas: drop a level from a multi-level column index?

As of Pandas 0.24.0, we can now use DataFrame.droplevel():

cols = pd.MultiIndex.from_tuples([("a", "b"), ("a", "c")])
df = pd.DataFrame([[1,2], [3,4]], columns=cols)

df.droplevel(0, axis=1) 

#   b  c
#0  1  2
#1  3  4

This is very useful if you want to keep your DataFrame method-chain rolling.

Position DIV relative to another DIV?

you can use position:relative; inside #one div and position:absolute inside #two div. you can see it

How can one pull the (private) data of one's own Android app?

Does that mean that one could chmod the directory from world:--x to world:r-x long enough to be able to fetch the files?

Yes, exactly. Weirdly enough, you also need the file to have the x bit set. (at least on Android 2.3)

chmod 755 all the way down worked to copy a file (but you should revert permissions afterwards, if you plan to continue using the device).

How to list files in an android directory?

String[] listOfFiles = getActivity().getFilesDir().list();

or

String[] listOfFiles = Environment.getExternalStoragePublicDirectory (Environment.DIRECTORY_DOWNLOADS).list();

How to change proxy settings in Android (especially in Chrome)

Found one solution for WIFI (works for Android 4.3, 4.4):

  1. Connect to WIFI network (e.g. 'Alex')
  2. Settings->WIFI
  3. Long tap on connected network's name (e.g. on 'Alex')
  4. Modify network config-> Show advanced options
  5. Set proxy settings

Use 'import module' or 'from module import'?

import package
import module

With import, the token must be a module (a file containing Python commands) or a package (a folder in the sys.path containing a file __init__.py.)

When there are subpackages:

import package1.package2.package
import package1.package2.module

the requirements for folder (package) or file (module) are the same, but the folder or file must be inside package2 which must be inside package1, and both package1 and package2 must contain __init__.py files. https://docs.python.org/2/tutorial/modules.html

With the from style of import:

from package1.package2 import package
from package1.package2 import module

the package or module enters the namespace of the file containing the import statement as module (or package) instead of package1.package2.module. You can always bind to a more convenient name:

a = big_package_name.subpackage.even_longer_subpackage_name.function

Only the from style of import permits you to name a particular function or variable:

from package3.module import some_function

is allowed, but

import package3.module.some_function 

is not allowed.

Typescript Date Type?

Every class or interface can be used as a type in TypeScript.

 const date = new Date();

will already know about the date type definition as Date is an internal TypeScript object referenced by the DateConstructor interface.

And for the constructor you used, it is defined as:

interface DateConstructor {
    new(): Date;
    ...
}

To make it more explicit, you can use:

 const date: Date = new Date();

You might be missing the type definitions though, the Date is coming for my example from the ES6 lib, and in my tsconfig.json I have defined:

"compilerOptions": {
    "target": "ES6",
    "lib": [
        "es6",
        "dom"
    ],

You might adapt these settings to target your wanted version of JavaScript.


The Date is by the way an Interface from lib.es6.d.ts:

/** Enables basic storage and retrieval of dates and times. */
interface Date {
    /** Returns a string representation of a date. The format of the string depends on the locale. */
    toString(): string;
    /** Returns a date as a string value. */
    toDateString(): string;
    /** Returns a time as a string value. */
    toTimeString(): string;
    /** Returns a value as a string value appropriate to the host environment's current locale. */
    toLocaleString(): string;
    /** Returns a date as a string value appropriate to the host environment's current locale. */
    toLocaleDateString(): string;
    /** Returns a time as a string value appropriate to the host environment's current locale. */
    toLocaleTimeString(): string;
    /** Returns the stored time value in milliseconds since midnight, January 1, 1970 UTC. */
    valueOf(): number;
    /** Gets the time value in milliseconds. */
    getTime(): number;
    /** Gets the year, using local time. */
    getFullYear(): number;
    /** Gets the year using Universal Coordinated Time (UTC). */
    getUTCFullYear(): number;
    /** Gets the month, using local time. */
    getMonth(): number;
    /** Gets the month of a Date object using Universal Coordinated Time (UTC). */
    getUTCMonth(): number;
    /** Gets the day-of-the-month, using local time. */
    getDate(): number;
    /** Gets the day-of-the-month, using Universal Coordinated Time (UTC). */
    getUTCDate(): number;
    /** Gets the day of the week, using local time. */
    getDay(): number;
    /** Gets the day of the week using Universal Coordinated Time (UTC). */
    getUTCDay(): number;
    /** Gets the hours in a date, using local time. */
    getHours(): number;
    /** Gets the hours value in a Date object using Universal Coordinated Time (UTC). */
    getUTCHours(): number;
    /** Gets the minutes of a Date object, using local time. */
    getMinutes(): number;
    /** Gets the minutes of a Date object using Universal Coordinated Time (UTC). */
    getUTCMinutes(): number;
    /** Gets the seconds of a Date object, using local time. */
    getSeconds(): number;
    /** Gets the seconds of a Date object using Universal Coordinated Time (UTC). */
    getUTCSeconds(): number;
    /** Gets the milliseconds of a Date, using local time. */
    getMilliseconds(): number;
    /** Gets the milliseconds of a Date object using Universal Coordinated Time (UTC). */
    getUTCMilliseconds(): number;
    /** Gets the difference in minutes between the time on the local computer and Universal Coordinated Time (UTC). */
    getTimezoneOffset(): number;
    /**
      * Sets the date and time value in the Date object.
      * @param time A numeric value representing the number of elapsed milliseconds since midnight, January 1, 1970 GMT.
      */
    setTime(time: number): number;
    /**
      * Sets the milliseconds value in the Date object using local time.
      * @param ms A numeric value equal to the millisecond value.
      */
    setMilliseconds(ms: number): number;
    /**
      * Sets the milliseconds value in the Date object using Universal Coordinated Time (UTC).
      * @param ms A numeric value equal to the millisecond value.
      */
    setUTCMilliseconds(ms: number): number;

    /**
      * Sets the seconds value in the Date object using local time.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setSeconds(sec: number, ms?: number): number;
    /**
      * Sets the seconds value in the Date object using Universal Coordinated Time (UTC).
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCSeconds(sec: number, ms?: number): number;
    /**
      * Sets the minutes value in the Date object using local time.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setMinutes(min: number, sec?: number, ms?: number): number;
    /**
      * Sets the minutes value in the Date object using Universal Coordinated Time (UTC).
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCMinutes(min: number, sec?: number, ms?: number): number;
    /**
      * Sets the hour value in the Date object using local time.
      * @param hours A numeric value equal to the hours value.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setHours(hours: number, min?: number, sec?: number, ms?: number): number;
    /**
      * Sets the hours value in the Date object using Universal Coordinated Time (UTC).
      * @param hours A numeric value equal to the hours value.
      * @param min A numeric value equal to the minutes value.
      * @param sec A numeric value equal to the seconds value.
      * @param ms A numeric value equal to the milliseconds value.
      */
    setUTCHours(hours: number, min?: number, sec?: number, ms?: number): number;
    /**
      * Sets the numeric day-of-the-month value of the Date object using local time.
      * @param date A numeric value equal to the day of the month.
      */
    setDate(date: number): number;
    /**
      * Sets the numeric day of the month in the Date object using Universal Coordinated Time (UTC).
      * @param date A numeric value equal to the day of the month.
      */
    setUTCDate(date: number): number;
    /**
      * Sets the month value in the Date object using local time.
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
      * @param date A numeric value representing the day of the month. If this value is not supplied, the value from a call to the getDate method is used.
      */
    setMonth(month: number, date?: number): number;
    /**
      * Sets the month value in the Date object using Universal Coordinated Time (UTC).
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively.
      * @param date A numeric value representing the day of the month. If it is not supplied, the value from a call to the getUTCDate method is used.
      */
    setUTCMonth(month: number, date?: number): number;
    /**
      * Sets the year of the Date object using local time.
      * @param year A numeric value for the year.
      * @param month A zero-based numeric value for the month (0 for January, 11 for December). Must be specified if numDate is specified.
      * @param date A numeric value equal for the day of the month.
      */
    setFullYear(year: number, month?: number, date?: number): number;
    /**
      * Sets the year value in the Date object using Universal Coordinated Time (UTC).
      * @param year A numeric value equal to the year.
      * @param month A numeric value equal to the month. The value for January is 0, and other month values follow consecutively. Must be supplied if numDate is supplied.
      * @param date A numeric value equal to the day of the month.
      */
    setUTCFullYear(year: number, month?: number, date?: number): number;
    /** Returns a date converted to a string using Universal Coordinated Time (UTC). */
    toUTCString(): string;
    /** Returns a date as a string value in ISO format. */
    toISOString(): string;
    /** Used by the JSON.stringify method to enable the transformation of an object's data for JavaScript Object Notation (JSON) serialization. */
    toJSON(key?: any): string;
}

How to save LogCat contents to file?

String filePath = folder.getAbsolutePath()+ "/logcat.txt"; 
Runtime.getRuntime().exec(new String[]{"logcat", "-f", filePath, "MyAppTAG:V", "*:E"});

How to overlay one div over another div

This is what you need:

_x000D_
_x000D_
function showFrontLayer() {_x000D_
  document.getElementById('bg_mask').style.visibility='visible';_x000D_
  document.getElementById('frontlayer').style.visibility='visible';_x000D_
}_x000D_
function hideFrontLayer() {_x000D_
  document.getElementById('bg_mask').style.visibility='hidden';_x000D_
  document.getElementById('frontlayer').style.visibility='hidden';_x000D_
}
_x000D_
#bg_mask {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: auto;_x000D_
  margin-top: 0px;_x000D_
  width: 981px;_x000D_
  height: 610px;_x000D_
  background : url("img_dot_white.jpg") center;_x000D_
  z-index: 0;_x000D_
  visibility: hidden;_x000D_
} _x000D_
_x000D_
#frontlayer {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  margin: 70px 140px 175px 140px;_x000D_
  padding : 30px;_x000D_
  width: 700px;_x000D_
  height: 400px;_x000D_
  background-color: orange;_x000D_
  visibility: hidden;_x000D_
  border: 1px solid black;_x000D_
  z-index: 1;_x000D_
} _x000D_
_x000D_
_x000D_
</style>
_x000D_
<html>_x000D_
  <head>_x000D_
    <META HTTP-EQUIV="EXPIRES" CONTENT="-1" />_x000D_
_x000D_
  </head>_x000D_
  <body>_x000D_
    <form action="test.html">_x000D_
      <div id="baselayer">_x000D_
_x000D_
        <input type="text" value="testing text"/>_x000D_
        <input type="button" value="Show front layer" onclick="showFrontLayer();"/> Click 'Show front layer' button<br/><br/><br/>_x000D_
_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing textsting text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text Testing text_x000D_
        <div id="bg_mask">_x000D_
          <div id="frontlayer"><br/><br/>_x000D_
            Now try to click on "Show front layer" button or the text box. It is not active.<br/><br/><br/>_x000D_
            Use position: absolute to get the one div on top of another div.<br/><br/><br/>_x000D_
            The bg_mask div is between baselayer and front layer.<br/><br/><br/>_x000D_
            In bg_mask, img_dot_white.jpg(1 pixel in width and height) is used as background image to avoid IE browser transparency issue;<br/><br/><br/>_x000D_
            <input type="button" value="Hide front layer" onclick="hideFrontLayer();"/>_x000D_
          </div>_x000D_
        </div>_x000D_
      </div>_x000D_
    </form>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Accessing elements of Python dictionary by index

Few people appear, despite the many answers to this question, to have pointed out that dictionaries are un-ordered mappings, and so (until the blessing of insertion order with Python 3.7) the idea of the "first" entry in a dictionary literally made no sense. And even an OrderedDict can only be accessed by numerical index using such uglinesses as mydict[mydict.keys()[0]] (Python 2 only, since in Python 3 keys() is a non-subscriptable iterator.)

From 3.7 onwards and in practice in 3,6 as well - the new behaviour was introduced then, but not included as part of the language specification until 3.7 - iteration over the keys, values or items of a dict (and, I believe, a set also) will yield the least-recently inserted objects first. There is still no simple way to access them by numerical index of insertion.

As to the question of selecting and "formatting" items, if you know the key you want to retrieve in the dictionary you would normally use the key as a subscript to retrieve it (my_var = mydict['Apple']).

If you really do want to be able to index the items by entry number (ignoring the fact that a particular entry's number will change as insertions are made) then the appropriate structure would probably be a list of two-element tuples. Instead of

mydict = {
  'Apple': {'American':'16', 'Mexican':10, 'Chinese':5},
  'Grapes':{'Arabian':'25','Indian':'20'} }

you might use:

mylist = [
    ('Apple', {'American':'16', 'Mexican':10, 'Chinese':5}),
    ('Grapes', {'Arabian': '25', 'Indian': '20'}
]

Under this regime the first entry is mylist[0] in classic list-endexed form, and its value is ('Apple', {'American':'16', 'Mexican':10, 'Chinese':5}). You could iterate over the whole list as follows:

for (key, value) in mylist:  # unpacks to avoid tuple indexing
    if key == 'Apple':
        if 'American' in value:
            print(value['American'])

but if you know you are looking for the key "Apple", why wouldn't you just use a dict instead?

You could introduce an additional level of indirection by cacheing the list of keys, but the complexities of keeping two data structures in synchronisation would inevitably add to the complexity of your code.

Starting a shell in the Docker Alpine container

Nowadays, Alpine images will boot directly into /bin/sh by default, without having to specify a shell to execute:

$ sudo docker run -it --rm alpine  
/ # echo $0  
/bin/sh  

This is since the alpine image Dockerfiles now contain a CMD command, that specifies the shell to execute when the container starts: CMD ["/bin/sh"].

In older Alpine image versions (pre-2017), the CMD command was not used, since Docker used to create an additional layer for CMD which caused the image size to increase. This is something that the Alpine image developers wanted to avoid. In recent Docker versions (1.10+), CMD no longer occupies a layer, and so it was added to alpine images. Therefore, as long as CMD is not overridden, recent Alpine images will boot into /bin/sh.

For reference, see the following commit to the official Alpine Dockerfiles by Glider Labs:
https://github.com/gliderlabs/docker-alpine/commit/ddc19dd95ceb3584ced58be0b8d7e9169d04c7a3#diff-db3dfdee92c17cf53a96578d4900cb5b

How to change the data type of a column without dropping the column with query?

ALTER tablename MODIFY columnName newColumnType

I'm not sure how it will handle the change from datetime to varchar though, so you may need to rename the column, add a new one with the old name and the correct data type (varchar) and then write an update query to populate the new column from the old.

http://www.1keydata.com/sql/sql-alter-table.html

How should I escape strings in JSON?

Ideally, find a JSON library in your language that you can feed some appropriate data structure to, and let it worry about how to escape things. It'll keep you much saner. If for whatever reason you don't have a library in your language, you don't want to use one (I wouldn't suggest this¹), or you're writing a JSON library, read on.

Escape it according to the RFC. JSON is pretty liberal: The only characters you must escape are \, ", and control codes (anything less than U+0020).

This structure of escaping is specific to JSON. You'll need a JSON specific function. All of the escapes can be written as \uXXXX where XXXX is the UTF-16 code unit¹ for that character. There are a few shortcuts, such as \\, which work as well. (And they result in a smaller and clearer output.)

For full details, see the RFC.

¹JSON's escaping is built on JS, so it uses \uXXXX, where XXXX is a UTF-16 code unit. For code points outside the BMP, this means encoding surrogate pairs, which can get a bit hairy. (Or, you can just output the character directly, since JSON's encoded for is Unicode text, and allows these particular characters.)

Is CSS Turing complete?

Turing-completeness is not only about "defining functions" or "have ifs/loops/etc". For example, Haskell doesn't have "loop", lambda-calculus don't have "ifs", etc...

For example, this site: http://experthuman.com/programming-with-nothing. The author uses Ruby and create a "FizzBuzz" program with only closures (no strings, numbers, or anything like that)...

There are examples when people compute some arithmetical functions on Scala using only the type system

So, yes, in my opinion, CSS3+HTML is turing-complete (even if you can't exactly do any real computation with then without becoming crazy)

How to get the seconds since epoch from the time + date output of gmtime()?

There are two ways, depending on your original timestamp:

mktime() and timegm()

http://docs.python.org/library/time.html

Can .NET load and parse a properties file equivalent to Java Properties class?

I don't know of any built-in way to do this. However, it would seem easy enough to do, since the only delimiters you have to worry about are the newline character and the equals sign.

It would be very easy to write a routine that will return a NameValueCollection, or an IDictionary given the contents of the file.

What is causing this error - "Fatal error: Unable to find local grunt"

I made the mistake to install some packages using sudo and other without privileges , this fixed my problem.

sudo chown -R $(whoami) $HOME/.npm

hope it helps someone.

Import pandas dataframe column as string not int

This probably isn't the most elegant way to do it, but it gets the job done.

In[1]: import numpy as np

In[2]: import pandas as pd

In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])

In[4]: df
Out[4]: 
                       ID
0  00013007854817840016671868
1  00013007854817840016749251
2  00013007854817840016754630
3  00013007854817840016781876
4  00013007854817840017028824
5  00013007854817840017963235
6  00013007854817840018860166

Just replace '/Users/spencerlyon2/Desktop/test.csv' with the path to your file

How to push a single file in a subdirectory to Github (not master)

git status #then file which you need to push git add example.FileExtension

git commit "message is example"

git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)

Xamarin.Forms ListView: Set the highlight color of a tapped item

I have & use a solution similar to @adam-pedley. No custom renderers, in xaml i bind background ViewCell Property

                <ListView x:Name="placesListView" Grid.Row="2" Grid.ColumnSpan="3" ItemsSource="{Binding PlacesCollection}" SelectedItem="{Binding PlaceItemSelected}">
                <ListView.ItemTemplate>
                    <DataTemplate>
                        <ViewCell>
                            <Grid BackgroundColor="{Binding IsSelected,Converter={StaticResource boolToColor}}">
                                <Grid.RowDefinitions>
                                    <RowDefinition Height="auto"/>
                                    <RowDefinition Height="auto"/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="*" />
                                    <ColumnDefinition Width="*" />
                                </Grid.ColumnDefinitions>

                                <Label Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding DisplayName}" Style="{StaticResource blubeLabelBlackItalic}" FontSize="Default" HorizontalOptions="Start" />
                                <Label Grid.Row="2" Grid.ColumnSpan="2" Text="{Binding DisplayDetail}"  Style="{StaticResource blubeLabelGrayItalic}" FontSize="Small" HorizontalOptions="Start"/>
                                <!--
                                <Label Grid.RowSpan="2" Grid.ColumnSpan="2" Text="{Binding KmDistance}"  Style="{StaticResource blubeLabelGrayItalic}" FontSize="Default" HorizontalOptions="End" VerticalOptions="Center"/>
                                -->
                            </Grid>
                        </ViewCell>
                    </DataTemplate>
                </ListView.ItemTemplate>                    
            </ListView>

In code (MVVM) i save the lastitemselected by a boolToColor Converter i update background color

    public class BoolToColorConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (bool)value ? Color.Yellow : Color.White;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return (Color)value == Color.Yellow ? true : false;
        }
    }

    PlaceItem LastItemSelected;

    PlaceItem placeItemSelected;
    public PlaceItem PlaceItemSelected
    {
        get
        {
            return placeItemSelected;
        }

        set
        {
            if (LastItemSelected != null)
                LastItemSelected.IsSelected = false;

            placeItemSelected = value;
            if (placeItemSelected != null)
            {
                placeItemSelected.IsSelected = true;
                LastItemSelected = placeItemSelected;
            }
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(PlaceItemSelected)));
        }
    }

My example is extracted by a listview of places which are in a Xamarin Forms Maps (same contentpage). I hope this solution will be usefull for somebody

How to detect when an Android app goes to the background and come back to the foreground

There are three ways through which you can achieve this:

  • Single Activity architecture
  • ActivityLifecycleCallback
  • LifecycleObserver and ProcessLifecycleOwner

Have written an article in detail on this over here. Hope it helps.

What is the proper #include for the function 'sleep()'?

this is what I use for a cross-platform code:

#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif

int main()
{
  pollingDelay = 100
  //do stuff

  //sleep:
  #ifdef _WIN32
  Sleep(pollingDelay);
  #else
  usleep(pollingDelay*1000);  /* sleep for 100 milliSeconds */
  #endif

  //do stuff again
  return 0;
}

curl POST format for CURLOPT_POSTFIELDS

This answer took me forever to find as well. I discovered that all you have to do is concatenate the URL ('?' after the file name and extension) with the URL-encoded query string. It doesn't even look like you have to set the POST cURL options. See the fake example below:

//create URL
$exampleURL = 'http://www.example.com/example.php?';

// create curl resource
$ch = curl_init(); 

// build URL-encoded query string
$data = http_build_query(
    array('first' => 'John', 'last' => 'Smith', '&'); // set url
curl_setopt($ch, CURLOPT_URL, $exampleURL . $data); 

// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

// $output contains the output string
$output = curl_exec($ch); 

// close curl resource to free up system resources <br/>
curl_close($ch);

You can also use file_get_contents():

// read entire webpage file into a string
$output = file_get_contents($exampleURL . $data);

Can we pass model as a parameter in RedirectToAction?

[NonAction]
private ActionResult CRUD(someModel entity)
{
        try
        {
            //you business logic here
     return View(entity);
       }                                
         catch (Exception exp)
         {
             ModelState.AddModelError("", exp.InnerException.Message);
             Response.StatusCode = 350;
             return someerrohandilingactionresult(entity, actionType);
         }
         //Retrun appropriate message or redirect to proper action
      return RedirectToAction("Index");   
}

Getting a Request.Headers value

In dotnet core, Request.Headers["X-MyCustomHeader"] returns StringValues which will not be null. You can check the count though to make sure it found your header as follows:

var myHeaderValue = Request.Headers["X-MyCustomHeader"];
if(myHeaderValue.Count == 0) return Unauthorized();
string myHeader = myHeaderValue.ToString(); //For illustration purposes.

How to concatenate strings in windows batch file for loop?

In batch you could do it like this:

@echo off

setlocal EnableDelayedExpansion

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do (
  set "var=%%sxyz"
  svn co "!var!"
)

If you don't need the variable !var! elsewhere in the loop, you could simplify that to

@echo off

setlocal

set "string_list=str1 str2 str3 ... str10"

for %%s in (%string_list%) do svn co "%%sxyz"

However, like C.B. I'd prefer PowerShell if at all possible:

$string_list = 'str1', 'str2', 'str3', ... 'str10'

$string_list | ForEach-Object {
  $var = "${_}xyz"   # alternatively: $var = $_ + 'xyz'
  svn co $var
}

Again, this could be simplified if you don't need $var elsewhere in the loop:

$string_list = 'str1', 'str2', 'str3', ... 'str10'
$string_list | ForEach-Object { svn co "${_}xyz" }

Insertion sort vs Bubble Sort Algorithms

The main advantage of insert sort is that it's online algorithm. You don't have to have all the values at start. This could be useful, when dealing with data coming from network, or some sensor.

I have a feeling, that this would be faster than other conventional n log(n) algorithms. Because the complexity would be n*(n log(n)) e.g. reading/storing each value from stream (O(n)) and then sorting all the values (O(n log(n))) resulting in O(n^2 log(n))

On the contrary using Insert Sort needs O(n) for reading values from the stream and O(n) to put the value to the correct place, thus it's O(n^2) only. Other advantage is, that you don't need buffers for storing values, you sort them in the final destination.

What is a good way to handle exceptions when trying to read a file in python?

How about this:

try:
    f = open(fname, 'rb')
except OSError:
    print "Could not open/read file:", fname
    sys.exit()

with f:
    reader = csv.reader(f)
    for row in reader:
        pass #do stuff here

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

Sleep Command in T-SQL?

Here is a very simple piece of C# code to test the CommandTimeout with. It creates a new command which will wait for 2 seconds. Set the CommandTimeout to 1 second and you will see an exception when running it. Setting the CommandTimeout to either 0 or something higher than 2 will run fine. By the way, the default CommandTimeout is 30 seconds.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data.SqlClient;

namespace ConsoleApplication1
{
  class Program
  {
    static void Main(string[] args)
    {
      var builder = new SqlConnectionStringBuilder();
      builder.DataSource = "localhost";
      builder.IntegratedSecurity = true;
      builder.InitialCatalog = "master";

      var connectionString = builder.ConnectionString;

      using (var connection = new SqlConnection(connectionString))
      {
        connection.Open();

        using (var command = connection.CreateCommand())
        {
          command.CommandText = "WAITFOR DELAY '00:00:02'";
          command.CommandTimeout = 1;

          command.ExecuteNonQuery();
        }
      }
    }
  }
}

Xcode swift am/pm time to 24 hour format

Here is the answer with more extra format.

** Xcode 12, Swift 5.3 **

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "HH:mm:ss"
var dateFromStr = dateFormatter.date(from: "12:16:45")!

dateFormatter.dateFormat = "hh:mm:ss a 'on' MMMM dd, yyyy"
//Output: 12:16:45 PM on January 01, 2000

dateFormatter.dateFormat = "E, d MMM yyyy HH:mm:ss Z"
//Output: Sat, 1 Jan 2000 12:16:45 +0600

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
//Output: 2000-01-01T12:16:45+0600

dateFormatter.dateFormat = "EEEE, MMM d, yyyy"
//Output: Saturday, Jan 1, 2000

dateFormatter.dateFormat = "MM-dd-yyyy HH:mm"
//Output: 01-01-2000 12:16

dateFormatter.dateFormat = "MMM d, h:mm a"
//Output: Jan 1, 12:16 PM

dateFormatter.dateFormat = "HH:mm:ss.SSS"
//Output: 12:16:45.000

dateFormatter.dateFormat = "MMM d, yyyy"
//Output: Jan 1, 2000

dateFormatter.dateFormat = "MM/dd/yyyy"
//Output: 01/01/2000

dateFormatter.dateFormat = "hh:mm:ss a"
//Output: 12:16:45 PM

dateFormatter.dateFormat = "MMMM yyyy"
//Output: January 2000

dateFormatter.dateFormat = "dd.MM.yy"
//Output: 01.01.00

//Output: Customisable AP/PM symbols
dateFormatter.amSymbol = "am"
dateFormatter.pmSymbol = "Pm"
dateFormatter.dateFormat = "a"
//Output: Pm

// Usage
var timeFromDate = dateFormatter.string(from: dateFromStr)
print(timeFromDate)

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

I fixed it by added the jquery.slim.min.js after the jquery.min.js, as the Solution Sequence.

Problem Sequence

<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/bootstrap/js/bootstrap.bundle.min.js"></script>

Solution Sequence

<script src="./vendor/jquery/jquery.min.js"></script>
<script src="./vendor/jquery/jquery.slim.min.js"></script>
<script src="./vendor/jquery-easing/jquery.easing.min.js"></script>

HorizontalAlignment=Stretch, MaxWidth, and Left aligned at the same time?

Both answers given worked for the problem I stated -- Thanks!

In my real application though, I was trying to constrain a panel inside of a ScrollViewer and Kent's method didn't handle that very well for some reason I didn't bother to track down. Basically the controls could expand beyond the MaxWidth setting and defeated my intent.

Nir's technique worked well and didn't have the problem with the ScrollViewer, though there is one minor thing to watch out for. You want to be sure the right and left margins on the TextBox are set to 0 or they'll get in the way. I also changed the binding to use ViewportWidth instead of ActualWidth to avoid issues when the vertical scrollbar appeared.

How to get current user who's accessing an ASP.NET application?

Using System.Web.HttpContext.Current.User.Identity.Name should work. Please check the IIS Site settings on the server that is hosting your site by doing the following:

  1. Go to IIS ? Sites ? Your Site ? Authentication

    IIS Settings

  2. Now check that Anonymous Access is Disabled & Windows Authentication is Enabled.

    Authentication

  3. Now System.Web.HttpContext.Current.User.Identity.Name should return something like this:

    domain\username

Width of input type=text element

I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.

How to capture multiple repeated groups?

I think you need something like this....

b="HELLO,THERE,WORLD"
re.findall('[\w]+',b)

Which in Python3 will return

['HELLO', 'THERE', 'WORLD']

Why should we NOT use sys.setdefaultencoding("utf-8") in a py script?

#!/usr/bin/env python
#-*- coding: utf-8 -*-
u = u'moçambique'
print u.encode("utf-8")
print u

chmod +x test.py
./test.py
moçambique
moçambique

./test.py > output.txt
Traceback (most recent call last):
  File "./test.py", line 5, in <module>
    print u
UnicodeEncodeError: 'ascii' codec can't encode character 
u'\xe7' in position 2: ordinal not in range(128)

on shell works , sending to sdtout not , so that is one workaround, to write to stdout .

I made other approach, which is not run if sys.stdout.encoding is not define, or in others words , need export PYTHONIOENCODING=UTF-8 first to write to stdout.

import sys
if (sys.stdout.encoding is None):            
    print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout." 
    exit(1)


so, using same example:

export PYTHONIOENCODING=UTF-8
./test.py > output.txt

will work

Execution failed for task ':app:compileDebugAidl': aidl is missing

Check if you actually have installed the buildVersionTools you are using. In my case I tried 25.0.1 whilst I only had 25.0.2.

To check it go to the SDK Manager, clicking the icon:

enter image description here

Then click Launch Standalone SDK Manager at the bottom:

enter image description here

Now check whatever you need and install packages.

enter image description here

Hope it helps!

Why can't I duplicate a slice with `copy()`?

Another simple way to do this is by using append which will allocate the slice in the process.

arr := []int{1, 2, 3}
tmp := append([]int(nil), arr...)  // Notice the ... splat
fmt.Println(tmp)
fmt.Println(arr)

Output (as expected):

[1 2 3]
[1 2 3]

So a shorthand for copying array arr would be append([]int(nil), arr...)

https://play.golang.org/p/sr_4ofs5GW

Cookie blocked/not saved in IFRAME in Internet Explorer

A better solution would be to make an Ajax call inside the iframe to the page that would get/set cookies...

How do you do block comments in YAML?

An alternative approach:

If

  • your YAML structure has well defined fields to be used by your app
  • AND you may freely add additional fields that won't mess up with your app

then

  • at any level you may add a new block text field named like "Description" or "Comment" or "Notes" or whatever

Example:

Instead of

# This comment
# is too long

use

Description: >
  This comment
  is too long

or

Comment: >
    This comment is also too long
    and newlines survive from parsing!

More advantages:

  1. If the comments become large and complex and have a repeating pattern, you may promote them from plain text blocks to objects
  2. Your app may -in the future- read or update those comments

ImageMagick security policy 'PDF' blocking conversion

For me on Arch Linux, I had to comment this:

  <policy domain="delegate" rights="none" pattern="gs" />

How to view instagram profile picture in full-size?

You can even set the prof. pic size to its high resolution that is '1080x1080'

replace "150x150" with 1080x1080 and remove /vp/ from the link.

Error QApplication: no such file or directory

Well, It's a bit late for this but I've just started learning Qt and maybe this could help somebody out there:

If you're using Qt Creator then when you've started creating the project you were asked to choose a kit to be used with your project, Let's say you chose Desktop Qt <version-here> MinGW 64-bit. For Qt 5, If you opened the Qt folder of your installation, you'll find a folder with the version of Qt installed as its name inside it, here you can find the kits you can choose from.

You can go to /PATH/FOR/Qt/mingw<version>_64/include and here you'll find all the includes you can use in your program, just search for QApplication and you'll find it inside the folder QtWidgets, So you can use #include <QtWidgets/QApplication> since the path starts from the include folder.

The same goes for other headers if you're stuck with any and for other kits.

Note: "all the includes you can use" doesn't mean these are the only ones you can use, If you include iostream for example then the compiler will include it from /PATH/FOR/Qt/Tools/mingw<version>_64/lib/gcc/x86_64-w64-mingw32/7.3.0/include/c++/iostream

ASP.net vs PHP (What to choose)

This is impossible to answer and has been brought up many many times before. Do a search, read those threads, then pick the framework you and your team have experience with.

Find the min/max element of an array in JavaScript

The following code works for me :

var valueList = [10,4,17,9,3];
var maxValue = valueList.reduce(function(a, b) { return Math.max(a, b); });
var minValue = valueList.reduce(function(a, b) { return Math.min(a, b); });

Mathematical functions in Swift

To be perfectly precise, Darwin is enough. No need to import the whole Cocoa framework.

import Darwin

Of course, if you need elements from Cocoa or Foundation or other higher level frameworks, you can import them instead

How to add time to DateTime in SQL

Or try an alternate method using Time datatype:

DECLARE @MyTime TIME = '03:30:00', @MyDay DATETIME = CAST(GETDATE() AS DATE)

SELECT @MyDay+@MyTime

Get img src with PHP

I have done that the more simple way, not as clean as it should be but it was a quick hack

$htmlContent = file_get_contents('pageURL');

// read all image tags into an array
preg_match_all('/<img[^>]+>/i',$htmlContent, $imgTags); 

for ($i = 0; $i < count($imgTags[0]); $i++) {
  // get the source string
  preg_match('/src="([^"]+)/i',$imgTags[0][$i], $imgage);

  // remove opening 'src=' tag, can`t get the regex right
  $origImageSrc[] = str_ireplace( 'src="', '',  $imgage[0]);
}
// will output all your img src's within the html string
print_r($origImageSrc);

How to make <label> and <input> appear on the same line on an HTML form?

I found "display:flex" style is a good way to make these elements in same line. No matter what kind of element in the div. Especially if the input class is form-control,other solutions like bootstrap, inline-block will not work well.

Example:

<div style="display:flex; flex-direction: row; justify-content: center; align-items: center">
    <label for="Student">Name:</label>
    <input name="Student" />
</div>

More detail about display:flex:

flex-direction: row, column

justify-content: flex-end, center, space-between, space-around

align-items: stretch, flex-start, flex-end, center

How to use pip with python 3.4 on windows?

I had the same problem when I install python3.5.3. And finally I find the pip.exe in this folder: ~/python/scripts/pip.exe. Hope that help.

Delete dynamically-generated table row using jQuery

  $(document.body).on('click', 'buttontrash', function () { // <-- changes
    alert("aa");
   /$(this).closest('tr').remove();
    return false;
});

This works perfectly, take not of document.body

How to stop PHP code execution?

I'm not sure you understand what "exit" states

Terminates execution of the script. Shutdown functions and object destructors will always be executed even if exit is called.

It's normal to do that, it must clear it's memmory of all the variables and functions you called before. Not doing this would mean your memmory would remain stuck and ocuppied in your RAM, and if this would happen several times you would need to reboot and flush your RAM in order to have any left.

Sum rows in data.frame or matrix

I came here hoping to find a way to get the sum across all columns in a data table and run into issues implementing the above solutions. A way to add a column with the sum across all columns uses the cbind function:

cbind(data, total = rowSums(data))

This method adds a total column to the data and avoids the alignment issue yielded when trying to sum across ALL columns using the above solutions (see the post below for a discussion of this issue).

Adding a new column to matrix error

How to check if a folder exists

You need to transform your Path into a File and test for existence:

for(Path entry: stream){
  if(entry.toFile().exists()){
    log.info("working on file " + entry.getFileName());
  }
}

How do I load an url in iframe with Jquery

$("#button").click(function () { 
    $("#frame").attr("src", "http://www.example.com/");
});

HTML:

 <div id="mydiv">
     <iframe id="frame" src="" width="100%" height="300">
     </iframe>
 </div>
 <button id="button">Load</button>

Break or return from Java 8 stream forEach?

This is possible for Iterable.forEach() (but not reliably with Stream.forEach()). The solution is not nice, but it is possible.

WARNING: You should not use it for controlling business logic, but purely for handling an exceptional situation which occurs during the execution of the forEach(). Such as a resource suddenly stops being accessible, one of the processed objects is violating a contract (e.g. contract says that all the elements in the stream must not be null but suddenly and unexpectedly one of them is null) etc.

According to the documentation for Iterable.forEach():

Performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception... Exceptions thrown by the action are relayed to the caller.

So you throw an exception which will immediately break the internal loop.

The code will be something like this - I cannot say I like it but it works. You create your own class BreakException which extends RuntimeException.

try {
    someObjects.forEach(obj -> {
        // some useful code here
        if(some_exceptional_condition_met) {
            throw new BreakException();
       }
    }
}
catch (BreakException e) {
    // here you know that your condition has been met at least once
}

Notice that the try...catch is not around the lambda expression, but rather around the whole forEach() method. To make it more visible, see the following transcription of the code which shows it more clearly:

Consumer<? super SomeObject> action = obj -> {
    // some useful code here
    if(some_exceptional_condition_met) {
        throw new BreakException();
    }
});

try {
    someObjects.forEach(action);
}
catch (BreakException e) {
    // here you know that your condition has been met at least once
}

PowerShell equivalent to grep -f

PS) new-alias grep findstr
PS) C:\WINDOWS> ls | grep -I -N exe

105:-a---        2006-11-02     13:34      49680 twunk_16.exe
106:-a---        2006-11-02     13:34      31232 twunk_32.exe
109:-a---        2006-09-18     23:43     256192 winhelp.exe
110:-a---        2006-11-02     10:45       9216 winhlp32.exe

PS) grep /?

Is there a regular expression to detect a valid regular expression?

No, if you are strictly speaking about regular expressions and not including some regular expression implementations that are actually context free grammars.

There is one limitation of regular expressions which makes it impossible to write a regex that matches all and only regexes. You cannot match implementations such as braces which are paired. Regexes use many such constructs, let's take [] as an example. Whenever there is an [ there must be a matching ], which is simple enough for a regex "\[.*\]".

What makes it impossible for regexes is that they can be nested. How can you write a regex that matches nested brackets? The answer is you can't without an infinitely long regex. You can match any number of nested parenthesis through brute force but you can't ever match an arbitrarily long set of nested brackets.

This capability is often referred to as counting, because you're counting the depth of the nesting. A regex by definition does not have the capability to count.


I ended up writing "Regular Expression Limitations" about this.

Convert a list to a dictionary in Python

You can also try this approach save the keys and values in different list and then use dict method

data=['test1', '1', 'test2', '2', 'test3', '3', 'test4', '4']

keys=[]
values=[]
for i,j in enumerate(data):
    if i%2==0:
        keys.append(j)
    else:
        values.append(j)

print(dict(zip(keys,values)))

output:

{'test3': '3', 'test1': '1', 'test2': '2', 'test4': '4'}

Get number of digits with JavaScript

A solution that also works with both negative numbers and floats, and doesn't call any expensive String manipulation functions:

function getDigits(n) {
   var a = Math.abs(n);            // take care of the sign
   var b = a << 0;                 // truncate the number
   if(b - a !== 0) {               // if the number is a float
       return ("" + a).length - 1; // return the amount of digits & account for the dot
   } else {
       return ("" + a).length;     // return the amount of digits
   }
}

How do I check if a cookie exists?

function getCookie(name) {

    var dc = document.cookie;
    var prefix = name + "=";
    var begin = dc.indexOf("; " + prefix);
    if (begin == -1) {
        begin = dc.indexOf(prefix);
        if (begin != 0) return null;
        else{
            var oneCookie = dc.indexOf(';', begin);
            if(oneCookie == -1){
                var end = dc.length;
            }else{
                var end = oneCookie;
            }
            return dc.substring(begin, end).replace(prefix,'');
        } 

    }
    else
    {
        begin += 2;
        var end = document.cookie.indexOf(";", begin);
        if (end == -1) {
            end = dc.length;
        }
        var fixed = dc.substring(begin, end).replace(prefix,'');
    }
    // return decodeURI(dc.substring(begin + prefix.length, end));
    return fixed;
} 

Tried @jac function, got some trouble, here's how I edited his function.

jquery AJAX and json format

You need to parse the string you are sending from javascript object to the JSON object

var json=$.parseJSON(data);

Handling Dialogs in WPF with MVVM

I struggled with the same problem. I have come up with a way to intercommunicate between the View and the ViewModel. You can initiate sending a message from the ViewModel to the View to tell it to show a messagebox and it will report back with the result. Then the ViewModel can respond to the result returned from the View.

I demonstrate this in my blog:

Where is Ubuntu storing installed programs?

to find the program you want you can run this command at terminal:

find / usr-name "your_program"

gradle build fails on lint task

Got same error on AndroidStudio version 0.51

Build was working fine and suddenly, after only changing the version code value, I got a Lint related build error.

Tried to change build.gradle, cleared AndroidStudio cache and restart, but no change.

Finally I returned to original code (causing the error), and removed android:debuggable="false" from AndroidManifest.xml, causing the build to succeed.

I added it again and it still works... Don't ask me why :S

How to mute an html5 video player using jQuery

Are you using the default controls boolean attribute on the video tag? If so, I believe all the supporting browsers have mute buttons. If you need to wire it up, set .muted to true on the element in javascript (use .prop for jquery because it's an IDL attribute.) The speaker icon on the volume control is the mute button on chrome,ff, safari, and opera for example

Check/Uncheck checkbox with JavaScript

For single check try

_x000D_
_x000D_
myCheckBox.checked=1
_x000D_
<input type="checkbox" id="myCheckBox"> Call to her
_x000D_
_x000D_
_x000D_

for multi try

_x000D_
_x000D_
document.querySelectorAll('.imChecked').forEach(c=> c.checked=1)
_x000D_
Buy wine: <input type="checkbox" class="imChecked"><br>_x000D_
Play smooth-jazz music: <input type="checkbox"><br>_x000D_
Shave: <input type="checkbox" class="imChecked"><br>
_x000D_
_x000D_
_x000D_

capture div into image using html2canvas

You can get the screenshot of a division and save it easily just using the below snippet. Here I'm used the entire body, you can choose the specific image/div elements just by putting the id/class names.

 html2canvas(document.getElementsByClassName("image-div")[0], {
  useCORS: true,
}).then(function (canvas) {
  var imageURL = canvas.toDataURL("image/png");
  let a = document.createElement("a");
  a.href = imageURL;
  a.download = imageURL;
  a.click();
});

PHP string "contains"

PHP 8 or newer:

Use the str_contains function.

if (str_contains($str, "."))
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

PHP 7 or older:

if (strpos($str, '.') !== FALSE)
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0, the comparison will evaluate to true because 0 is loosely equal to false.

How do you convert an entire directory with ffmpeg?

And for Windows, this does not work

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec mp3 "%~nG.mp3"

even if I do double those %.

I would even suggest:

-acodec ***libmp3lame***

also:

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec libmp3lame "%~nG.mp3"

Impersonate tag in Web.Config

Put the identity element before the authentication element

mysql is not recognised as an internal or external command,operable program or batch

In my case, I resolved it by adding this path C:\xampp\mysql\bin to system variables path and then restarted pash/cmd.

Note: Click me if you don't know how to set the path and system variables.

How can I add a hint or tooltip to a label in C# Winforms?

System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();
ToolTip1.SetToolTip( Label1, "Label for Label1");

Stylesheet not updating

If it is cached on the server, there is nothing you can do in the browser to fix this. You have to wait for the server to reload the file. You can't even delete the file and re-upload it. This could take even longer if you are using a caching server like Cloudflare (it will even survive a server reboot). You could rename it and load a copy.

Open a file with Notepad in C#

System.Diagnostics.Process.Start( "notepad.exe", "text.txt");

Auto detect mobile browser (via user-agent?)

There are open source scripts on Detect Mobile Browser that do this in Apache, ASP, ColdFusion, JavaScript and PHP.

How do I alter the precision of a decimal column in Sql Server?

There may be a better way, but you can always copy the column into a new column, drop it and rename the new column back to the name of the first column.

to wit:

ALTER TABLE MyTable ADD NewColumnName DECIMAL(16, 2);
GO

UPDATE  MyTable
SET     NewColumnName = OldColumnName;
GO

ALTER TABLE CONTRACTS DROP COLUMN OldColumnName;
GO


EXEC sp_rename
    @objname = 'MyTable.NewColumnName',
    @newname = 'OldColumnName',
    @objtype = 'COLUMN'
GO

This was tested on SQL Server 2008 R2, but should work on SQL Server 2000+.

How can I run NUnit tests in Visual Studio 2017?

For anyone having issues with Visual Studio 2019:

I had to first open menu Test ? Windows ? Test Explorer, and run the tests from there, before the option to Run / Debug tests would show up on the right click menu.

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

Add a View:

  1. Right-Click View Folder
  2. Click Add -> View
  3. Click Create a strongly-typed view
  4. Select your User class
  5. Select List as the Scaffold template

Add a controller and action method to call the view:

public ActionResult Index()
{
    var users = DataContext.GetUsers();
    return View(users);
}

How to choose the id generation strategy when using JPA and Hibernate

Basically, you have two major choices:

  • You can generate the identifier yourself, in which case you can use an assigned identifier.
  • You can use the @GeneratedValue annotation and Hibernate will assign the identifier for you.

For the generated identifiers you have two options:

  • UUID identifiers.
  • Numerical identifiers.

For numerical identifiers you have three options:

  • IDENTITY
  • SEQUENCE
  • TABLE

IDENTITY is only a good choice when you cannot use SEQUENCE (e.g. MySQL) because it disables JDBC batch updates.

SEQUENCE is the preferred option, especially when used with an identifier optimizer like pooled or pooled-lo.

TABLE is to be avoided since it uses a separate transaction to fetch the identifier and row-level locks which scales poorly.

Accessing elements by type in javascript

var inputs = document.querySelectorAll("input[type=text]") ||
(function() {
    var ret=[], elems = document.getElementsByTagName('input'), i=0,l=elems.length;
    for (;i<l;i++) {
        if (elems[i].type.toLowerCase() === "text") {
            ret.push(elems[i]);
        }
    }

    return ret;
}());

Parse large JSON file in Nodejs

I had similar requirement, i need to read a large json file in node js and process data in chunks and call a api and save in mongodb. inputFile.json is like:

{
 "customers":[
       { /*customer data*/},
       { /*customer data*/},
       { /*customer data*/}....
      ]
}

Now i used JsonStream and EventStream to achieve this synchronously.

var JSONStream = require("JSONStream");
var es = require("event-stream");

fileStream = fs.createReadStream(filePath, { encoding: "utf8" });
fileStream.pipe(JSONStream.parse("customers.*")).pipe(
  es.through(function(data) {
    console.log("printing one customer object read from file ::");
    console.log(data);
    this.pause();
    processOneCustomer(data, this);
    return data;
  }),
  function end() {
    console.log("stream reading ended");
    this.emit("end");
  }
);

function processOneCustomer(data, es) {
  DataModel.save(function(err, dataModel) {
    es.resume();
  });
}

When is the @JsonProperty property used and what is it used for?

From JsonProperty javadoc,

Defines name of the logical property, i.e. JSON object field name to use for the property. If value is empty String (which is the default), will try to use name of the field that is annotated.

TypeError : Unhashable type

You are creating a set via set(...) call, and set needs hashable items. You can't have set of lists. Because list's arent hashable.

[[(a,b) for a in range(3)] for b in range(3)] is a list. It's not a hashable type. The __hash__ you saw in dir(...) isn't a method, it's just None.

A list comprehension returns a list, you don't need to explicitly use list there, just use:

>>> [[(a,b) for a in range(3)] for b in range(3)]
[[(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)]]

Try those:

>>> a = {1, 2, 3}
>>> b= [1, 2, 3]
>>> type(a)
<class 'set'>
>>> type(b)
<class 'list'>
>>> {1, 2, []}
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> print([].__hash__)
None
>>> [[],[],[]] #list of lists
[[], [], []]
>>> {[], [], []} #set of lists
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'

How to loop through key/value object in Javascript?

Something like this:

setUsers = function (data) {
    for (k in data) {
        user[k] = data[k];
    }
}

Split a vector into chunks

split(x,matrix(1:n,n,length(x))[1:length(x)])

perhaps this is more clear, but the same idea:
split(x,rep(1:n, ceiling(length(x)/n),length.out = length(x)))

if you want it ordered,throw a sort around it

Getting the application's directory from a WPF application

Try this. Don't forget using System.Reflection.

string baseDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);

Setting Windows PATH for Postgres tools

All you need to do is to change the PATH variable to include the bin directory of your PostgreSQL installation.

An explanation on how to change environment variables is here:

http://support.microsoft.com/kb/310519
http://www.computerhope.com/issues/ch000549.htm

To verify that the path is set correctly, you can use:

echo %PATH%

on the commandline.

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

The Philippe solution but cleaner:

My subtraction data is: '2018-09-22T11:05:00.000Z'

import datetime
import pandas as pd

df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)

Cell color changing in Excel using C#

Note: This assumes that you will declare constants for row and column indexes named COLUMN_HEADING_ROW, FIRST_COL, and LAST_COL, and that _xlSheet is the name of the ExcelSheet (using Microsoft.Interop.Excel)

First, define the range:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

Then, set the background color of that range:

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

Finally, set the font color:

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

And here's the code combined:

var columnHeadingsRange = _xlSheet.Range[
    _xlSheet.Cells[COLUMN_HEADING_ROW, FIRST_COL],
    _xlSheet.Cells[COLUMN_HEADING_ROW, LAST_COL]];

columnHeadingsRange.Interior.Color = XlRgbColor.rgbSkyBlue;

columnHeadingsRange.Font.Color = XlRgbColor.rgbWhite;

What is the difference between user and kernel modes in operating systems?

A processor in a computer running Windows has two different modes: user mode and kernel mode. The processor switches between the two modes depending on what type of code is running on the processor. Applications run in user mode, and core operating system components run in kernel mode. While many drivers run in kernel mode, some drivers may run in user mode.

When you start a user-mode application, Windows creates a process for the application. The process provides the application with a private virtual address space and a private handle table. Because an application's virtual address space is private, one application cannot alter data that belongs to another application. Each application runs in isolation, and if an application crashes, the crash is limited to that one application. Other applications and the operating system are not affected by the crash.

In addition to being private, the virtual address space of a user-mode application is limited. A processor running in user mode cannot access virtual addresses that are reserved for the operating system. Limiting the virtual address space of a user-mode application prevents the application from altering, and possibly damaging, critical operating system data.

All code that runs in kernel mode shares a single virtual address space. This means that a kernel-mode driver is not isolated from other drivers and the operating system itself. If a kernel-mode driver accidentally writes to the wrong virtual address, data that belongs to the operating system or another driver could be compromised. If a kernel-mode driver crashes, the entire operating system crashes.

If you are a Windows user once go through this link you will get more.

Communication between user mode and kernel mode

ERROR in ./node_modules/css-loader?

you have to update your node.js and angular/cli.If you update these two things then your project has angular.json file instead of angular-cli.json file.Then add css file into angular.json file.If you add css file into angular-cli.json file instead of angular.json file,then errors are occured.

How to find whether a number belongs to a particular range in Python?

To check whether some number n is in the inclusive range denoted by the two number a and b you do either

if   a <= n <= b:
    print "yes"
else:
    print "no"

use the replace >= and <= with > and < to check whether n is in the exclusive range denoted by a and b (i.e. a and b are not themselves members of the range).

Range will produce an arithmetic progression defined by the two (or three) arguments converted to integers. See the documentation. This is not what you want I guess.

Manually adding a Userscript to Google Chrome

This parameter is is working for me:

--enable-easy-off-store-extension-install

Do the following:

  1. Right click on your "Chrome" icon.
  2. Choose properties
  3. At the end of your target line, place these parameters: --enable-easy-off-store-extension-install
  4. It should look like: chrome.exe --enable-easy-off-store-extension-install
  5. Start Chrome by double-clicking on the icon

How to manually send HTTP POST requests from Firefox or Chrome browser?

CURL is AWESOME to do what you want ! It's a simple but effective command line tool.

Rest implementation test commands :

curl -i -X GET http://rest-api.io/items
curl -i -X GET http://rest-api.io/items/5069b47aa892630aae059584
curl -i -X DELETE http://rest-api.io/items/5069b47aa892630aae059584
curl -i -X POST -H 'Content-Type: application/json' -d '{"name": "New item", "year": "2009"}' http://rest-api.io/items
curl -i -X PUT -H 'Content-Type: application/json' -d '{"name": "Updated item", "year": "2010"}' http://rest-api.io/items/5069b47aa892630aae059584

Python 3: ImportError "No Module named Setuptools"

The solution which worked for me was to upgrade my setuptools:

python3 -m pip install --upgrade pip setuptools wheel

Difference between IISRESET and IIS Stop-Start command

Take IISReset as a suite of commands that helps you manage IIS start / stop etc.

Which means you need to specify option (/switch) what you want to do to carry any operation.

Default behavior OR default switch is /restart with iisreset so you do not need to run command twice with /start and /stop.

Hope this clarifies your question. For reference the output of iisreset /? is:

IISRESET.EXE (c) Microsoft Corp. 1998-2005

Usage:
iisreset [computername]

    /RESTART            Stop and then restart all Internet services.
    /START              Start all Internet services.
    /STOP               Stop all Internet services.
    /REBOOT             Reboot the computer.
    /REBOOTONERROR      Reboot the computer if an error occurs when starting,
                        stopping, or restarting Internet services.
    /NOFORCE            Do not forcefully terminate Internet services if
                        attempting to stop them gracefully fails.
    /TIMEOUT:val        Specify the timeout value ( in seconds ) to wait for
                        a successful stop of Internet services. On expiration
                        of this timeout the computer can be rebooted if
                        the /REBOOTONERROR parameter is specified.
                        The default value is 20s for restart, 60s for stop,
                        and 0s for reboot.
    /STATUS             Display the status of all Internet services.
    /ENABLE             Enable restarting of Internet Services
                        on the local system.
    /DISABLE            Disable restarting of Internet Services
                        on the local system.

Printing a java map Map<String, Object> - How?

There is a get method in HashMap:

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

Properties order in Margin

There are three unique situations:

  • 4 numbers, e.g. Margin="a,b,c,d".
  • 2 numbers, e.g. Margin="a,b".
  • 1 number, e.g. Margin="a".

4 Numbers

If there are 4 numbers, then its left, top, right, bottom (a clockwise circle starting from the middle left margin). First number is always the "West" like "WPF":

<object Margin="left,top,right,bottom"/>

Example: if we use Margin="10,20,30,40" it generates:

enter image description here

2 Numbers

If there are 2 numbers, then the first is left & right margin thickness, the second is top & bottom margin thickness. First number is always the "West" like "WPF":

<object Margin="a,b"/> // Equivalent to Margin="a,b,a,b".

Example: if we use Margin="10,30", the left & right margin are both 10, and the top & bottom are both 30.

enter image description here

1 Number

If there is 1 number, then the number is repeated (its essentially a border thickness).

<object Margin="a"/> // Equivalent to Margin="a,a,a,a".

Example: if we use Margin="20" it generates:

enter image description here

Update 2020-05-27

Have been working on a large-scale WPF application for the past 5 years with over 100 screens. Part of a team of 5 WPF/C#/Java devs. We eventually settled on either using 1 number (for border thickness) or 4 numbers. We never use 2. It is consistent, and seems to be a good way to reduce cognitive load when developing.


The rule:

All width numbers start on the left (the "West" like "WPF") and go clockwise (if two numbers, only go clockwise twice, then mirror the rest).

What characters are allowed in an email address?

Gmail will only allow + sign as special character and in some cases (.) but any other special characters are not allowed at Gmail. RFC's says that you can use special characters but you should avoid sending mail to Gmail with special characters.

Getting "type or namespace name could not be found" but everything seems ok?

This one worked for me. In your class, where the class name is defined, eg: Public class ABC, remove one character and wait a little. You error list will increase because you have changed the name. Now put back the character that you have typed. This worked for me, hopefully it will work for you too. Good Luck!!!

Spring cron expression for every after 30 minutes

<property name="cronExpression" value="0 0/30 * * * ?" />

Find Number of CPUs and Cores per CPU using Command Prompt

You can also enter msinfo32 into the command line.

It will bring up all your system information. Then, in the find box, just enter processor and it will show you your cores and logical processors for each CPU. I found this way to be easiest.

How to find item with max value using linq?

With EF or LINQ to SQL:

var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();

With LINQ to Objects I suggest to use morelinq extension MaxBy (get morelinq from nuget):

var item = items.MaxBy(i => i.Value);

How can I get a list of locally installed Python modules?

If we need to list the installed packages in the Python shell, we can use the help command as follows

>>> help('modules package')

How to position three divs in html horizontally?

You add a

float: left;

to the style of the 3 elements and make sure the parent container has

overflow: hidden; position: relative;

this makes sure the floats take up actual space.

<html>
    <head>
        <title>Website Title </title>
    </head>
    <body>
        <div id="the-whole-thing" style="position: relative; overflow: hidden;">
            <div id="leftThing" style="position: relative; width: 25%; background-color: blue; float: left;">
                Left Side Menu
            </div>
            <div id="content" style="position: relative; width: 50%; background-color: green; float: left;">
                Random Content
            </div>
            <div id="rightThing" style="position: relative; width: 25%; background-color: yellow; float: left;">
                Right Side Menu
            </div>
        </div>
    </body>
</html>

Also please note that the width: 100% and height: 100% need to be removed from the container, otherwise the 3rd block will wrap to a 2nd line.

How to list all users in a Linux group?

lid -g groupname | cut -f1 -d'(' 

How do I access properties of a javascript object if I don't know the names?

function getDetailedObject(inputObject) {
    var detailedObject = {}, properties;

    do {
        properties = Object.getOwnPropertyNames( inputObject );
        for (var o in properties) {
            detailedObject[properties[o]] = inputObject[properties[o]];
        }
    } while ( inputObject = Object.getPrototypeOf( inputObject ) );

    return detailedObject;
}

This will get all properties and their values (inherited or own, enumerable or not) in a new object. original object is untouched. Now new object can be traversed using

var obj = { 'b': '4' }; //example object
var detailedObject = getDetailedObject(obj);
for(var o in detailedObject) {
    console.log('key: ' + o + '   value: ' + detailedObject[o]);
}

notifyDataSetChange not working from custom adapter

If by any chance you landed on this thread and wondering why adapter.invaidate() or adapter.clear() methods are not present in your case then maybe because you might be using RecyclerView.Adapter instead of BaseAdapter which is used by the asker of this question. If clearing the list or arraylist not resolving your problem then it may happen that you are making two or more instances of the adapter for ex.:

MainActivity

...

adapter = new CustomAdapter(list);
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);

...

and
SomeFragment

...

adapter = new CustomAdapter(newList);
adapter.notifyDataSetChanged();

...

If in the second case you are expecting a change in the list of inflated views in recycler view then it is not gonna happen as in the second time a new instance of the adapter is created which is not attached to the recycler view. Setting notifyDataSetChanged in the second adapter is not gonna change the content of recycer view. For that make a new instance of the recycler view in SomeFragment and attach it to the new instance of the adapter.

SomeFragment

...

recyclerView = new RecyclerView();
adapter = new CustomAdapter();
recyclerView.setAdapter(adapter);

...

Although, I don't recommend making multiple instances of the same adapter and recycler view.

Where does pip install its packages?

pip show <package name> will provide the location for Windows and macOS, and I'm guessing any system. :)

For example:

> pip show cvxopt
Name: cvxopt
Version: 1.2.0
...
Location: /usr/local/lib/python2.7/site-packages

Confirmation before closing of tab/browser

If you want to ask based on condition:

var ask = true
window.onbeforeunload = function (e) {
    if(!ask) return null
    e = e || window.event;
    //old browsers
    if (e) {e.returnValue = 'Sure?';}
    //safari, chrome(chrome ignores text)
    return 'Sure?';
};

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))