Programs & Examples On #Httphandlerfactory

500 Error on AppHarbor but downloaded build works on my machine

Just a wild guess: (not much to go on) but I have had similar problems when, for example, I was using the IIS rewrite module on my local machine (and it worked fine), but when I uploaded to a host that did not have that add-on module installed, I would get a 500 error with very little to go on - sounds similar. It drove me crazy trying to find it.

So make sure whatever options/addons that you might have and be using locally in IIS are also installed on the host.

Similarly, make sure you understand everything that is being referenced/used in your web.config - that is likely the problem area.

Cell Style Alignment on a range

For SpreadSheetGear users (a C# framework for interacting easier with spreadsheets) try this:

workbook.Worksheets[0].Cells["B1:B4"].HorizontalAlignment = HAlign.Center;. This will align all the cells in your sheet from B1 to B4 (column 2- row 1 through 4).

Redirect Windows cmd stdout and stderr to a single file

Correct, file handle 1 for the process is STDOUT, redirected by the 1> or by > (1 can be omitted, by convention, the command interpreter [cmd.exe] knows to handle that). File handle 2 is STDERR, redirected by 2>.

Note that if you're using these to make log files, then unless you're sending the outut to _uniquely_named_ (eg date-and-time-stamped) log files, then if you run the same process twice, the redirected will overwrite (replace) the previous log file.

The >> (for either STDOUT or STDERR) will APPEND not REPLACE the file. So you get a cumulative logfile, showwing the results from all runs of the process - typically more useful.

Happy trails...

Android Whatsapp/Chat Examples

If you are looking to create an instant messenger for Android, this code should get you started somewhere.

Excerpt from the source :

This is a simple IM application runs on Android, application makes http request to a server, implemented in php and mysql, to authenticate, to register and to get the other friends' status and data, then it communicates with other applications in other devices by socket interface.

EDIT : Just found this! Maybe it's not related to WhatsApp. But you can use the source to understand how chat applications are programmed.

There is a website called Scringo. These awesome people provide their own SDK which you can integrate in your existing application to exploit cool features like radaring, chatting, feedback, etc. So if you are looking to integrate chat in application, you could just use their SDK. And did I say the best part? It's free!

*UPDATE : * Scringo services will be closed down on 15 February, 2015.

Display fullscreen mode on Tkinter

Yeah mate i was trying to do the same in windows, and what helped me was a bit of lambdas with the root.state() method.

root = Tk()
root.bind('<Escape>', lambda event: root.state('normal'))
root.bind('<F11>', lambda event: root.state('zoomed'))

How to check if memcache or memcached is installed for PHP?

this is my test function that I use to check Memcache on the server

<?php     
public function test()
 {
    // memcache test - make sure you have memcache extension installed and the deamon is up and running
    $memcache = new Memcache;
    $memcache->connect('localhost', 11211) or die ("Could not connect");

    $version = $memcache->getVersion();
    echo "Server's version: ".$version."<br/>\n";

    $tmp_object = new stdClass;
    $tmp_object->str_attr = 'test';
    $tmp_object->int_attr = 123;

    $memcache->set('key', $tmp_object, false, 10) or die ("Failed to save data at the server");
    echo "Store data in the cache (data will expire in 10 seconds)<br/>\n";

    $get_result = $memcache->get('key');
    echo "Data from the cache:<br/>\n";

    var_dump($get_result);
 }

if you see something like this

    Server's version: 1.4.5_4_gaa7839e
    Store data in the cache (data will expire in 10 seconds)
    Data from the cache:
    object(stdClass)#3 (2) { ["str_attr"]=> string(4) "test" ["int_attr"]=> int(123) }

it means that everything is okay

Cheers!

Android Studio Stuck at Gradle Download on create new project

I found the same issue happening on my laptop, despite waiting for quite a long time. This is what I did and it worked for me. Just force close the Android Studio and launch it again. This time, just open the existing project and let it take care of finishing up the process of building/downloading.

Another option that you could possibly try is that if you look into File --> Settings, there is an option for Gradle location. You could go to the Gradle download site, download a local distribution of Gradle and point the Gradle location to that local directory.

ReferenceError: variable is not defined

Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.

Define variable with var outside the function (and of course before it) and then assign 10 to it inside function:

var value;
$(function() {
  value = "10";
});
console.log(value); // 10

Note that you shouldn't omit the first line in this code (var value;), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;) and assigning value to a variable (variable = value;) are two different things. You can't assign value to variable that you haven't defined.

It might be irrelevant here, but $(function() {}) is a shortcut for $(document).ready(function() {}), which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined until it has loaded, so console.log(value); placed right after $(function() {}) will return undefined. In other words, it would execute in following order:

var value;
console.log(value);
value = "10";

See also:

How to use TLS 1.2 in Java 6

In case you need to access a specific set of remote services you could use an intermediate reverse-proxy, to perform tls1.2 for you. This would save you from trying to patch or upgrade java1.6.

e.g. app -> proxy:http(5500)[tls-1.2] -> remote:https(443)

Configuration in its simplest form (one port per service) for apache httpd is:

Listen 127.0.0.1:5000
<VirtualHost *:5500>
    SSLProxyEngine On
    ProxyPass / https://remote-domain/
    ProxyPassReverse / https://remote-domain/
</VirtualHost>

Then instead of accessing https://remote-domain/ you access http://localhost:5500/

How to check for empty value in Javascript?

In my opinion, using "if(value)" to judge a value whether is an empty value is not strict, because the result of "v?true:false" is false when the value of v is 0(0 is not an empty value). You can use this function:

const isEmptyValue = (value) => {
    if (value === '' || value === null || value === undefined) {
        return true
    } else {
        return false
    }
}

Merging two images with PHP

You can try my function for merging images horizontally or vertically without changing image ratio. just copy paste will work.

function merge($filename_x, $filename_y, $filename_result, $mergeType = 0) {

    //$mergeType 0 for horizandal merge 1 for vertical merge

 // Get dimensions for specified images
 list($width_x, $height_x) = getimagesize($filename_x);
 list($width_y, $height_y) = getimagesize($filename_y);


$lowerFileName = strtolower($filename_x); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    $image_x = imagecreatefromjpeg($filename_x);    
}else if(substr_count($lowerFileName, '.png')>0){
    $image_x = imagecreatefrompng($filename_x); 
}else if(substr_count($lowerFileName, '.gif')>0){
    $image_x = imagecreatefromgif($filename_x); 
}


$lowerFileName = strtolower($filename_y); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    $image_y = imagecreatefromjpeg($filename_y);    
}else if(substr_count($lowerFileName, '.png')>0){
    $image_y = imagecreatefrompng($filename_y); 
}else if(substr_count($lowerFileName, '.gif')>0){
    $image_y = imagecreatefromgif($filename_y); 
}


if($mergeType==0){
    //for horizandal merge
     if($height_y<$height_x){
        $new_height = $height_y;

        $new_x_height = $new_height;
        $precentageReduced = ($height_x - $new_height)/($height_x/100);
        $new_x_width = ceil($width_x - (($width_x/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_x_width, $new_x_height);
        imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
        $image_x = $tmp;

        $height_x = $new_x_height;
        $width_x = $new_x_width;

     }else{
        $new_height = $height_x;

        $new_y_height = $new_height;
        $precentageReduced = ($height_y - $new_height)/($height_y/100);
        $new_y_width = ceil($width_y - (($width_y/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_y_width, $new_y_height);
        imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
        $image_y = $tmp;

        $height_y = $new_y_height;
        $width_y = $new_y_width;

     }

     $new_width = $width_x + $width_y;

     $image = imagecreatetruecolor($new_width, $new_height);

    imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
    imagecopy($image, $image_y, $width_x, 0, 0, 0, $width_y, $height_y);

}else{


    //for verical merge
    if($width_y<$width_x){
        $new_width = $width_y;

        $new_x_width = $new_width;
        $precentageReduced = ($width_x - $new_width)/($width_x/100);
        $new_x_height = ceil($height_x - (($height_x/100) * $precentageReduced));

        $tmp = imagecreatetruecolor($new_x_width, $new_x_height);
        imagecopyresampled($tmp, $image_x, 0, 0, 0, 0, $new_x_width, $new_x_height, $width_x, $height_x);
        $image_x = $tmp;

        $width_x = $new_x_width;
        $height_x = $new_x_height;

     }else{
        $new_width = $width_x;

        $new_y_width = $new_width;
        $precentageReduced = ($width_y - $new_width)/($width_y/100);
        $new_y_height = ceil($height_y - (($height_y/100) * $precentageReduced));

         $tmp = imagecreatetruecolor($new_y_width, $new_y_height);
        imagecopyresampled($tmp, $image_y, 0, 0, 0, 0, $new_y_width, $new_y_height, $width_y, $height_y);
        $image_y = $tmp;

        $width_y = $new_y_width;
        $height_y = $new_y_height;

     }

     $new_height = $height_x + $height_y;

     $image = imagecreatetruecolor($new_width, $new_height);

    imagecopy($image, $image_x, 0, 0, 0, 0, $width_x, $height_x);
    imagecopy($image, $image_y, 0, $height_x, 0, 0, $width_y, $height_y);

}





$lowerFileName = strtolower($filename_result); 
if(substr_count($lowerFileName, '.jpg')>0 || substr_count($lowerFileName, '.jpeg')>0){
    imagejpeg($image, $filename_result);
}else if(substr_count($lowerFileName, '.png')>0){
    imagepng($image, $filename_result);
}else if(substr_count($lowerFileName, '.gif')>0){
    imagegif($image, $filename_result); 
}


 // Clean up
 imagedestroy($image);
 imagedestroy($image_x);
 imagedestroy($image_y);

}


merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged_har.jpg',0); //merge horizontally
merge('images/h_large.jpg', 'images/v_large.jpg', 'images/merged.jpg',1); //merge vertically

How to generate a random string of 20 characters

public String randomString(String chars, int length) {
  Random rand = new Random();
  StringBuilder buf = new StringBuilder();
  for (int i=0; i<length; i++) {
    buf.append(chars.charAt(rand.nextInt(chars.length())));
  }
  return buf.toString();
}

Replace \n with <br />

I know this is an old thread but I tried the suggested answers and unfortunately simply replacing line breaks with <br /> didn't do what I needed it to. It simply rendered them literally as text.

One solution would have been to disable autoescape like this: {% autoescape false %}{{ mystring }}{% endautoescape %} and this works fine but this is no good if you have user-provided content. So this was also not a solution for me.

So this is what I used:

In Python:

newvar = mystring.split('\n')

And then, passing newvar into my Jinja template:

{% for line in newvar %}
    <br />{{ line }}
{% endfor %}

Python Pandas : group by in group by and average?

I would simply do this, which literally follows what your desired logic was:

df.groupby(['org']).mean().groupby(['cluster']).mean()

Android WebView not loading URL

Just as an alternative solution:

For me webView.getSettings().setUserAgentString("Android WebView") did the trick.

I already had implemented INTERNET permission and WebViewClient as well as WebChromeClient

GitLab remote: HTTP Basic: Access denied and fatal Authentication

If you are using git > 2.11 and using Kerberos to interact with Gitlab you need set this configuration in your local git to avoid the remote: HTTP Basic: Access denied error.

$ git config --global http.emptyAuth true

Source

How to make a DIV not wrap?

The combo you need is

white-space: nowrap

on the parent and

display: inline-block; // or inline

on the children

Rename file with Git

Note that, from March 15th, 2013, you can move or rename a file directly from GitHub:

(you don't even need to clone that repo, git mv xx and git push back to GitHub!)

renaming

You can also move files to entirely new locations using just the filename field.
To navigate down into a folder, just type the name of the folder you want to move the file into followed by /.
The folder can be one that’s already part of your repository, or it can even be a brand-new folder that doesn’t exist yet!

moving

How to stretch a fixed number of horizontal navigation items evenly and fully across a specified container

I'm hesitant to offer this as it misuses ye olde html. It's not a GOOD solution but it is a solution: use a table.

CSS:

table.navigation {
    width: 990px;
}
table.navigation td {
    text-align: center;
}

HTML:

<table cellpadding="0" cellspacing="0" border="0" class="navigation">
    <tr>
        <td>HOME</td>
        <td>ABOUT</td>
        <td>BASIC SERVICES</td>
        <td>SPECIALTY SERVICES</td>
        <td>OUR STAFF</td>
        <td>CONTACT US</td>
    </tr>
</table>

This is not what tables were created to do but until we can reliably perform the same action in a better way I guess it is just about permissable.

Binding a WPF ComboBox to a custom list

I had what at first seemed to be an identical problem, but it turned out to be due to an NHibernate/WPF compatibility issue. The problem was caused by the way WPF checks for object equality. I was able to get my stuff to work by using the object ID property in the SelectedValue and SelectedValuePath properties.

<ComboBox Name="CategoryList"
          DisplayMemberPath="CategoryName"
          SelectedItem="{Binding Path=CategoryParent}"
          SelectedValue="{Binding Path=CategoryParent.ID}"
          SelectedValuePath="ID">

See the blog post from Chester, The WPF ComboBox - SelectedItem, SelectedValue, and SelectedValuePath with NHibernate, for details.

Unfinished Stubbing Detected in Mockito

For those who use com.nhaarman.mockitokotlin2.mock {}

This error occurs when, for example, we create a mock inside another mock

mock {
    on { x() } doReturn mock {
        on { y() } doReturn z()
    }
}

The solution to this is to create the child mock in a variable and use the variable in the scope of the parent mock to prevent the mock creation from being explicitly nested.

val liveDataMock = mock {
        on { y() } doReturn z()
}
mock {
    on { x() } doReturn liveDataMock
}

GL

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Deny all, allow only one IP through htaccess

If you want to use mod_rewrite for access control you can use condition like user agent, http referrer, remote addr etc.

Example

RewriteCond %{REMOTE_ADDR} !=*.*.*.* #you ip address
RewriteRule ^$ - [F]

Refrences:

How to convert java.lang.Object to ArrayList?

I hope this will be help you

import java.util.ArrayList; 
public class Demo {

 public static void main(String[] args) {
    Object obj2 =null;
    ArrayList al1 = (ArrayList) obj2;
    al1 = (ArrayList) obj2;
    System.out.println("List2 Value: " + al1);
    }
 }

obj2 Object is default null before you cast it to ArrayList. That's why print 'al1' as null.

How do I get bit-by-bit data from an integer value in C?

@prateek thank you for your help. I rewrote the function with comments for use in a program. Increase 8 for more bits (up to 32 for an integer).

std::vector <bool> bits_from_int (int integer)    // discern which bits of PLC codes are true
{
    std::vector <bool> bool_bits;

    // continously divide the integer by 2, if there is no remainder, the bit is 1, else it's 0
    for (int i = 0; i < 8; i++)
    {
        bool_bits.push_back (integer%2);    // remainder of dividing by 2
        integer /= 2;    // integer equals itself divided by 2
    }

    return bool_bits;
}

How to export iTerm2 Profiles

It isn't the most obvious workflow. You first have to click "Load preferences from a custom folder or URL". Select the folder you want them saved in; I keep an appsync folder in Dropbox for these sorts of things. Once you have selected the folder, you can click "Save settings to Folder". On a new machine / fresh install of your OS, you can now load these settings from the folder. At first I was sure that loading preferences would wipe out my previous settings, but it didn't.

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

Browser detection

if (Request.Browser.Type.Contains("Firefox")) // replace with your check
{
    ...
} 
else if (Request.Browser.Type.ToUpper().Contains("IE")) // replace with your check
{
    if (Request.Browser.MajorVersion  < 7)
    { 
        DoSomething(); 
    }
    ...
}
else { }

React JS onClick event handler

Use ECMA2015. Arrow functions make "this" a lot more intuitive.

import React from 'react';


class TestApp extends React.Component {
   getComponent(e, index) {
       $(e.target).css({
           'background-color': '#ccc'
       });
   }
   render() {
       return (
           <div>
             <ul>
               <li onClick={(e) => this.getComponent(e, 1)}>Component 1</li>
               <li onClick={(e) => this.getComponent(e, 2)}>Component 2</li>
               <li onClick={(e) => this.getComponent(e, 3)}>Component 3</li>
             </ul>
           </div>
       );
   }
});
React.renderComponent(<TestApp /> , document.getElementById('soln1'));`

Can we write our own iterator in Java?

Here is the complete answer to the question.

import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;

class ListIterator implements Iterator<String>{
    List<String> list;
    int pos = 0;

    public ListIterator(List<String> list) {
        this.list = list;
    }

    @Override
    public boolean hasNext() {
        while(pos < list.size()){
            if (list.get(pos).startsWith("a"))
                return true;
            pos++;
        }
        return false;

    }

    @Override
    public String next() {
        if (hasNext())
            return list.get(pos++);
        throw new NoSuchElementException();
    }
}

public class IteratorTest {

    public static void main(String[] args) {
        List<String> list = Arrays.asList("alice", "bob", "abigail", "charlie");
        ListIterator itr = new ListIterator(list);

        while(itr.hasNext())
            System.out.println(itr.next()); // prints alice, abigail
    }
}
  • ListIterator is the iterator for the array which returns the elements that start with 'a'.
  • There is no need for implementing an Iterable interface. But that is a possibility.
  • There is no need to implement this generically.
  • It fully satisfies the contract for hasNext() and next(). ie if hasNext() says there are still elements, next() will return those elements. And if hasNext() says no more elements, it returns a valid NoSuchElementException exception.

Visual studio code terminal, how to run a command with administrator rights?

Running as admin didn't help me. (also got errors with syscall: rename)

Turns out this error can also occur if files are locked by Windows.

This can occur if :

  • You are actually running the project
  • You have files open in both Visual Studio and VSCode.

Running as admin doesn't get around windows file locking.

I created a new project in VS2017 and then switched to VSCode to try to add more packages. After stopping the project from running and closing VS2017 it was able to complete without error

Disclaimer: I'm not exactly sure if this means running as admin isn't necessary, but try to avoid it if possible to avoid the possibility of some rogue package doing stuff it isn't meant to.

Getting the Username from the HKEY_USERS values

You can use the command PSGetSid from Microsoft's SysInternals team.

Download URL: http://technet.microsoft.com/en-gb/sysinternals/bb897417.aspx

Usage:

psgetsid [\\computer[,computer[,...] | @file] [-u username [-p password]]] [account|SID]
-u  Specifies optional user name for login to remote computer.
-p  Specifies optional password for user name. If you omit this you will be prompted to enter a hidden password.
Account PsGetSid will report the SID for the specified user account rather than the computer.
SID PsGetSid will report the account for the specified SID.
Computer    Direct PsGetSid to perform the command on the remote computer or computers specified. If you omit the computer name PsGetSid runs the command on the local system, and if you specify a wildcard (\\*), PsGetSid runs the command on all computers in the current domain.
@file   PsGetSid will execute the command on each of the computers listed in the file.

Example:

psgetsid S-1-5-21-583907252-682003330-839522115-63941

NB:

  • Where the user is a domain/AD(LDAP) user, running this on any computer on the domain should give the same results.
  • Where the user is local to the machine the command should either be run on that machine, or you should specify the computer via the optional parameter.

Update

If you use PowerShell, the following may be useful for resolving any AD users listed:

#create a drive for HKEY USERS:
New-PSDrive -PSProvider Registry -Name HKU -Root HKEY_USERS -ErrorAction SilentlyContinue

#List all immediate subfolders
#where they're a folder (not a key)
#and they's an SID (i.e. exclude .DEFAULT and SID_Classes entries)
#return the SID
#and return the related AD entry (should one exist).
Get-ChildItem -Path 'HKU:\' `
| ?{($_.PSIsContainer -eq $true) `
-and ($_.PSChildName -match '^S-[\d-]+$')} `
| select @{N='SID';E={$_.PSChildName}} `
, @{N='Name';E={Get-ADUser $_.PSChildName | select -expand Name}}

You could also refine the SID filter further to only pull back those SIDs which will resolve to an AD account if you wished; more on the SID structure here: https://technet.microsoft.com/en-us/library/cc962011.aspx

addEventListener, "change" and option selection

The problem is that you used the select option, this is where you went wrong. Select signifies that a textbox or textArea has a focus. What you need to do is use change. "Fires when a new choice is made in a select element", also used like blur when moving away from a textbox or textArea.

function start(){
      document.getElementById("activitySelector").addEventListener("change", addActivityItem, false);
      }

function addActivityItem(){
      //option is selected
      alert("yeah");
}

window.addEventListener("load", start, false);

Accessing MP3 metadata with Python

I used eyeD3 the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to install using pip or download the tar and execute python setup.py install from the source folder.

Relevant examples from the website are below.

Reading the contents of an mp3 file containing either v1 or v2 tag info:

 import eyeD3
 tag = eyeD3.Tag()
 tag.link("/some/file.mp3")
 print tag.getArtist()
 print tag.getAlbum()
 print tag.getTitle()

Read an mp3 file (track length, bitrate, etc.) and access it's tag:

if eyeD3.isMp3File(f):
     audioFile = eyeD3.Mp3AudioFile(f)
     tag = audioFile.getTag()

Specific tag versions can be selected:

 tag.link("/some/file.mp3", eyeD3.ID3_V2)
 tag.link("/some/file.mp3", eyeD3.ID3_V1)
 tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION)  # The default.

Or you can iterate over the raw frames:

 tag = eyeD3.Tag()
 tag.link("/some/file.mp3")
 for frame in tag.frames:
    print frame

Once a tag is linked to a file it can be modified and saved:

 tag.setArtist(u"Cro-Mags")
 tag.setAlbum(u"Age of Quarrel")
 tag.update()

If the tag linked in was v2 and you'd like to save it as v1:

 tag.update(eyeD3.ID3_V1_1)

Read in a tag and remove it from the file:

 tag.link("/some/file.mp3")
 tag.remove()
 tag.update()

Add a new tag:

 tag = eyeD3.Tag()
 tag.link('/some/file.mp3')    # no tag in this file, link returned False
 tag.header.setVersion(eyeD3.ID3_V2_3)
 tag.setArtist('Fugazi')
 tag.update()

How to remove specific object from ArrayList in Java?

simple use remove() function. and pass object as param u want to remove. ur arraylist.remove(obj)

Removing NA observations with dplyr::filter()

For example:

you can use:

df %>% filter(!is.na(a))

to remove the NA in column a.

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

The solution I opted for was to format the date with the mysql query :

String l_mysqlQuery = "SELECT DATE_FORMAT(time, '%Y-%m-%d %H:%i:%s') FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

I had the exact same issue. Even though my mysql table contains dates formatted as such : 2017-01-01 21:02:50

String l_mysqlQuery = "SELECT time FROM uld_departure;"
l_importedTable = fStatement.executeQuery( l_mysqlQuery );
System.out.println(l_importedTable.getString( timeIndex));

was returning a date formatted as such : 2017-01-01 21:02:50.0

Load RSA public key from file

Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/

   import java.io.DataInputStream;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.security.KeyFactory;
    import java.security.NoSuchAlgorithmException;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.interfaces.RSAPublicKey;
    import java.security.spec.InvalidKeySpecException;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.X509EncodedKeySpec;

    public class Demo {

        public static final String PRIVATE_KEY="/home/user/private.der";
        public static final String PUBLIC_KEY="/home/user/public.der";

        public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
            //get the private key
            File file = new File(PRIVATE_KEY);
            FileInputStream fis = new FileInputStream(file);
            DataInputStream dis = new DataInputStream(fis);

            byte[] keyBytes = new byte[(int) file.length()];
            dis.readFully(keyBytes);
            dis.close();

            PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
            KeyFactory kf = KeyFactory.getInstance("RSA");
            RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
            System.out.println("Exponent :" + privKey.getPrivateExponent());
            System.out.println("Modulus" + privKey.getModulus());

            //get the public key
            File file1 = new File(PUBLIC_KEY);
            FileInputStream fis1 = new FileInputStream(file1);
            DataInputStream dis1 = new DataInputStream(fis1);
            byte[] keyBytes1 = new byte[(int) file1.length()];
            dis1.readFully(keyBytes1);
            dis1.close();

            X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
            KeyFactory kf1 = KeyFactory.getInstance("RSA");
            RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);

            System.out.println("Exponent :" + pubKey.getPublicExponent());
            System.out.println("Modulus" + pubKey.getModulus());
        }
    }

How to convert list data into json in java

Try these simple steps:

ObjectMapper mapper = new ObjectMapper();
String newJsonData = mapper.writeValueAsString(cartList);
return newJsonData;
ObjectMapper() is com.fasterxml.jackson.databind.ObjectMapper.ObjectMapper();

Error: Segmentation fault (core dumped)

There is one more reason for such failure which I came to know when mine failed

  • You might be working with a lot of data and your RAM is full

This might not apply in this case but it also throws the same error and since this question comes up on top for this error, I have added this answer here.

How to work on UAC when installing XAMPP

Basically there's three things you can do

  1. Ensure that your user account has administrator privilege.
  2. Disable User Account Control (UAC).
  3. Install in C://xampp.

I've just writen an answer to a very similar answer here where I explain how you can disable UAC since Windows 8.

LINQ where clause with lambda expression having OR clauses and null values returning incomplete results

Your second delegate is not a rewrite of the first in anonymous delegate (rather than lambda) format. Look at your conditions.

First:

x.ID == packageId || x.Parent.ID == packageId || x.Parent.Parent.ID == packageId

Second:

(x.ID == packageId) || (x.Parent != null && x.Parent.ID == packageId) || 
(x.Parent != null && x.Parent.Parent != null && x.Parent.Parent.ID == packageId)

The call to the lambda would throw an exception for any x where the ID doesn't match and either the parent is null or doesn't match and the grandparent is null. Copy the null checks into the lambda and it should work correctly.

Edit after Comment to Question

If your original object is not a List<T>, then we have no way of knowing what the return type of FindAll() is, and whether or not this implements the IQueryable interface. If it does, then that likely explains the discrepancy. Because lambdas can be converted at compile time into an Expression<Func<T>> but anonymous delegates cannot, then you may be using the implementation of IQueryable when using the lambda version but LINQ-to-Objects when using the anonymous delegate version.

This would also explain why your lambda is not causing a NullReferenceException. If you were to pass that lambda expression to something that implements IEnumerable<T> but not IQueryable<T>, runtime evaluation of the lambda (which is no different from other methods, anonymous or not) would throw a NullReferenceException the first time it encountered an object where ID was not equal to the target and the parent or grandparent was null.

Added 3/16/2011 8:29AM EDT

Consider the following simple example:

IQueryable<MyObject> source = ...; // some object that implements IQueryable<MyObject>

var anonymousMethod =  source.Where(delegate(MyObject o) { return o.Name == "Adam"; });    
var expressionLambda = source.Where(o => o.Name == "Adam");

These two methods produce entirely different results.

The first query is the simple version. The anonymous method results in a delegate that's then passed to the IEnumerable<MyObject>.Where extension method, where the entire contents of source will be checked (manually in memory using ordinary compiled code) against your delegate. In other words, if you're familiar with iterator blocks in C#, it's something like doing this:

public IEnumerable<MyObject> MyWhere(IEnumerable<MyObject> dataSource, Func<MyObject, bool> predicate)
{
    foreach(MyObject item in dataSource)
    {
        if(predicate(item)) yield return item;
    }
}

The salient point here is that you're actually performing your filtering in memory on the client side. For example, if your source were some SQL ORM, there would be no WHERE clause in the query; the entire result set would be brought back to the client and filtered there.

The second query, which uses a lambda expression, is converted to an Expression<Func<MyObject, bool>> and uses the IQueryable<MyObject>.Where() extension method. This results in an object that is also typed as IQueryable<MyObject>. All of this works by then passing the expression to the underlying provider. This is why you aren't getting a NullReferenceException. It's entirely up to the query provider how to translate the expression (which, rather than being an actual compiled function that it can just call, is a representation of the logic of the expression using objects) into something it can use.

An easy way to see the distinction (or, at least, that there is) a distinction, would be to put a call to AsEnumerable() before your call to Where in the lambda version. This will force your code to use LINQ-to-Objects (meaning it operates on IEnumerable<T> like the anonymous delegate version, not IQueryable<T> like the lambda version currently does), and you'll get the exceptions as expected.

TL;DR Version

The long and the short of it is that your lambda expression is being translated into some kind of query against your data source, whereas the anonymous method version is evaluating the entire data source in memory. Whatever is doing the translating of your lambda into a query is not representing the logic that you're expecting, which is why it isn't producing the results you're expecting.

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

Use of String.Format in JavaScript?

Just make and use this function:

function format(str, args) {
   for (i = 0; i < args.length; i++)
      str = str.replace("{" + i + "}", args[i]);
   return str;
}

If you don't want to change the str parameter, then before the for loop, clone (duplicate) it to a new string (make a new copy of str), and set the copy in the for loop and at last return it instead of the parameter itself.

In C# (Sharp) it is simple create to a copy by just calling String.Clone(), but I don't know how in JavaScript, but you can search on Google or surf on the Internet and learn ways to do it.

I just gave you my idea about string format in JavaScript.

How to add new elements to an array?

There are many ways to add an element to an array. You can use a temp List to manage the element and then convert it back to Array or you can use the java.util.Arrays.copyOf and combine it with generics for better results.

This example will show you how:

public static <T> T[] append2Array(T[] elements, T element)
{
    T[] newArray = Arrays.copyOf(elements, elements.length + 1);
    newArray[elements.length] = element;

    return newArray;
}

To use this method you just need to call it like this:

String[] numbers = new String[]{"one", "two", "three"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(numbers, "four");
System.out.println(Arrays.toString(numbers));

If you want to merge two array you can modify the previous method like this:

public static <T> T[] append2Array(T[] elements, T[] newElements)
{
    T[] newArray = Arrays.copyOf(elements, elements.length + newElements.length);
    System.arraycopy(newElements, 0, newArray, elements.length, newElements.length);

    return newArray;
}

Now you can call the method like this:

String[] numbers = new String[]{"one", "two", "three"};
String[] moreNumbers = new String[]{"four", "five", "six"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(numbers, moreNumbers);
System.out.println(Arrays.toString(numbers));

As I mentioned, you also may use List objects. However, it will require a little hack to cast it safe like this:

public static <T> T[] append2Array(Class<T[]> clazz, List<T> elements, T element)
{
    elements.add(element);
    return clazz.cast(elements.toArray());
}

Now you can call the method like this:

String[] numbers = new String[]{"one", "two", "three"};
System.out.println(Arrays.toString(numbers));
numbers = append2Array(String[].class, Arrays.asList(numbers), "four");
System.out.println(Arrays.toString(numbers));

Creating an Array from a Range in VBA

Adding to @Vityata 's answer, below is the function I use to convert a row / column vector in a 1D array:

Function convertVecToArr(ByVal rng As Range) As Variant
'convert two dimension array into a one dimension array
    
    Dim arr() As Variant, slicedArr() As Variant
    arr = rng.value   'arr = rng works too (https://bettersolutions.com/excel/cells-ranges/vba-working-with-arrays.htm)
    
    If UBound(arr, 1) > UBound(arr, 2) Then
        slicedArr = Application.WorksheetFunction.Transpose(arr)
    Else
        slicedArr = Application.WorksheetFunction.index(arr, 1, 0)  'If you set row_num or column_num to 0 (zero), Index returns the array of values for the entire column or row, respectively._
                                                                   'To use values returned as an array, enter the Index function as an array formula in a horizontal range of cells for a row,_
                                                                   'and in a vertical range of cells for a column.
                                                                   'https://usefulgyaan.wordpress.com/2013/06/12/vba-trick-of-the-week-slicing-an-array-without-loop-application-index/
    End If
convertVecToArr = slicedArr
End Function

How to make program go back to the top of the code instead of closing

Use an infinite loop:

while True:
    print('Hello world!')

This certainly can apply to your start() function as well; you can exit the loop with either break, or use return to exit the function altogether, which also terminates the loop:

def start():
    print ("Welcome to the converter toolkit made by Alan.")

    while True:
        op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")

        if op == "1":
            f1 = input ("Please enter your fahrenheit temperature: ")
            f1 = int(f1)

            a1 = (f1 - 32) / 1.8
            a1 = str(a1)

            print (a1+" celsius") 

        elif op == "2":
            m1 = input ("Please input your the amount of meters you wish to convert: ")
            m1 = int(m1)
            m2 = (m1 * 100)

            m2 = str(m2)
            print (m2+" m")

        if op == "3":
            mb1 = input ("Please input the amount of megabytes you want to convert")
            mb1 = int(mb1)
            mb2 = (mb1 / 1024)
            mb3 = (mb2 / 1024)

            mb3 = str(mb3)

            print (mb3+" GB")

        else:
            print ("Sorry, that was an invalid command!")

If you were to add an option to quit as well, that could be:

if op.lower() in {'q', 'quit', 'e', 'exit'}:
    print("Goodbye!")
    return

for example.

How to remove leading and trailing spaces from a string

 static void Main()
    {
        // A.
        // Example strings with multiple whitespaces.
        string s1 = "He saw   a cute\tdog.";
        string s2 = "There\n\twas another sentence.";

        // B.
        // Create the Regex.
        Regex r = new Regex(@"\s+");

        // C.
        // Strip multiple spaces.
        string s3 = r.Replace(s1, @" ");
        Console.WriteLine(s3);

        // D.
        // Strip multiple spaces.
        string s4 = r.Replace(s2, @" ");
        Console.WriteLine(s4);
        Console.ReadLine();
    }

OUTPUT:

He saw a cute dog. There was another sentence. He saw a cute dog.

Access a URL and read Data with R

Often data on webpages is in the form of an XML table. You can read an XML table into R using the package XML.

In this package, the function

readHTMLTable(<url>)

will look through a page for XML tables and return a list of data frames (one for each table found).

How to apply bold text style for an entire row using Apache POI?

Please find below the easy way :

XSSFCellStyle style = workbook.createCellStyle();
style.setBorderTop((short) 6); // double lines border
style.setBorderBottom((short) 1); // single line border
XSSFFont font = workbook.createFont();
font.setFontHeightInPoints((short) 15);
font.setBoldweight(XSSFFont.BOLDWEIGHT_BOLD);
style.setFont(font);                 

Row row = sheet.createRow(0);   
Cell cell0 = row.createCell(0);
cell0.setCellValue("Nav Value");
cell0.setCellStyle(style);  
for(int j = 0; j<=3; j++)
row.getCell(j).setCellStyle(style);

JavaScript CSS how to add and remove multiple CSS classes to an element

In modern browsers, the classList API is supported.

This allows for a (vanilla) JavaScript function like this:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];

        // Loop through the array of classes to add one class at a time
        for (j = 0, lengthJ = classArray.length; j < lengthJ; j += 1) {
            className = classArray[j];

            element.classList.add(className);
        }
    }
};

Modern browsers (not IE) support passing multiple arguments to the classList::add function, which would remove the need for the nested loop, simplifying the function a bit:

var addClasses;

addClasses = function (selector, classArray) {
    'use strict';

    var classList, className, element, elements, i, j, lengthI, lengthJ;

    elements = document.querySelectorAll(selector);

    // Loop through the elements
    for (i = 0, lengthI = elements.length; i < lengthI; i += 1) {
        element = elements[i];
        classList = element.classList;

        // Pass the array of classes as multiple arguments to classList::add
        classList.add.apply(classList, classArray);
    }
};

Usage

addClasses('.button', ['large', 'primary']);

Functional version

var addClassesToElement, addClassesToSelection;

addClassesToElement = function (element, classArray) {
    'use strict';

    classArray.forEach(function (className) {
       element.classList.add(className);
    });
};

addClassesToSelection = function (selector, classArray) {
    'use strict';

    // Use Array::forEach on NodeList to iterate over results.
    // Okay, since we’re not trying to modify the NodeList.
    Array.prototype.forEach.call(document.querySelectorAll(selector), function (element) {
        addClassesToElement(element, classArray)
    });
};

// Usage
addClassesToSelection('.button', ['button', 'button--primary', 'button--large'])

The classList::add function will prevent multiple instances of the same CSS class as opposed to some of the previous answers.

Resources on the classList API:

How do I convert speech to text?

.NET can do it with its System.Speech namespace.

You would have to convert to .wav first or capture the audio live from the mic.

Details on implementation can be found here: Transcribing Audio with .NET

How can I create objects while adding them into a vector?

// create a vector of unknown players.
std::vector<player> players;

// resize said vector to only contain 6 players.
players.resize(6);

Values are always initialized, so a vector of 6 players is a vector of 6 valid player objects.

As for the second part, you need to use pointers. Instantiating c++ interface as a child class

Center a column using Twitter Bootstrap 3

The preferred method of centering columns is to use "offsets" (ie: col-md-offset-3)

Bootstrap 3.x centering examples

For centering elements, there is a center-block helper class.

You can also use text-center to center text (and inline elements).

Responsive Demo: http://bootply.com/91632

EDIT - As mentioned in the comments, center-block works on column contents and display:block elements, but won't work on the column itself (col-* divs) because Bootstrap uses float.


Update 2020

Now with Bootstrap 4, the centering methods have changed..

  • text-center is still used for display:inline elements
  • mx-auto replaces center-block to center display:block elements
  • offset-* or mx-auto can be used to center grid columns

mx-auto (auto x-axis margins) will center display:block or display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various flexbox centering methods.

Demo Bootstrap 4 Horizontal Centering

For vertical centering in BS4 see https://stackoverflow.com/a/41464397/171456

How do I specify local .gem files in my Gemfile?

You can force bundler to use the gems you deploy using "bundle package" and "bundle install --local"

On your development machine:

bundle install

(Installs required gems and makes Gemfile.lock)

bundle package

(Caches the gems in vendor/cache)

On the server:

bundle install --local

(--local means "use the gems from vendor/cache")

How to get data from database in javascript based on the value passed to the function

The error is coming as your query is getting formed as

SELECT * FROM Employ where number = parseInt(val);

I dont know which DB you are using but no DB will understand parseInt.

What you can do is use a variable say temp and store the value of parseInt(val) in temp variable and make the query as

SELECT * FROM Employ where number = temp;

Cannot read property 'push' of undefined when combining arrays

answer to your question is simple order is not a object make it an array. var order = new Array(); order.push(/item to push/); when ever this error appears just check the left of which property the error is in this case it is push which is order[] so it is undefined.

Changing CSS Values with Javascript

You can get the "computed" styles of any element.

IE uses something called "currentStyle", Firefox (and I assume other "standard compliant" browsers) uses "defaultView.getComputedStyle".

You'll need to write a cross browser function to do this, or use a good Javascript framework like prototype or jQuery (search for "getStyle" in the prototype javascript file, and "curCss" in the jquery javascript file).

That said if you need the height or width you should probably use element.offsetHeight and element.offsetWidth.

The value returned is Null, so if I have Javascript that needs to know the width of something to do some logic (I increase the width by 1%, not to a specific value)

Mind, if you add an inline style to the element in question, it can act as the "default" value and will be readable by Javascript on page load, since it is the element's inline style property:

<div style="width:50%">....</div>

Invalid column count in CSV input on line 1 Error

When facing errors with input files of any type, encoding issues are common.

A simple solution might be to open a new file, copy pasting your CSV text in it, then saving it as a new file.

How do I set the timeout for a JAX-WS webservice client?

In case your appserver is WebLogic (for me it was 10.3.6) then properties responsible for timeouts are:

com.sun.xml.ws.connect.timeout 
com.sun.xml.ws.request.timeout

Change default timeout for mocha

In current versions of Mocha, the timeout can be changed globally like this:

mocha.timeout(5000);

Just add the line above anywhere in your test suite, preferably at the top of your spec or in a separate test helper.


In older versions, and only in a browser, you could change the global configuration using mocha.setup.

mocha.setup({ timeout: 5000 });

The documentation does not cover the global timeout setting, but offers a few examples on how to change the timeout in other common scenarios.

Pass a PHP array to a JavaScript function

Data transfer between two platform requires a common data format. JSON is a common global format to send cross platform data.

drawChart(600/50, JSON.parse('<?php echo json_encode($day); ?>'), JSON.parse('<?php echo json_encode($week); ?>'), JSON.parse('<?php echo json_encode($month); ?>'), JSON.parse('<?php echo json_encode(createDatesArray(cal_days_in_month(CAL_GREGORIAN, date('m',strtotime('-1 day')), date('Y',strtotime('-1 day'))))); ?>'))

This is the answer to your question. The answer may look very complex. You can see a simple example describing the communication between server side and client side here

$employee = array(
 "employee_id" => 10011,
   "Name" => "Nathan",
   "Skills" =>
    array(
           "analyzing",
           "documentation" =>
            array(
              "desktop",
                "mobile"
             )
        )
);

Conversion to JSON format is required to send the data back to client application ie, JavaScript. PHP has a built in function json_encode(), which can convert any data to JSON format. The output of the json_encode function will be a string like this.

{
    "employee_id": 10011,
    "Name": "Nathan",
    "Skills": {
        "0": "analyzing",
        "documentation": [
            "desktop",
            "mobile"
        ]
    }
}

On the client side, success function will get the JSON string. Javascript also have JSON parsing function JSON.parse() which can convert the string back to JSON object.

$.ajax({
        type: 'POST',
        headers: {
            "cache-control": "no-cache"
        },
        url: "employee.php",
        async: false,
        cache: false,
        data: {
            employee_id: 10011
        },
        success: function (jsonString) {
            var employeeData = JSON.parse(jsonString); // employeeData variable contains employee array.
    });

Java ArrayList for integers

List of Integer.

List<Integer> list = new ArrayList<>();
int x = 5;
list.add(x);

How to check if Location Services are enabled?

I use such way for NETWORK_PROVIDER but you can add and for GPS.

LocationManager locationManager;

In onCreate I put

   isLocationEnabled();
   if(!isLocationEnabled()) {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle(R.string.network_not_enabled)
                .setMessage(R.string.open_location_settings)
                .setPositiveButton(R.string.yes,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
                            }
                        })
                .setNegativeButton(R.string.cancel,
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    } 

And method of checking

protected boolean isLocationEnabled(){
    String le = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) getSystemService(le);
    if(!locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
        return false;
    } else {
        return true;
    }
}

Python Web Crawlers and "getting" html source code

An Example with python3 and the requests library as mentioned by @leoluk:

pip install requests

Script req.py:

import requests

url='http://localhost'

# in case you need a session
cd = { 'sessionid': '123..'}

r = requests.get(url, cookies=cd)
# or without a session: r = requests.get(url)
r.content

Now,execute it and you will get the html source of localhost!

python3 req.py

How to generate gcc debug symbol outside the build target?

Compile with debug information:

gcc -g -o main main.c

Separate the debug information:

objcopy --only-keep-debug main main.debug

or

cp main main.debug
strip --only-keep-debug main.debug

Strip debug information from origin file:

objcopy --strip-debug main

or

strip --strip-debug --strip-unneeded main

debug by debuglink mode:

objcopy --add-gnu-debuglink main.debug main
gdb main

You can also use exec file and symbol file separatly:

gdb -s main.debug -e main

or

gdb
(gdb) exec-file main
(gdb) symbol-file main.debug

For details:

(gdb) help exec-file
(gdb) help symbol-file

Ref:
https://sourceware.org/gdb/onlinedocs/gdb/Files.html#Files https://sourceware.org/gdb/onlinedocs/gdb/Separate-Debug-Files.html

In Java, should I escape a single quotation mark (') in String (double quoted)?

It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!

The only times you should need to escape are when trying to put " inside a string, or ' in a character:

String quotes = "He said \"Hello, World!\"";
char quote = '\'';

Open Popup window using javascript

First point is- showing multiple popups is not desirable in terms of usability.

But you can achieve it by using multiple popup names

var newwindow;
function createPop(url, name)
{    
   newwindow=window.open(url,name,'width=560,height=340,toolbar=0,menubar=0,location=0');  
   if (window.focus) {newwindow.focus()}
}

Better approach will be showing both in a single page in two different iFrames or Divs.

Update:

So I will suggest to create a new tab in the test.aspx page to show the report, instead of replacing the image content and placing the pdf.

Math operations from string

Regex won't help much. First of all, you will want to take into account the operators precedence, and second, you need to work with parentheses which is impossible with regex.

Depending on what exactly kind of expression you need to parse, you may try either Python AST or (more likely) pyparsing. But, first of all, I'd recommend to read something about syntax analysis in general and the Shunting yard algorithm in particular.

And fight the temptation of using eval, that's not safe.

Allowed memory size of 536870912 bytes exhausted in Laravel

It is happened to me with laravel 5.1 on php-7 when I was running bunch of unitests.

The solution was - to change memory_limit in php.ini but it should be correct one. So you need one responsible for server, located there:

/etc/php/7.0/cli/php.ini

so you need a line with

 memory_limit

After that you need to restart php service

sudo service php7.0-fpm restart

to check if it was changed successfully I used command line to run this:

 php -i

the report contained following line

memory_limit => 2048M => 2048M

Now test cases are fine.

MySQL: How to copy rows, but change a few fields?

This is a solution where you have many fields in your table and don't want to get a finger cramp from typing all the fields, just type the ones needed :)

How to copy some rows into the same table, with some fields having different values:

  1. Create a temporary table with all the rows you want to copy
  2. Update all the rows in the temporary table with the values you want
  3. If you have an auto increment field, you should set it to NULL in the temporary table
  4. Copy all the rows of the temporary table into your original table
  5. Delete the temporary table

Your code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE Event_ID="155";

UPDATE temporary_table SET Event_ID="120";

UPDATE temporary_table SET ID=NULL

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

General scenario code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

UPDATE temporary_table SET <auto_inc_field>=NULL;

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

Simplified/condensed code:

CREATE TEMPORARY TABLE temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <auto_inc_field>=NULL, <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

INSERT INTO original_table SELECT * FROM temporary_table;

As creation of the temporary table uses the TEMPORARY keyword it will be dropped automatically when the session finishes (as @ar34z suggested).

std::thread calling method of class

Not so hard:

#include <thread>

void Test::runMultiThread()
{
    std::thread t1(&Test::calculate, this,  0, 10);
    std::thread t2(&Test::calculate, this, 11, 20);
    t1.join();
    t2.join();
}

If the result of the computation is still needed, use a future instead:

#include <future>

void Test::runMultiThread()
{
     auto f1 = std::async(&Test::calculate, this,  0, 10);
     auto f2 = std::async(&Test::calculate, this, 11, 20);

     auto res1 = f1.get();
     auto res2 = f2.get();
}

Oracle SQL convert date format from DD-Mon-YY to YYYYMM

Am I missing something? You can just convert offer_date in the comparison:

SELECT *
FROM offers
WHERE to_char(offer_date, 'YYYYMM') = (SELECT to_date(create_date, 'YYYYMM') FROM customers where id = '12345678') AND
      offer_rate > 0 

Android + Pair devices via bluetooth programmatically

The Best way is do not use any pairing code. Instead of onClick go to other function or other class where You create the socket using UUID.
Android automatically pops up for pairing if already not paired.

or see this link for better understanding

Below is code for the same:

private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
    public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
        // Cancel discovery because it's costly and we're about to connect
        mBtAdapter.cancelDiscovery();

        // Get the device MAC address, which is the last 17 chars in the View
        String info = ((TextView) v).getText().toString();
        String address = info.substring(info.length() - 17);

        // Create the result Intent and include the MAC address
        Intent intent = new Intent();
        intent.putExtra(EXTRA_DEVICE_ADDRESS, address);

        // Set result and finish this Activity
        setResult(Activity.RESULT_OK, intent);

      // **add this 2 line code** 
       Intent myIntent = new Intent(view.getContext(), Connect.class);
        startActivityForResult(myIntent, 0);

        finish();
    }
};

Connect.java file is :

public class Connect extends Activity {
private static final String TAG = "zeoconnect";
private ByteBuffer localByteBuffer;
 private InputStream in;
 byte[] arrayOfByte = new byte[4096];
 int bytes;


  public BluetoothDevice mDevice;



@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.connect);



              try {
                setup();
            } catch (ZeoMessageException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ZeoMessageParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            }

 private void setup() throws ZeoMessageException, ZeoMessageParseException  {
    // TODO Auto-generated method stub

        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
        getApplicationContext().registerReceiver(receiver,
                    new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));

            BluetoothDevice zee = BluetoothAdapter.getDefaultAdapter().
                    getRemoteDevice("**:**:**:**:**:**");// add device mac adress

            try {
                sock = zee.createRfcommSocketToServiceRecord(
                         UUID.fromString("*******************")); // use unique UUID
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

            Log.d(TAG, "++++ Connecting");
            try {
                sock.connect();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }
            Log.d(TAG, "++++ Connected");


            try {
                in = sock.getInputStream();
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

              Log.d(TAG, "++++ Listening...");

              while (true) {

                  try {
                      bytes = in.read(arrayOfByte);
                      Log.d(TAG, "++++ Read "+ bytes +" bytes");  
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                }
                        Log.d(TAG, "++++ Done: test()"); 

                        }} 




 private static final LogBroadcastReceiver receiver = new LogBroadcastReceiver();
    public static class LogBroadcastReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context paramAnonymousContext, Intent paramAnonymousIntent) {
            Log.d("ZeoReceiver", paramAnonymousIntent.toString());
            Bundle extras = paramAnonymousIntent.getExtras();
            for (String k : extras.keySet()) {
                Log.d("ZeoReceiver", "    Extra: "+ extras.get(k).toString());
            }
        }


    };

    private BluetoothSocket sock;
    @Override
    public void onDestroy() {
        getApplicationContext().unregisterReceiver(receiver);
        if (sock != null) {
            try {
                sock.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        super.onDestroy();
    }
 }

Excel VBA Automation Error: The object invoked has disconnected from its clients

I had this same problem in a large Excel 2000 spreadsheet with hundreds of lines of code. My solution was to make the Worksheet active at the beginning of the Class. I.E. ThisWorkbook.Worksheets("WorkSheetName").Activate This was finally discovered when I noticed that if "WorkSheetName" was active when starting the operation (the code) the error didn't occur. Drove me crazy for quite awhile.

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

Tomcat startup logs - SEVERE: Error filterStart how to get a stack trace?

I got the same issue, unable to start the application once it is deployed in tomcat. But, once I copy the Struts set of jars into CATALINA_HOME\lib (Tomcat dir) directory it is resolved. You don't need to have these jars in your WEB_INF\lib but you need to have them in your Build Path.

commons-fileupload-1.2.1.jar

commons-io-1.3.2.jar

freemarker-2.3.16.jar

javassist-3.11.0.GA.jar

struts2-convention-plugin-2.2.1.jar

struts2-core-2.2.1.jar

xwork-core-2.2.1.jar

jQuery Ajax POST example with PHP

<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<form method="post" id="form_content" action="Javascript:void(0);">
    <button id="desc" name="desc" value="desc" style="display:none;">desc</button>
    <button id="asc" name="asc"  value="asc">asc</button>
    <input type='hidden' id='check' value=''/>
</form>

<div id="demoajax"></div>

<script>
    numbers = '';
    $('#form_content button').click(function(){
        $('#form_content button').toggle();
        numbers = this.id;
        function_two(numbers);
    });

    function function_two(numbers){
        if (numbers === '')
        {
            $('#check').val("asc");
        }
        else
        {
            $('#check').val(numbers);
        }
        //alert(sort_var);

        $.ajax({
            url: 'test.php',
            type: 'POST',
            data: $('#form_content').serialize(),
            success: function(data){
                $('#demoajax').show();
                $('#demoajax').html(data);
                }
        });

        return false;
    }
    $(document).ready(function_two());
</script>

ExecuteNonQuery doesn't return results

Whenever you want to execute an SQL statement that shouldn't return a value or a record set, the ExecuteNonQuery should be used.

So if you want to run an update, delete, or insert statement, you should use the ExecuteNonQuery. ExecuteNonQuery returns the number of rows affected by the statement. This sounds very nice, but whenever you use the SQL Server 2005 IDE or Visual Studio to create a stored procedure it adds a small line that ruins everything.

That line is: SET NOCOUNT ON; This line turns on the NOCOUNT feature of SQL Server, which "Stops the message indicating the number of rows affected by a Transact-SQL statement from being returned as part of the results" and therefore it makes the stored procedure always to return -1 when called from the application (in my case a web application).

In conclusion, remove that line from your stored procedure, and you will now get a value indicating the number of rows affected by the statement.

Happy programming!

http://aspsoft.blogs.com/jonas/2006/10/executenonquery.html

Getting the object's property name

IN ES5

E.G. you have this kind of object:

var ELEMENTS = {
    STEP_ELEMENT: { ID: "0", imageName: "el_0.png" },
    GREEN_ELEMENT: { ID: "1", imageName: "el_1.png" },
    BLUE_ELEMENT: { ID: "2", imageName: "el_2.png" },
    ORANGE_ELEMENT: { ID: "3", imageName: "el_3.png" },
    PURPLE_ELEMENT: { ID: "4", imageName: "el_4.png" },
    YELLOW_ELEMENT: { ID: "5", imageName: "el_5.png" }
};

And now if you want to have a function that if you pass '0' as a param - to get 'STEP_ELEMENT', if '2' to get 'BLUE_ELEMENT' and so for

function(elementId) {
    var element = null;

    Object.keys(ELEMENTS).forEach(function(key) {
        if(ELEMENTS[key].ID === elementId.toString()){
            element = key;
            return;
        }    
    });

    return element;
}

This is probably not the best solution to the problem but its good to give you an idea how to do it.

Cheers.

How do I seed a random class to avoid getting duplicate random values

A good seed initialisation can be done like this

Random rnd = new Random((int)DateTime.Now.Ticks);

The ticks will be unique and the cast into a int with probably a loose of value will be OK.

I need to convert an int variable to double

Converting to double can be done by casting an int to a double:

You can convert an int to a double by using this mechnism like so:

int i = 3; // i is 3
double d = (double) i; // d = 3.0

Alternative (using Java's automatic type recognition):

double d = 1.0 * i; // d = 3.0

Implementing this in your code would be something like:

double firstSolution = ((double)(b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21));
double secondSolution = ((double)(b2 * a11 - b1 * a21) / (double)(a11 * a22 - a12 * a21));

Alternatively you can use a hard-parameter of type double (1.0) to have java to the work for you, like so:

double firstSolution = ((1.0 * (b1 * a22 - b2 * a12)) / (1.0 * (a11 * a22 - a12 * a21)));
double secondSolution = ((1.0 * (b2 * a11 - b1 * a21)) / (1.0 * (a11 * a22 - a12 * a21)));

Good luck.

How an 'if (A && B)' statement is evaluated?

You are asking about the && operator, not the if statement.

&& short-circuits, meaning that if while working it meets a condition which results in only one answer, it will stop working and use that answer.

So, 0 && x will execute 0, then terminate because there is no way for the expression to evaluate non-zero regardless of what is the second parameter to &&.

How to downgrade Xcode to previous version?

When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools

PHP regular expression - filter number only

You could do something like this if you want only whole numbers.

function make_whole($v){
    $v = floor($v);
    if(is_numeric($v)){
      echo (int)$v;
      // if you want only positive whole numbers
      //echo (int)$v = abs($v);
    }
}

What's the difference between Apache's Mesos and Google's Kubernetes

"I understand both are server cluster management software."

This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).

Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).

grid controls for ASP.NET MVC?

Try: http://mvcjqgridcontrol.codeplex.com/ It's basically a MVC-compliant jQuery Grid wrapper with full .Net support

HTML tag inside JavaScript

JavaScript is a scripting language, not a HTMLanguage type. It is mainly to do process at background and it needs document.write to display things on browser. Also if your document.write exceeds one line, make sure to put concatenation + at the end of each line.

Example

<script type="text/javascript">
if(document.getElementById('number1').checked) {
document.write("<h1>Hello" +
"member</h1>");
}
</script>

How to enable mod_rewrite for Apache 2.2

For my situation, I had

RewriteEngine On

in my .htaccess, along with the module being loaded, and it was not working.

The solution to my problem was to edit my vhost entry to inlcude

AllowOverride all

in the <Directory> section for the site in question.

Convert Java String to sql.Timestamp

Have you tried using Timestamp.valueOf(String)? It looks like it should do almost exactly what you want - you just need to change the separator between your date and time to a space, and the ones between hours and minutes, and minutes and hours, to colons:

import java.sql.*;

public class Test {
    public static void main(String[] args) {
        String text = "2011-10-02 18:48:05.123456";
        Timestamp ts = Timestamp.valueOf(text);
        System.out.println(ts.getNanos());
    }
}

Assuming you've already validated the string length, this will convert to the right format:

static String convertSeparators(String input) {
    char[] chars = input.toCharArray();
    chars[10] = ' ';
    chars[13] = ':';
    chars[16] = ':';
    return new String(chars);
}

Alternatively, parse down to milliseconds by taking a substring and using Joda Time or SimpleDateFormat (I vastly prefer Joda Time, but your mileage may vary). Then take the remainder of the string as another string and parse it with Integer.parseInt. You can then combine the values pretty easily:

Date date = parseDateFromFirstPart();
int micros = parseJustLastThreeDigits();

Timestamp ts = new Timestamp(date.getTime());
ts.setNanos(ts.getNanos() + micros * 1000);

Passing an array to a query using a WHERE clause

Because the original question relates to an array of numbers and I am using an array of strings I couldn't make the given examples work.

I found that each string needed to be encapsulated in single quotes to work with the IN() function.

Here is my solution

foreach($status as $status_a) {
        $status_sql[] = '\''.$status_a.'\'';
    }
    $status = implode(',',$status_sql);

$sql = mysql_query("SELECT * FROM table WHERE id IN ($status)");

As you can see the first function wraps each array variable in single quotes (\') and then implodes the array.

NOTE: $status does not have single quotes in the SQL statement.

There is probably a nicer way to add the quotes but this works.

ld: framework not found Pods

Step 1

The first thing that you will need to do is remove the Podfile, Podfile.lock, the Pods folder, and the generated workspace.

Step 2

Next, in the .xcodeproj, remove the references to the Pods.xcconfig files and the libPods.a file.

Step 3

Within the Build Phases project tab, delete the Check Pods Manifest.lock section (open),Copy Pods Resources section (bottom) and Embed Pod Resources(bottom).

Step4

Remove Pods.framework.

The only thing you may want to do is include some of the libraries that you were using before. You can do this by simply draging whatever folders where in the pods folders into your project (I prefer to put them into my Supporting Files folder).

It worked for me.

Declare variable MySQL trigger

All DECLAREs need to be at the top. ie.

delimiter //

CREATE TRIGGER pgl_new_user 
AFTER INSERT ON users FOR EACH ROW
BEGIN
    DECLARE m_user_team_id integer;
    DECLARE m_projects_id integer;
    DECLARE cur CURSOR FOR SELECT project_id FROM user_team_project_relationships WHERE user_team_id = m_user_team_id;

    SET @m_user_team_id := (SELECT id FROM user_teams WHERE name = "pgl_reporters");

    OPEN cur;
        ins_loop: LOOP
            FETCH cur INTO m_projects_id;
            IF done THEN
                LEAVE ins_loop;
            END IF;
            INSERT INTO users_projects (user_id, project_id, created_at, updated_at, project_access) 
            VALUES (NEW.id, m_projects_id, now(), now(), 20);
        END LOOP;
    CLOSE cur;
END//

What is the problem with shadowing names defined in outer scopes?

A good workaround in some cases may be to move the variables and code to another function:

def print_data(data):
    print data

def main():
    data = [4, 5, 6]
    print_data(data)

main()

Writing image to local server

How about this?

var http = require('http'), 
fs = require('fs'), 
options;

options = {
    host: 'www.google.com' , 
    port: 80,
    path: '/images/logos/ps_logo2.png'
}

var request = http.get(options, function(res){

//var imagedata = ''
//res.setEncoding('binary')

var chunks = [];

res.on('data', function(chunk){

    //imagedata += chunk
    chunks.push(chunk)

})

res.on('end', function(){

    //fs.writeFile('logo.png', imagedata, 'binary', function(err){

    var buffer = Buffer.concat(chunks)
    fs.writeFile('logo.png', buffer, function(err){
        if (err) throw err
        console.log('File saved.')
    })

})

How to access a preexisting collection with Mongoose?

I had the same problem and was able to run a schema-less query using an existing Mongoose connection with the code below. I've added a simple constraint 'a=b' to show where you would add such a constraint:

var action = function (err, collection) {
    // Locate all the entries using find
    collection.find({'a':'b'}).toArray(function(err, results) {
        /* whatever you want to do with the results in node such as the following
             res.render('home', {
                 'title': 'MyTitle',
                 'data': results
             });
        */
    });
};

mongoose.connection.db.collection('question', action);

Getting list of lists into pandas DataFrame

Call the pd.DataFrame constructor directly:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

Calling a method every x minutes

var startTimeSpan = TimeSpan.Zero;
var periodTimeSpan = TimeSpan.FromMinutes(5);

var timer = new System.Threading.Timer((e) =>
{
    MyMethod();   
}, null, startTimeSpan, periodTimeSpan);

Convert java.util.Date to java.time.LocalDate

I solved this question with solution below

  import org.joda.time.LocalDate;
  Date myDate = new Date();
  LocalDate localDate = LocalDate.fromDateFields(myDate);
  System.out.println("My date using Date" Nov 18 11:23:33 BRST 2016);
  System.out.println("My date using joda.time LocalTime" 2016-11-18);

In this case localDate print your date in this format "yyyy-MM-dd"

Getting started with OpenCV 2.4 and MinGW on Windows 7

If you installed opencv 2.4.2 then you need to change the -lopencv_core240 to -lopencv_core242

I made the same mistake.

Force SSL/https using .htaccess and mod_rewrite

I found a mod_rewrite solution that works well for both proxied and unproxied servers.

If you are using CloudFlare, AWS Elastic Load Balancing, Heroku, OpenShift or any other Cloud/PaaS solution and you are experiencing redirect loops with normal HTTPS redirects, try the following snippet instead.

RewriteEngine On

# If we receive a forwarded http request from a proxy...
RewriteCond %{HTTP:X-Forwarded-Proto} =http [OR]

# ...or just a plain old http request directly from the client
RewriteCond %{HTTP:X-Forwarded-Proto} =""
RewriteCond %{HTTPS} !=on

# Redirect to https version
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

How do I reload a page without a POSTDATA warning in Javascript?

You can't refresh without the warning; refresh instructs the browser to repeat the last action. It is up to the browser to choose whether to warn the user if repeating the last action involves resubmitting data.

You could re-navigate to the same page with a fresh session by doing:

window.location = window.location.href;

Show row number in row header of a DataGridView

This worked for me.

Private Sub GridView1_CellFormatting(sender As Object, e As DataGridViewCellFormattingEventArgs) Handles GridView1.CellFormatting
    Dim idx As Integer = e.RowIndex
    Dim row As DataGridViewRow = VDataGridView1.Rows(idx)
    Dim newNo As Long = idx
    If Not _RowNumberStartFromZero Then
        newNo += 1
    End If

    Dim oldNo As Long = -1
    If row.HeaderCell.Value IsNot Nothing Then
        If IsNumeric(row.HeaderCell.Value) Then
            oldNo = CLng(row.HeaderCell.Value)
        End If
    End If

    If newNo <> oldNo Then 'only change if it's wrong or not set
        row.HeaderCell.Value = newNo.ToString()
        row.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
    End If
End Sub

How to differ sessions in browser-tabs?

you will need to do

1- store a cookie for accounts list

2- optional store a cookie for default one

3- store for each account with it's index like acc1, acc2

4- put in the url something represent the index of accounts and if not you will select the default one like google mail domain.com/0/some-url >> 0 here represent the index of account also you may need to know how to use urlwrite

5- when select a cookie, select it according to your urlpath represent the account index

Regards

ALTER TABLE DROP COLUMN failed because one or more objects access this column

The @SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.

So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int NULL,
  CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;

You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.

Parsing CSV / tab-delimited txt file with Python

Start by turning the text into a list of lists. That will take care of the parsing part:

lol = list(csv.reader(open('text.txt', 'rb'), delimiter='\t'))

The rest can be done with indexed lookups:

d = dict()
key = lol[6][0]      # cell A7
value = lol[6][3]    # cell D7
d[key] = value       # add the entry to the dictionary
 ...

connecting to phpMyAdmin database with PHP/MySQL

Connect to MySQL

<?php

/*** mysql hostname ***/
$hostname = 'localhost';

/*** mysql username ***/
$username = 'username';

/*** mysql password ***/
$password = 'password';

try {
    $dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
    /*** echo a message saying we have connected ***/
    echo 'Connected to database';
    }
catch(PDOException $e)
    {
    echo $e->getMessage();
    }
?>

Also mysqli_connect() function to open a new connection to the MySQL server.

<?php
// Create connection
$con=mysqli_connect(host,username,password,dbname); 

// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
?> 

How can I sharpen an image in OpenCV?

To sharpen an image we can use the filter (as in many previous answers)

kernel = np.array([[-1, -1, -1],[-1, 8, -1],[-1, -1, 0]], np.float32) 

kernel /= denominator * kernel

It will be the most when the denominator is 1 and will decrease as increased (2.3..)

The most used one is when the denominator is 3.

Below is the implementation.

kernel = np.array([[-1, -1, -1],[-1, 8, -1],[-1, -1, 0]], np.float32) 

kernel = 1/3 * kernel

dst = cv2.filter2D(image, -1, kernel)

How do I plot only a table in Matplotlib?

This is another option to write a pandas dataframe directly into a matplotlib table:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

fig, ax = plt.subplots()

# hide axes
fig.patch.set_visible(False)
ax.axis('off')
ax.axis('tight')

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

ax.table(cellText=df.values, colLabels=df.columns, loc='center')

fig.tight_layout()

plt.show()

enter image description here

How can I reset or revert a file to a specific revision?

git checkout -- foo

That will reset foo to HEAD. You can also:

git checkout HEAD^ foo

for one revision back, etc.

Add class to <html> with Javascript?

document.getElementsByTagName("html")[0].classList.add('theme-dark');
document.getElementsByTagName("html")[0].classList.remove('theme-dark')
document.getElementsByTagName("html")[0].classList.toggle('theme-dark')

FirebaseInstanceIdService is deprecated

Kotlin allows for even simpler code than what's shown in other answers.

To get the new token whenever it's refreshed:

class MyFirebaseMessagingService: FirebaseMessagingService() {

    override fun onNewToken(token: String?) {
        Log.d("FMS_TOKEN", token)
    }
    ...
}

To get the token from anywhere at runtime:

FirebaseInstanceId.getInstance().instanceId.addOnSuccessListener {
    Log.d("FMS_TOKEN", it.token)
}

PHP Warning: POST Content-Length of 8978294 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

Already restarted your Webserver?

This will force php to reload the php.ini

MongoDB: Combine data from multiple collections into one..how?

Mongorestore has this feature of appending on top of whatever is already in the database, so this behavior could be used for combining two collections:

  1. mongodump collection1
  2. collection2.rename(collection1)
  3. mongorestore

Didn't try it yet, but it might perform faster than the map/reduce approach.

Passing functions with arguments to another function in Python?

You can use the partial function from functools like so.

from functools import partial

def perform(f):
    f()

perform(Action1)
perform(partial(Action2, p))
perform(partial(Action3, p, r))

Also works with keywords

perform(partial(Action4, param1=p))

Cannot open new Jupyter Notebook [Permission Denied]

I had the very same issue running Jupyter. After chasing my tail on permissions, I found that everything cleared up after I changed ownership on the directory where I was trying to run/store my notebooks. Ex.: I was running my files out of my ~/bash dir. That was root:root; when I changed it to jim:jim....no more errors.

How do I access Configuration in any class in ASP.NET Core?

Using the Options pattern in ASP.NET Core is the way to go. I just want to add, if you need to access the options within your startup.cs, I recommend to do it this way:

CosmosDbOptions.cs:

public class CosmosDbOptions
{
    public string ConnectionString { get; set; }
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // This is how you can access the Connection String:
    var connectionString = Configuration.GetSection(nameof(CosmosDbOptions))[nameof(CosmosDbOptions.ConnectionString)];
}

DropdownList DataSource

Refer to example at this link. It may be help to you.

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx

void Page_Load(Object sender, EventArgs e)
  {

     // Load data for the DropDownList control only once, when the 
     // page is first loaded.
     if(!IsPostBack)
     {

        // Specify the data source and field names for the Text 
        // and Value properties of the items (ListItem objects) 
        // in the DropDownList control.
        ColorList.DataSource = CreateDataSource();
        ColorList.DataTextField = "ColorTextField";
        ColorList.DataValueField = "ColorValueField";

        // Bind the data to the control.
        ColorList.DataBind();

        // Set the default selected item, if desired.
        ColorList.SelectedIndex = 0;

     }

  }

void Selection_Change(Object sender, EventArgs e)
  {

     // Set the background color for days in the Calendar control
     // based on the value selected by the user from the 
     // DropDownList control.
     Calendar1.DayStyle.BackColor = 
         System.Drawing.Color.FromName(ColorList.SelectedItem.Value);

  }

iPhone/iOS JSON parsing tutorial

try out with this fastest JSON framework JSONKit. it's faster than normal JSON framework.

Why do you create a View in a database?

A view provides several benefits.

1. Views can hide complexity

If you have a query that requires joining several tables, or has complex logic or calculations, you can code all that logic into a view, then select from the view just like you would a table.

2. Views can be used as a security mechanism

A view can select certain columns and/or rows from a table (or tables), and permissions set on the view instead of the underlying tables. This allows surfacing only the data that a user needs to see.

3. Views can simplify supporting legacy code

If you need to refactor a table that would break a lot of code, you can replace the table with a view of the same name. The view provides the exact same schema as the original table, while the actual schema has changed. This keeps the legacy code that references the table from breaking, allowing you to change the legacy code at your leisure.

These are just some of the many examples of how views can be useful.

C char array initialization

Edit: OP (or an editor) silently changed some of the single quotes in the original question to double quotes at some point after I provided this answer.

Your code will result in compiler errors. Your first code fragment:

char buf[10] ; buf = ''

is doubly illegal. First, in C, there is no such thing as an empty char. You can use double quotes to designate an empty string, as with:

char* buf = ""; 

That will give you a pointer to a NUL string, i.e., a single-character string with only the NUL character in it. But you cannot use single quotes with nothing inside them--that is undefined. If you need to designate the NUL character, you have to specify it:

char buf = '\0';

The backslash is necessary to disambiguate from character '0'.

char buf = 0;

accomplishes the same thing, but the former is a tad less ambiguous to read, I think.

Secondly, you cannot initialize arrays after they have been defined.

char buf[10];

declares and defines the array. The array identifier buf is now an address in memory, and you cannot change where buf points through assignment. So

buf =     // anything on RHS

is illegal. Your second and third code fragments are illegal for this reason.

To initialize an array, you have to do it at the time of definition:

char buf [10] = ' ';

will give you a 10-character array with the first char being the space '\040' and the rest being NUL, i.e., '\0'. When an array is declared and defined with an initializer, the array elements (if any) past the ones with specified initial values are automatically padded with 0. There will not be any "random content".

If you declare and define the array but don't initialize it, as in the following:

char buf [10];

you will have random content in all the elements.

How do I iterate through lines in an external file with shell?

You'll be wanting to use the 'read' command

while read name
do
    echo "$name"
done < names.txt

Note that "$name" is quoted -- if it's not, it will be split using the characters in $IFS as delimiters. This probably won't be noticed if you're just echoing the variable, but if your file contains a list of file names which you want to copy, those will get broken down by $IFS if the variable is unquoted, which is not what you want or expect.

If you want to use Mike Clark's approach (loading into a variable rather than using read), you can do it without the use of cat:

NAMES="$(< scripts/names.txt)" #names from names.txt file
for NAME in $NAMES; do
    echo "$NAME"
done

The problem with this is that it loads the whole file into $NAMES, when you read it back out, you can either get the whole file (if quoted) or the file broken down by $IFS, if not quoted. By default, this will give you individual words, not individual lines. So if the name "Mary Jane" appeared on a line, you would get "Mary" and "Jane" as two separate names. Using read will get around this... although you could also change the value of $IFS

How to use cURL to get jSON data and decode the data?

to get the object you do not need to use cURL (you are loading another dll into memory and have another dependency, unless you really need curl I'd stick with built in php functions), you can use one simple php file_get_contents(url) function: http://il1.php.net/manual/en/function.file-get-contents.php

$unparsed_json = file_get_contents("api.php?action=getThreads&hash=123fajwersa&node_id=4&order_by=post_date&order=desc&limit=1&grab_content&content_limit=1");

$json_object = json_decode($unparsed_json);

then json_decode() parses JSON into a PHP object, or an array if you pass true to the second parameter. http://php.net/manual/en/function.json-decode.php

For example:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));           // Object
var_dump(json_decode($json, true));     // Associative array

Uninstall / remove a Homebrew package including all its dependencies

Using this answer requires that you create and maintain a file that contains the package names you want installed on your system. If you don't have one already, use the following command and delete the package names what you don't want to keep installed.

brew leaves > brew_packages

Then you can remove all installed, but unwanted packages and any unnecessary dependencies by running the following command

brew_clean brew_packages

brew_clean is available here: https://gist.github.com/cskeeters/10ff1295bca93808213d

This script gets all of the packages you specified in brew_packages and all of their dependancies and compares them against the output of brew list and finally removes the unwanted packages after verifying this list with the user.

At this point if you want to remove package a, you simply remove it from the brew_packages file then re-run brew_clean brew_packages. It will remove b, but not c.

How to change the font and font size of an HTML input tag?

in your css :

 #txtComputer {
      font-size: 24px;
 }

You can style an input entirely (background, color, etc.) and even use the hover event.

Java Generate Random Number Between Two Given Values

Use Random.nextInt(int).

In your case it would look something like this:

a[i][j] = r.nextInt(101);

How to set the width of a RaisedButton in Flutter?

we use Row or Column, Expanded, Container and the element to use example RaisedButton

 body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
                Padding(
                  padding: const EdgeInsets.symmetric(vertical: 10.0),
                ),
                Row(
                  children: <Widget>[
                    Expanded(
                      flex: 2, // we define the width of the button
                      child: Container(
                        // height: 50, we define the height of the button
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10.0),
                          child: RaisedButton(
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            textColor: Colors.white,
                            color: Colors.blue,
                            onPressed: () {
                              // Method to execute
                            },
                            child: Text('Copy'),
                          ),
                        ),
                      ),
                    ),
                    Expanded(
                      flex: 2, // we define the width of the button
                      child: Container(
                        // height: 50, we define the height of the button
                        child: Padding(
                          padding: const EdgeInsets.symmetric(horizontal: 10.0),
                          child: RaisedButton(
                            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
                            textColor: Colors.white,
                            color: Colors.green,
                            onPressed: () {
                              // Method to execute
                            },
                            child: Text('Paste'),
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),

BeanFactory vs ApplicationContext

I think it's better to always use ApplicationContext, unless you're in a mobile environment like someone else said already. ApplicationContext has more functionality and you definitely want to use the PostProcessors such as RequiredAnnotationBeanPostProcessor, AutowiredAnnotationBeanPostProcessor and CommonAnnotationBeanPostProcessor, which will help you simplify your Spring configuration files, and you can use annotations such as @Required, @PostConstruct, @Resource, etc in your beans.

Even if you don't use all the stuff ApplicationContext offers, it's better to use it anyway, and then later if you decide to use some resource stuff such as messages or post processors, or the other schema to add transactional advices and such, you will already have an ApplicationContext and won't need to change any code.

If you're writing a standalone app, load the ApplicationContext in your main method, using a ClassPathXmlApplicationContext, and get the main bean and invoke its run() (or whatever method) to start your app. If you're writing a web app, use the ContextLoaderListener in web.xml so that it creates the ApplicationContext and you can later get it from the ServletContext, regardless of whether you're using JSP, JSF, JSTL, struts, Tapestry, etc.

Also, remember you can use multiple Spring configuration files and you can either create the ApplicationContext by listing all the files in the constructor (or listing them in the context-param for the ContextLoaderListener), or you can just load a main config file which has import statements. You can import a Spring configuration file into another Spring configuration file by using <import resource="otherfile.xml" /> which is very useful when you programmatically create the ApplicationContext in the main method and load only one Spring config file.

Clear a terminal screen for real

I know the solution employing printing of new lines isn't much supported, but if all else fails, why not? Especially where one is operating in an environment where someone else is likely to be able to see the screen, yet not able to keylog. One potential solution then, is the following alias:

alias c="printf '\r\n%.0s' {1..50}"

Then, to "clear" away the current contents of the screen (or rather, hide them), just type c+Enter at the terminal.

How does one target IE7 and IE8 with valid CSS?

I would recommend looking into conditional comments and making a separate sheet for the IEs you are having problems with.

 <!--[if IE 7]>
   <link rel="stylesheet" type="text/css" href="ie7.css" />
 <![endif]-->

How to crop an image using C#?

You can use Graphics.DrawImage to draw a cropped image onto the graphics object from a bitmap.

Rectangle cropRect = new Rectangle(...);
Bitmap src = Image.FromFile(fileName) as Bitmap;
Bitmap target = new Bitmap(cropRect.Width, cropRect.Height);

using(Graphics g = Graphics.FromImage(target))
{
   g.DrawImage(src, new Rectangle(0, 0, target.Width, target.Height), 
                    cropRect,                        
                    GraphicsUnit.Pixel);
}

What does '<?=' mean in PHP?

Code like "a => b" means, for an associative array (some languages, like Perl, if I remember correctly, call those "hash"), that 'a' is a key, and 'b' a value.

You might want to take a look at the documentations of, at least:

Here, you are having an array, called $user_list, and you will iterate over it, getting, for each line, the key of the line in $user, and the corresponding value in $pass.

For instance, this code:

$user_list = array(
    'user1' => 'password1',
    'user2' => 'password2',
);

foreach ($user_list as $user => $pass)
{
    var_dump("user = $user and password = $pass");
}

Will get you this output:

string 'user = user1 and password = password1' (length=37)
string 'user = user2 and password = password2' (length=37)

(I'm using var_dump to generate a nice output, that facilitates debuging; to get a normal output, you'd use echo)


"Equal or greater" is the other way arround: "greater or equals", which is written, in PHP, like this; ">="
The Same thing for most languages derived from C: C++, JAVA, PHP, ...


As a piece of advice: If you are just starting with PHP, you should definitely spend some time (maybe a couple of hours, maybe even half a day or even a whole day) going through some parts of the manual :-)
It'd help you much!

mailto using javascript

With JavaScript you can create a link 'on the fly' using something like:

var mail = document.createElement("a");
mail.href = "mailto:[email protected]";
mail.click();

This is redirected by the browser to some mail client installed on the machine without losing the content of the current window ... and you would not need any API like 'jQuery'.

How can I have Github on my own server?

I tried gitosis that is fully command line. And I chose this one.

Being a Java guy, I also looked with interest to Gitblit.

Eclipse count lines of code

Another way would by to use another loc utility, like LocMetrics for instance.
It also lists many other loc tools. The integration with Eclipse wouldn't be always there (as it would be with Metrics2, which you can check out because it is a more recent version than Metrics), but at least those tools can reason in term of logical lines (computed by summing the terminal semicolons and terminal curly braces).
You can also check with eclipse-metrics is more adapted to what you expect.

How to make an autocomplete address field with google maps api?

Like others have mentioned, the Google Places Autocomplete API is missing some important functions. Case in point, Google will not validate that the street number is real, and they also will not put it into a standardized format. So, it is the user's responsibility to enter that portion of the address correctly.

Google also won't predict PO Boxes or apartment numbers. So, if you are using their API for shipping, address cleansing or data governance, you may want one that will validate the building number, autocomplete the unit number and standardize the information.

Full Disclosure, I work for SmartyStreets

Link entire table row?

Also it depends if you need to use a table element or not. You can imitate a table using CSS and make an A element the row

<div class="table" style="width:100%;">
  <a href="#" class="tr">
    <span class="td">
      cell 1
    </span>
    <span class="td">
      cell 2
    </span>
  </a>
</div>

css:

.table{display:table;}
.tr{display:table-row;}
.td{display:table-cell;}
.tr:hover{background-color:#ccc;}

HTML5 LocalStorage: Checking if a key exists

This method worked for me:

if ("username" in localStorage) {
    alert('yes');
} else {
    alert('no');
}

Read String line by line

Solution using Java 8 features such as Stream API and Method references

new BufferedReader(new StringReader(myString))
        .lines().forEach(System.out::println);

or

public void someMethod(String myLongString) {

    new BufferedReader(new StringReader(myLongString))
            .lines().forEach(this::parseString);
}

private void parseString(String data) {
    //do something
}

Git error on commit after merge - fatal: cannot do a partial commit during a merge

For myself this happened in SourceTree when I tried to commit a merge before resolving all of the files. I then marked the last file resolved and yet it still gave me this error when trying to commit. I closed SourceTree and reopened it, and then it committed fine.

How to add a form load event (currently not working)

You got half of the answer! Now that you created the event handler, you need to hook it to the form so that it actually gets called when the form is loading. You can achieve that by doing the following:

 public class ProgramViwer : Form{
  public ProgramViwer()
  {
       InitializeComponent();
       Load += new EventHandler(ProgramViwer_Load);
  }
  private void ProgramViwer_Load(object sender, System.EventArgs e)
  {
       formPanel.Controls.Clear();
       formPanel.Controls.Add(wel);
  }
}

MVVM Passing EventArgs As Command Parameter

I try to keep my dependencies to a minimum, so I implemented this myself instead of going with EventToCommand of MVVMLight. Works for me so far, but feedback is welcome.

Xaml:

<i:Interaction.Behaviors>
    <beh:EventToCommandBehavior Command="{Binding DropCommand}" Event="Drop" PassArguments="True" />
</i:Interaction.Behaviors>

ViewModel:

public ActionCommand<DragEventArgs> DropCommand { get; private set; }

this.DropCommand = new ActionCommand<DragEventArgs>(OnDrop);

private void OnDrop(DragEventArgs e)
{
    // ...
}

EventToCommandBehavior:

/// <summary>
/// Behavior that will connect an UI event to a viewmodel Command,
/// allowing the event arguments to be passed as the CommandParameter.
/// </summary>
public class EventToCommandBehavior : Behavior<FrameworkElement>
{
    private Delegate _handler;
    private EventInfo _oldEvent;

    // Event
    public string Event { get { return (string)GetValue(EventProperty); } set { SetValue(EventProperty, value); } }
    public static readonly DependencyProperty EventProperty = DependencyProperty.Register("Event", typeof(string), typeof(EventToCommandBehavior), new PropertyMetadata(null, OnEventChanged));

    // Command
    public ICommand Command { get { return (ICommand)GetValue(CommandProperty); } set { SetValue(CommandProperty, value); } }
    public static readonly DependencyProperty CommandProperty = DependencyProperty.Register("Command", typeof(ICommand), typeof(EventToCommandBehavior), new PropertyMetadata(null));

    // PassArguments (default: false)
    public bool PassArguments { get { return (bool)GetValue(PassArgumentsProperty); } set { SetValue(PassArgumentsProperty, value); } }
    public static readonly DependencyProperty PassArgumentsProperty = DependencyProperty.Register("PassArguments", typeof(bool), typeof(EventToCommandBehavior), new PropertyMetadata(false));


    private static void OnEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var beh = (EventToCommandBehavior)d;

        if (beh.AssociatedObject != null) // is not yet attached at initial load
            beh.AttachHandler((string)e.NewValue);
    }

    protected override void OnAttached()
    {
        AttachHandler(this.Event); // initial set
    }

    /// <summary>
    /// Attaches the handler to the event
    /// </summary>
    private void AttachHandler(string eventName)
    {
        // detach old event
        if (_oldEvent != null)
            _oldEvent.RemoveEventHandler(this.AssociatedObject, _handler);

        // attach new event
        if (!string.IsNullOrEmpty(eventName))
        {
            EventInfo ei = this.AssociatedObject.GetType().GetEvent(eventName);
            if (ei != null)
            {
                MethodInfo mi = this.GetType().GetMethod("ExecuteCommand", BindingFlags.Instance | BindingFlags.NonPublic);
                _handler = Delegate.CreateDelegate(ei.EventHandlerType, this, mi);
                ei.AddEventHandler(this.AssociatedObject, _handler);
                _oldEvent = ei; // store to detach in case the Event property changes
            }
            else
                throw new ArgumentException(string.Format("The event '{0}' was not found on type '{1}'", eventName, this.AssociatedObject.GetType().Name));
        }
    }

    /// <summary>
    /// Executes the Command
    /// </summary>
    private void ExecuteCommand(object sender, EventArgs e)
    {
        object parameter = this.PassArguments ? e : null;
        if (this.Command != null)
        {
            if (this.Command.CanExecute(parameter))
                this.Command.Execute(parameter);
        }
    }
}

ActionCommand:

public class ActionCommand<T> : ICommand
{
    public event EventHandler CanExecuteChanged;
    private Action<T> _action;

    public ActionCommand(Action<T> action)
    {
        _action = action;
    }

    public bool CanExecute(object parameter) { return true; }

    public void Execute(object parameter)
    {
        if (_action != null)
        {
            var castParameter = (T)Convert.ChangeType(parameter, typeof(T));
            _action(castParameter);
        }
    }
}

Angular HTML binding

Just simply use [innerHTML] attribute in your HTML, something like this below:

<div [innerHTML]="myVal"></div>

Ever had properties in your component that contain some html markup or entities that you need to display in your template? The traditional interpolation won't work, but the innerHTML property binding comes to the rescue.

Using {{myVal}} Does NOT work as expected! This won't pick up the HTML tags like <p>, <strong> etc and pass it only as strings...

Imagine you have this code in your component:

const myVal:string ='<strong>Stackoverflow</strong> is <em>helpful!</em>'

If you use {{myVal}}, you will get this in the view:

<strong>Stackoverflow</strong> is <em>helpful!</em>

but using [innerHTML]="myVal"makes the result as expected like this:

Stackoverflow is helpful!

Getting specified Node values from XML document

Just like you do for getting something from the CNode you also need to do for the ANode

XmlNodeList xnList = xml.SelectNodes("/Element[@*]");
foreach (XmlNode xn in xnList)
{
  XmlNode anode = xn.SelectSingleNode("ANode");
    if (anode!= null)
    {
        string id = anode["ID"].InnerText;
        string date = anode["Date"].InnerText;
        XmlNodeList CNodes = xn.SelectNodes("ANode/BNode/CNode");
        foreach (XmlNode node in CNodes)
        {
         XmlNode example = node.SelectSingleNode("Example");
         if (example != null)
         {
            string na = example["Name"].InnerText;
            string no = example["NO"].InnerText;
         }
        }
    }
}

Newtonsoft JSON Deserialize

You can implement a class that holds the fields you have in your JSON

class MyData
{
    public string t;
    public bool a;
    public object[] data;
    public string[][] type;
}

and then use the generic version of DeserializeObject:

MyData tmp = JsonConvert.DeserializeObject<MyData>(json);
foreach (string typeStr in tmp.type[0])
{
    // Do something with typeStr
}

Documentation: Serializing and Deserializing JSON

TypeError: a bytes-like object is required, not 'str' in python and CSV

I had the same issue with Python3. My code was writing into io.BytesIO().

Replacing with io.StringIO() solved.

True/False vs 0/1 in MySQL

Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.

This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.

This doesn't affect the database at all, since it's implemented in the application.

There is not really a BOOLEAN type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.

If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.

You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.

setImmediate vs. nextTick

In the comments in the answer, it does not explicitly state that nextTick shifted from Macrosemantics to Microsemantics.

before node 0.9 (when setImmediate was introduced), nextTick operated at the start of the next callstack.

since node 0.9, nextTick operates at the end of the existing callstack, whereas setImmediate is at the start of the next callstack

check out https://github.com/YuzuJS/setImmediate for tools and details

mongod command not recognized when trying to connect to a mongodb server

Seems like, The environmental variable is not correctly set up.

Go to the mongodb installation folder and get the executable files (mongo.exe, mongod.exe etc) location. (In my case) Something like :

C:\Program Files\MongoDB\Server\3.2\bin

Then go to :

Panel > System & Security > System > Advanced System Settings > Environment Variables 

Find the PATH variable and edit its value. Then add C:\Program Files\MongoDB\Server\3.2\bin and don't forget to separate each values with ;. Now confirm and exit.

tsconfig.json: Build:No inputs were found in config file

This can occur because typescript server can't find any files described by the include array:

// tsconfig.json
{
  //...
  "include": [
    "./src/"
  ],
}

If you're using VSCode, you can restart your TS server within your editor super easily to prompt it to re-evaluate the file like this:

  1. Navigate to any .ts or .tsx file

  2. Open the command palette (CMD + SHIFT + P on mac)

  3. Run the TypeScript: Restart TS server command:

    TypeScript - Restart TS Server

How to stop/shut down an elasticsearch node?

Stopping the service and killing the daemon are indeed the correct ways to shutdown a node. However, it's not recommended to do so directly if you want to take down a node for maintenance. In fact, if you don't have replicas you will lose data.

When you directly shutdown a node, Elasticsearch will wait for 1m (default time) for it to come back online. If it doesn't, then it will start to allocate the shards from that node to other nodes wasting lots of IO.

A typical approach would be to disable shard allocation temporarily by issuing:

PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "none"
  }
}

Now, when you take down a node, ES won't try to allocate shard from that node to other nodes and you can perform you maintenance activity and then once the node is up, you can enable shard allocation again:

PUT _cluster/settings
{
  "persistent": {
    "cluster.routing.allocation.enable": "all"
  }
}

Source: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/restart-upgrade.html

If you don't have replicas for all your indexes, then performing this type of activity will have downtime on some of the indexes. A cleaner way in this case would be to migrate all the shards to other nodes before taking the node down:

PUT _cluster/settings
{
  "transient" : {
    "cluster.routing.allocation.exclude._ip" : "10.0.0.1"
  }
}

This will move all shards from 10.0.0.1 to other nodes (will take time depending on the data). Once everything is done, you can kill the node, perform maintenance and get it back online. This is a slower operation and is not required if you have replicas.

(Instead of _ip, _id, _name with wildcards will work just fine.)

More information: https://www.elastic.co/guide/en/elasticsearch/reference/5.5/allocation-filtering.html

Other answers have explained how to kill a process.

WebAPI Multiple Put/Post parameters

We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:

webapi:

[HttpPost]
public string DoJson2(dynamic data)
{
   //whole:
   var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString()); 

   //or 
   var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());

   var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());

   string appName = data.AppName;
   int appInstanceID = data.AppInstanceID;
   string processGUID = data.ProcessGUID;
   int userID = data.UserID;
   string userName = data.UserName;
   var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());

   ...
}

The complex object type could be object, array and dictionary.

ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
       "AppInstanceID":"100",
       "ProcessGUID":"072af8c3-482a-4b1c??-890b-685ce2fcc75d",
       "UserID":"20",
       "UserName":"Jack",
       "NextActivityPerformers":{
           "39??c71004-d822-4c15-9ff2-94ca1068d745":[{
                 "UserID":10,
                 "UserName":"Smith"
           }]
       }}
...

Arduino error: does not name a type?

I found the solution to this problem in a "}". I did some changes to my sketch and forgot to check for "}" and I had an extra one. As soon as I deleted it and compiled everything was fine.

Executing Javascript code "on the spot" in Chrome?

Right click on the page and choose 'inspect element'. In the screen that opens now (the developer tools), clicking the second icon from the left @ the bottom of it opens a console, where you can type javascript. The console is linked to the current page.

"An access token is required to request this resource" while accessing an album / photo with Facebook php sdk

There are 3 things you need.

  1. You need to oAuth with the owner of those photos. (with the 'user_photos' extended permission)

  2. You need the access token (which you get returned in the URL box after the oAuth is done.)

  3. When those are complete you can then access the photos like so https://graph.facebook.com/me?access_token=ACCESS_TOKEN

You can find all of the information in more detail here: http://developers.facebook.com/docs/authentication

How to save as a new file and keep working on the original one in Vim?

The following command will create a copy in a new window. So you can continue see both original file and the new file.

:w {newfilename} | sp #

Slide a layout up from bottom of screen

Ok, there are two possible approaches. The simplest - is to use a sliding menu library. It allows creating a bottom sliding menu, it can animate the top container to make bottom visible, it suports both dragging it with your finger, or animating it programmatically via button (StaticDrawer).

Harder way - if you want to use Animations, as was already suggested. With animations you must FIRST change your layouts. So try first to make your layout change to the final state without any animations whatsoever. Because it is very likely that you are not laying out your views properly in RelativeLayout, so even though you show your bottom view, it remains obscured by the top one. Once you achieved proper layout change - all you need to do is to is to remember translations before layout and apply translate animation AFTER layout.

Simple Android RecyclerView example

Dependencies

compile 'com.android.support:appcompat-v7:25.3.1'
compile 'com.android.support:design:25.3.1'
compile 'com.android.support:multidex:1.0.1'
compile 'com.android.support:cardview-v7:25.3.1'
compile 'com.android.support:support-v4:25.3.1'
compile 'com.lguipeng.bubbleview:library:1.0.0'
compile 'com.larswerkman:HoloColorPicker:1.5'
compile 'com.mcxiaoke.volley:library-aar:1.0.0'

One Class For Click Item

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

public class RecyclerItemClickListener implements RecyclerView.OnItemTouchListener {
    private OnItemClickListener mListener;

    public interface OnItemClickListener {
        public void onItemClick(View view, int position);
    }

    GestureDetector mGestureDetector;

    public RecyclerItemClickListener(Context context, OnItemClickListener listener) {
        mListener = listener;
        mGestureDetector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener() {
            @Override
            public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }
        });
    }

    @Override
    public boolean onInterceptTouchEvent(RecyclerView view, MotionEvent e) {
        View childView = view.findChildViewUnder(e.getX(), e.getY());
        if (childView != null && mListener != null && mGestureDetector.onTouchEvent(e)) {
            mListener.onItemClick(childView, view.getChildPosition(childView));
            return true;
        }
        return false;
    }

    @Override
    public void onTouchEvent(RecyclerView view, MotionEvent motionEvent) { }

    @Override
    public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

    }


}

Second Class RecyclerView

import android.annotation.SuppressLint;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;

public class SLByTopics extends Fragment {


    public static ArrayList<MByTopics> byTopicsMainArrayList=new ArrayList<>();


    TabRefreshReceiver tabRefreshReceiver;
    RecyclerView recyclerView;
    SAdpByTopics sAdpByTopics;
    public ArrayList<MByTopics> mByTopicsArrayList=new ArrayList<>();
    ProgressDialog progressDialog;

    public SLByTopics(){
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.sl_fragment_by_topics, container, false);

        progressDialog = new ProgressDialog(getActivity());
        if (IsOnline.isNetworkAvailable(getActivity())) {
            getCategoryTree();
        } else{
            IsOnline.showNoInterNetMessage(getActivity());
        }
        tabRefreshReceiver = new TabRefreshReceiver();
       LocalBroadcastManager.getInstance(getContext()).registerReceiver(tabRefreshReceiver, new IntentFilter("BY_TOPICS"));

        setUpView(view);
        return view;
    }

    private void setUpView(View view) {

        recyclerView=(RecyclerView)view.findViewById(R.id.by_topics_list_recyclerView);
        LinearLayoutManager linearLayoutManager=new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(linearLayoutManager);
    }

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

        recyclerView.addOnItemTouchListener(new RecyclerItemClickListener(getActivity(), new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, final int position) {

                if (mByTopicsArrayList.get(position).getChild().size()>0){
                    Intent intent = new Intent(getActivity(), SByTopicCategory.class);
                    intent.putExtra("selectedCategoryName",mByTopicsArrayList.get(position).getCatname());
                    intent.putExtra("jsonData",mByTopicsArrayList.get(position).getMainTopicJson());
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                }else {
                    Intent intent = new Intent(getActivity(), SByCategoryQuestionList.class);
                    intent.putExtra("selectedSubCategoryName",mByTopicsArrayList.get(position).getCatname());
                    intent.putExtra("catID",mByTopicsArrayList.get(position).getId());
                    startActivity(intent);
                    getActivity().overridePendingTransition(R.anim.activity_in, R.anim.activity_out);
                }
            }
        }));

    }

    private class TabRefreshReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                FragmentTransaction ft = getFragmentManager().beginTransaction();
                ft.detach(SLByTopics.this).attach(SLByTopics.this).commit();
                LocalBroadcastManager.getInstance(getContext()).unregisterReceiver(tabRefreshReceiver);
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    private void getCategoryTree() {
        progressDialog.setMessage("Please Wait...");
        progressDialog.setCancelable(false);
        progressDialog.show();

        StringRequest stringRequest = new StringRequest(Request.Method.POST, Const.HOSTNAME + Const.STUDENT_GET_CATEGORY_TREE,
                new Response.Listener<String>() {
                    @SuppressLint("LongLogTag")
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject object = new JSONObject(response);
                            String status = object.getString("status");
                            int i = Integer.parseInt(status);

                            switch (i) {

                                case 0:
                                    progressDialog.dismiss();
//                                    Toast.makeText(getActivity(), "getCategorySuccess", Toast.LENGTH_SHORT).show();
                                    Log.e("getCategoryTree Response", "getCategoryTree Response : " + response);

                                    try {    
                                        byTopicsMainArrayList.clear();
                                        JSONArray info = object.getJSONArray("info");
                                        if (info.length() > 0) {
                                            for (i = 0; i < info.length(); i++) {
                                                JSONObject data = info.getJSONObject(i);
                                                MByTopics mByTopics = new MByTopics();
                                                mByTopics.setId(data.getString("id"));
                                                mByTopics.setCatname(data.getString("catname"));
                                                mByTopics.setMainTopicJson(data.toString());

                                                JSONArray topicChildren = data.getJSONArray("children");
                                                ArrayList<SMByTopicCategory> byChildrenArrayList = new ArrayList<>();

                                                for (int j = 0; j < topicChildren.length(); j++) {
                                                    JSONObject topicChildrenData = topicChildren.getJSONObject(j);
                                                    SMByTopicCategory smByTopicCategory = new SMByTopicCategory();
                                                    smByTopicCategory.setId(topicChildrenData.getString("id"));
                                                    smByTopicCategory.setCatname(topicChildrenData.getString("catname"));
                                                    smByTopicCategory.setChildTopicJson(topicChildrenData.toString());

                                                    JSONArray topicChildrenQuestion = topicChildrenData.getJSONArray("children");
                                                    ArrayList<SMByTopicSubCategory> byChildrenSubArrayList = new ArrayList<>();

                                                    for (int k = 0; k < topicChildrenQuestion.length(); k++) {
                                                        JSONObject topicChildrenSubData = topicChildrenQuestion.getJSONObject(k);
                                                        SMByTopicSubCategory smByTopicSubCategory = new SMByTopicSubCategory();
                                                        smByTopicSubCategory.setId(topicChildrenSubData.getString("id"));
                                                        smByTopicSubCategory.setCatname(topicChildrenSubData.getString("catname"));
                                                        smByTopicSubCategory.setChildSubTopicJson(topicChildrenSubData.toString());

                                                        byChildrenSubArrayList.add(smByTopicSubCategory);
                                                    }

                                                    smByTopicCategory.setQuestions(byChildrenSubArrayList);

                                                    byChildrenArrayList.add(smByTopicCategory);
                                                }
                                                mByTopics.setChild(byChildrenArrayList);
                                                byTopicsMainArrayList.add(mByTopics);
                                            }


                                            mByTopicsArrayList.clear();
                                            mByTopicsArrayList=byTopicsMainArrayList;
                                            sAdpByTopics=new SAdpByTopics(mByTopicsArrayList,getActivity());
                                            recyclerView.setAdapter(sAdpByTopics);
                                            sAdpByTopics.notifyDataSetChanged();

                                        }

                                    }catch (Exception e){
                                        e.printStackTrace();
                                    }
                                    break;

                                default:
                                    progressDialog.dismiss();
//                                    Toast.makeText(getActivity(), "getCategoryError : " + response, Toast.LENGTH_SHORT).show();
                                    Log.e("getCategoryTree Not Response", "getCategoryTree Uploading Not Response : " + response);
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        progressDialog.dismiss();
                        Log.e("getCategoryTree Error :","getCategoryTree Error :"+error.getMessage());
//                        Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_LONG).show();
                    }
                }){

        };/* {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> map = new HashMap<String, String>();
//                map.put("uid", String.valueOf(ConfigManager.getUserId()));
                return map;
            }
        };*/

        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                0,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

        RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
        requestQueue.add(stringRequest);
    }
}

Adapter Class For Recycler Item

import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;

public class SAdpByTopics extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        ArrayList<MByTopics> topicsArrayList=new ArrayList<>();
        Activity activity;

     public SAdpByTopics(ArrayList<MByTopics> topicsArrayList,Activity activity){
        this.topicsArrayList=topicsArrayList;
        this.activity=activity;
     }

     @Override
     public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemeView= LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_by_topic_list,parent,false);
        RecyclerView.ViewHolder holder=new Holder(itemeView);
        holder.setIsRecyclable(false);
        return holder;
     }

     @Override
     public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
         final Holder classHolder = (Holder) holder;
         try{
             classHolder.txt_topic_name.setText(topicsArrayList.get(position).getCatname());
         }catch (Exception e){
             e.printStackTrace();
         }
     }

     @Override
     public int getItemCount() {
        return topicsArrayList.size();
     }


class Holder extends RecyclerView.ViewHolder implements View.OnClickListener {
    TextView txt_topic_name;

    public Holder(View itemView) {
        super(itemView);
        txt_topic_name = (TextView) itemView.findViewById(R.id.txt_topic_name);
    }

    @Override
    public void onClick(View v) {

    }
}
}

Module Class

public class MByTopics {

    String id;
    String topicName;
    String catname;
    String MainTopicJson;
    ArrayList<SMByTopicCategory> child;
    ArrayList<SMByTopicSubCategory> questions;

    public void setId(String id){
        this.id=id;
    }
    public String getId(){
        return  id;
    }

    public void setCatname(String catname) {
        this.catname = catname;
    }

    public String getCatname() {
        return catname;
    }

    public void setTopicName(String topicName) {
        this.topicName = topicName;
    }
    public String getTopicName() {
        return topicName;
    }

    public void setChild(ArrayList<SMByTopicCategory> child) {
        this.child = child;
    }

    public String getMainTopicJson() {
        return MainTopicJson;
    }

    public void setMainTopicJson(String mainTopicJson) {
        MainTopicJson = mainTopicJson;
    }

    public ArrayList<SMByTopicCategory> getChild() {
        return child;
    }

    public void setQuestions(ArrayList<SMByTopicSubCategory> questions) {
        this.questions = questions;
    }

    public ArrayList<SMByTopicSubCategory> getQuestions() {
        return questions;
    }

    public ArrayList<MByTopics> getByTopicList() {
        ArrayList<MByTopics> mByTopicsArrayList = new ArrayList<>();

        for (int i=0;i<11;i++){
            MByTopics mQuestionBankCategory=new MByTopics();

            if (i==1 || i== 5|| i==9){
                mQuestionBankCategory.setTopicName("Microeconomics");
            }else  if (i==2 || i== 10|| i==6) {
                mQuestionBankCategory.setTopicName("Macroeconomics");
            }else {
                mQuestionBankCategory.setTopicName("Current Isssues");
            }

            mByTopicsArrayList.add(mQuestionBankCategory);
        }

        return mByTopicsArrayList;
    }

}

How can I use different certificates on specific connections?

I've had to do something like this when using commons-httpclient to access an internal https server with a self-signed certificate. Yes, our solution was to create a custom TrustManager that simply passed everything (logging a debug message).

This comes down to having our own SSLSocketFactory that creates SSL sockets from our local SSLContext, which is set up to have only our local TrustManager associated with it. You don't need to go near a keystore/certstore at all.

So this is in our LocalSSLSocketFactory:

static {
    try {
        SSL_CONTEXT = SSLContext.getInstance("SSL");
        SSL_CONTEXT.init(null, new TrustManager[] { new LocalSSLTrustManager() }, null);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    } catch (KeyManagementException e) {
        throw new RuntimeException("Unable to initialise SSL context", e);
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    LOG.trace("createSocket(host => {}, port => {})", new Object[] { host, new Integer(port) });

    return SSL_CONTEXT.getSocketFactory().createSocket(host, port);
}

Along with other methods implementing SecureProtocolSocketFactory. LocalSSLTrustManager is the aforementioned dummy trust manager implementation.

Easy way to concatenate two byte arrays

Another way is to use a utility function (you could make this a static method of a generic utility class if you like):

byte[] concat(byte[]...arrays)
{
    // Determine the length of the result array
    int totalLength = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        totalLength += arrays[i].length;
    }

    // create the result array
    byte[] result = new byte[totalLength];

    // copy the source arrays into the result array
    int currentIndex = 0;
    for (int i = 0; i < arrays.length; i++)
    {
        System.arraycopy(arrays[i], 0, result, currentIndex, arrays[i].length);
        currentIndex += arrays[i].length;
    }

    return result;
}

Invoke like so:

byte[] a;
byte[] b;
byte[] result = concat(a, b);

It will also work for concatenating 3, 4, 5 arrays, etc.

Doing it this way gives you the advantage of fast arraycopy code which is also very easy to read and maintain.

How to save Excel Workbook to Desktop regardless of user?

You've mentioned that they each have their own machines, but if they need to log onto a co-workers machine, and then use the file, saving it through "C:\Users\Public\Desktop\" will make it available to different usernames.

Public Sub SaveToDesktop()
    ThisWorkbook.SaveAs Filename:="C:\Users\Public\Desktop\" & ThisWorkbook.Name & "_copy", _ 
    FileFormat:=xlOpenXMLWorkbookMacroEnabled
End Sub

I'm not sure whether this would be a requirement, but may help!

What is the purpose of a self executing function in javascript?

It looks like this question has been answered all ready, but I'll post my input anyway.

I know when I like to use self-executing functions.

var myObject = {
    childObject: new function(){
        // bunch of code
    },
    objVar1: <value>,
    objVar2: <value>
}

The function allows me to use some extra code to define the childObjects attributes and properties for cleaner code, such as setting commonly used variables or executing mathematic equations; Oh! or error checking. as opposed to being limited to nested object instantiation syntax of...

object: {
    childObject: {
        childObject: {<value>, <value>, <value>}
    }, 
    objVar1: <value>,
    objVar2: <value>
}

Coding in general has a lot of obscure ways of doing a lot of the same things, making you wonder, "Why bother?" But new situations keep popping up where you can no longer rely on basic/core principals alone.

Windows batch script to unhide files hidden by virus

this will unhide all files and folders on your computer

attrib -r -s -h /S /D

How do I create a sequence in MySQL?

By creating the increment table you should be aware not to delete inserted rows. reason for this is to avoid storing large dumb data in db with ID-s in it. Otherwise in case of mysql restart it would get max existing row and continue increment from that point as mention in documentation http://dev.mysql.com/doc/refman/5.0/en/innodb-auto-increment-handling.html

How do I use FileSystemObject in VBA?

After adding the reference, I had to use

Dim fso As New Scripting.FileSystemObject

Warning as error - How to get rid of these

To treat all compiler warnings as compilation errors

  1. With a project selected in Solution Explorer, on the Project menu, click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Treat all warnings as errors check box. (or select the build setting and change the “treat warnings as errors” settings to true.)

and if you want to get rid of it

To disable all compiler warnings

  1. With a project selected in Solution Explorer, on the Project menu click Properties.
  2. Click the Compile tab. (or Build Tab may be there)
  3. Select the Disable all warnings check box. (or select the build setting and change the “treat warnings as errors” settings to false.)

Install apk without downloading

you can use this code .may be solve the problem

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://192.168.43.1:6789/mobile_base/test.apk"));
startActivity(intent);

How to convert current date into string in java?

// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();

Difference between "process.stdout.write" and "console.log" in node.js?

Another important difference in this context would with process.stdout.clearLine() and process.stdout.cursorTo(0).

This would be useful if you want to show percentage of download or processing in the only one line. If you use clearLine(), cursorTo() with console.log() it doesn't work because it also append \n to the text. Just try out this example:

var waitInterval = 500;
var totalTime = 5000;
var currentInterval = 0;

function showPercentage(percentage){
    process.stdout.clearLine();
    process.stdout.cursorTo(0);
    console.log(`Processing ${percentage}%...` ); //replace this line with process.stdout.write(`Processing ${percentage}%...`);
}

var interval = setInterval(function(){
 currentInterval += waitInterval;
 showPercentage((currentInterval/totalTime) * 100);
}, waitInterval);

setTimeout(function(){
 clearInterval(interval); 
}, totalTime);

Unit testing with mockito for constructors

Here is the code to mock this functionality using PowerMockito API.

Second mockedSecond = PowerMockito.mock(Second.class);
PowerMockito.whenNew(Second.class).withNoArguments().thenReturn(mockedSecond);

You need to use Powermockito runner and need to add required test classes (comma separated ) which are required to be mocked by powermock API .

@RunWith(PowerMockRunner.class)
@PrepareForTest({First.class,Second.class})
class TestClassName{
    // your testing code
}

Reverse engineering from an APK file to a project

Another tool that you may want to use is APK Studio It relies howewer on third party tools: Apktool, jadx, ADB and Uber APK signer that you need to download separately.

Detect if user is scrolling

You just said javascript in your tags, so @Wampie Driessen post could helps you.

I want also to contribute, so you can use the following when using jQuery if you need it.

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.wheelDelta< 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

Another example:

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});?

How to play a local video with Swift?

None of the above worked for me Swift 5 for Local Video Player

after reading apple documentation I was able to create simple example for playing video from Local resources

Here is code snip

import UIKit
import AVKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //TODO : Make Sure Add and copy "SampleVideo.mp4" file in project before play
    }

    @IBAction func playLocalVideo(_ sender: Any) {

        guard let path = Bundle.main.path(forResource: "SampleVideo", ofType: "mp4") else {
            return
        }
        let videoURL = NSURL(fileURLWithPath: path)

        // Create an AVPlayer, passing it the local video url path
        let player = AVPlayer(url: videoURL as URL)
        let controller = AVPlayerViewController()
        controller.player = player
        present(controller, animated: true) {
            player.play()
        }
    }

}

PS: Make sure you don't forget to add and copy video named "SampleVideo.mp4" in project

A Java collection of value pairs? (tuples?)

I mean, even though there is no Pair class in Java there is something pretty simmilar: Map.Entry

Map.Entry Documentation

This is (simplifying quite a bit) what HashMap , or actually any Map stores.

You can create an instance of Map store your values in it and get the entry set. You will end up with a Set<Map.Entry<K,V>> which effectively is what you want.

So:

public static void main(String []args)
{    
    HashMap<String, Integer> values = new HashMap<String,Integer>();
    values.put("A", 235);//your custom data, the types may be different
    //more data insertions....
    Set<Map.Entry<String,Integer>> list = values.entrySet();//your list 
    //do as you may with it
}

Inserting an item in a Tuple

Since tuples are immutable, this will result in a new tuple. Just place it back where you got the old one.

sometuple + (someitem,)

JavaScript: Global variables after Ajax requests

What you expect is the synchronous (blocking) type request.

var it_works = false;

jQuery.ajax({
  type: "POST",
  url: 'some_file.php',
  success: function (data) {
    it_works = true;
  }, 
  async: false // <- this turns it into synchronous
});?

// Execution is BLOCKED until request finishes.

// it_works is available
alert(it_works);

Requests are asynchronous (non-blocking) by default which means that the browser won't wait for them to be completed in order to continue its work. That's why your alert got wrong result.

Now, with jQuery.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.


The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function as soon as the request is finished. This is preferred because blocking execution means blocking the UI which is unacceptable. Do it this way:

$.post("some_file.php", '', function(data) {
    iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
    // You should do your work here that depends on the result of the request!
    alert(param)
}

// All code here should be INDEPENDENT of the result of your AJAX request
// ...

Asynchronous programming is slightly more complicated because the consequence of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly better because they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronous programming is disrespectful and should not be employed in applications which are used by people.

Douglas Crockford (YUI Blog)

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

As an addition to the solution:

ul li:before {
 content: '?'; 
}

You can use any SVG icon as the content, such as the Font Aswesome.

enter image description here

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
  padding-left: 0;_x000D_
}_x000D_
li {_x000D_
  position: relative;_x000D_
  padding-left: 1.5em;  /* space to preserve indentation on wrap */_x000D_
}_x000D_
li:before {_x000D_
  content: '';  /* placeholder for the SVG */_x000D_
  position: absolute;_x000D_
  left: 0;  /* place the SVG at the start of the padding */_x000D_
  width: 1em;_x000D_
  height: 1em;_x000D_
  background: url("data:image/svg+xml;utf8,<?xml version='1.0' encoding='utf-8'?><svg width='18' height='18' viewBox='0 0 1792 1792' xmlns='http://www.w3.org/2000/svg'><path d='M1671 566q0 40-28 68l-724 724-136 136q-28 28-68 28t-68-28l-136-136-362-362q-28-28-28-68t28-68l136-136q28-28 68-28t68 28l294 295 656-657q28-28 68-28t68 28l136 136q28 28 28 68z'/></svg>") no-repeat;_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>This is my text, it's pretty long so it needs to wrap. Note that wrapping preserves the indentation that bullets had!</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note: To solve the wrapping problem that other answers had:

  • we reserve 1.5m ems of space at the left of each <li>
  • then position the SVG at the start of that space (position: absolute; left: 0)

Here are more Font Awesome black icons.

Check this CODEPEN to see how you can add colors and change their size.

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

How to get string objects instead of Unicode from JSON?

here is a recursive encoder written in C: https://github.com/axiros/nested_encode

Performance overhead for "average" structures around 10% compared to json.loads.

python speed.py                                                                                            
  json loads            [0.16sec]: {u'a': [{u'b': [[1, 2, [u'\xd6ster..
  json loads + encoding [0.18sec]: {'a': [{'b': [[1, 2, ['\xc3\x96ster.
  time overhead in percent: 9%

using this teststructure:

import json, nested_encode, time

s = """
{
  "firstName": "Jos\\u0301",
  "lastName": "Smith",
  "isAlive": true,
  "age": 25,
  "address": {
    "streetAddress": "21 2nd Street",
    "city": "\\u00d6sterreich",
    "state": "NY",
    "postalCode": "10021-3100"
  },
  "phoneNumbers": [
    {
      "type": "home",
      "number": "212 555-1234"
    },
    {
      "type": "office",
      "number": "646 555-4567"
    }
  ],
  "children": [],
  "spouse": null,
  "a": [{"b": [[1, 2, ["\\u00d6sterreich"]]]}]
}
"""


t1 = time.time()
for i in xrange(10000):
    u = json.loads(s)
dt_json = time.time() - t1

t1 = time.time()
for i in xrange(10000):
    b = nested_encode.encode_nested(json.loads(s))
dt_json_enc = time.time() - t1

print "json loads            [%.2fsec]: %s..." % (dt_json, str(u)[:20])
print "json loads + encoding [%.2fsec]: %s..." % (dt_json_enc, str(b)[:20])

print "time overhead in percent: %i%%"  % (100 * (dt_json_enc - dt_json)/dt_json)

Pandas DataFrame to List of Dictionaries

Edit

As John Galt mentions in his answer , you should probably instead use df.to_dict('records'). It's faster than transposing manually.

In [20]: timeit df.T.to_dict().values()
1000 loops, best of 3: 395 µs per loop

In [21]: timeit df.to_dict('records')
10000 loops, best of 3: 53 µs per loop

Original answer

Use df.T.to_dict().values(), like below:

In [1]: df
Out[1]:
   customer  item1   item2   item3
0         1  apple    milk  tomato
1         2  water  orange  potato
2         3  juice   mango   chips

In [2]: df.T.to_dict().values()
Out[2]:
[{'customer': 1.0, 'item1': 'apple', 'item2': 'milk', 'item3': 'tomato'},
 {'customer': 2.0, 'item1': 'water', 'item2': 'orange', 'item3': 'potato'},
 {'customer': 3.0, 'item1': 'juice', 'item2': 'mango', 'item3': 'chips'}]

Bootstrap 4 dropdown with search

I took the answer from PirateApp and made it reusable. If you include this script it will transform all selects with the class '.dropdown' to searchable dropdowns.

_x000D_
_x000D_
$('.dropdown').each(function(index, dropdown) {

  //Find the input search box
  let search = $(dropdown).find('.search');

  //Find every item inside the dropdown
  let items = $(dropdown).find('.dropdown-item');

  //Capture the event when user types into the search box
  $(search).on('input', function() {
    filter($(search).val().trim().toLowerCase())
  });

  //For every word entered by the user, check if the symbol starts with that word
  //If it does show the symbol, else hide it
  function filter(word) {
    let length = items.length
    let collection = []
    let hidden = 0
    for (let i = 0; i < length; i++) {
      if (items[i].value.toString().toLowerCase().includes(word)) {
        $(items[i]).show()
      } else {
        $(items[i]).hide()
        hidden++
      }
    }

    //If all items are hidden, show the empty view
    if (hidden === length) {
      $(dropdown).find('.dropdown_empty').show();
    } else {
      $(dropdown).find('.dropdown_empty').hide();
    }
  }

  //If the user clicks on any item, set the title of the button as the text of the item
  $(dropdown).find('.dropdown-menu').find('.menuItems').on('click', '.dropdown-item', function() {
    $(dropdown).find('.dropdown-toggle').text($(this)[0].value);
    $(dropdown).find('.dropdown-toggle').dropdown('toggle');
  })
});
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />

<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>

<div class="dropdown">
  <button class="btn btn-sm btn-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
        Benutzer
    </button>
  <div class="dropdown-menu" aria-labelledby="dropdown_user">
    <form class="px-4 py-2">
      <input type="search" class="form-control search" placeholder="Suche.." autofocus="autofocus">
    </form>
    <div class="menuItems">
      <input type="button" class="dropdown-item" type="button" value="Test1" />
      <input type="button" class="dropdown-item" type="button" value="Test2" />
      <input type="button" class="dropdown-item" type="button" value="Test3" />
    </div>
    <div style="display:none;" class="dropdown-header dropdown_empty">No entry found</div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

How to extract year and month from date in PostgreSQL without using to_char() function?

date_part(text, timestamp)

e.g.

date_part('month', timestamp '2001-02-16 20:38:40'),
date_part('year', timestamp '2001-02-16 20:38:40') 

http://www.postgresql.org/docs/8.0/interactive/functions-datetime.html

What causes HttpHostConnectException?

In my case the issue was a missing 's' in the HTTP URL. Error was: "HttpHostConnectException: Connect to someendpoint.com:80 [someendpoint.com/127.0.0.1] failed: Connection refused" End point and IP obviously changed to protect the network.

How to compare different branches in Visual Studio Code

In the 11.0.0 version released in November 2020, GitLens views are now by default all placed under the source control tab in VSCode, including the Search & Compare view which has the compare branches functionality:

Compare working branch

It can be changed back to the side bar layout in GitLens settings:

Layout settings

CSS /JS to prevent dragging of ghost image?

I found that for IE, you must add the draggable="false" attribute to images and anchors to prevent dragging. the CSS options work for all other browsers. I did this in jQuery:

$("a").attr('draggable', false); 
$("img").attr('draggable', false);

Cannot instantiate the type List<Product>

List is an interface. You need a specific class in the end so either try

List l = new ArrayList();

or

List l = new LinkedList();

Whichever suit your needs.

How can I output the value of an enum class in C++11

It is possible to get your second example (i.e., the one using a scoped enum) to work using the same syntax as unscoped enums. Furthermore, the solution is generic and will work for all scoped enums, versus writing code for each scoped enum (as shown in the answer provided by @ForEveR).

The solution is to write a generic operator<< function which will work for any scoped enum. The solution employs SFINAE via std::enable_if and is as follows.

#include <iostream>
#include <type_traits>

// Scoped enum
enum class Color
{
    Red,
    Green,
    Blue
};

// Unscoped enum
enum Orientation
{
    Horizontal,
    Vertical
};

// Another scoped enum
enum class ExecStatus
{
    Idle,
    Started,
    Running
};

template<typename T>
std::ostream& operator<<(typename std::enable_if<std::is_enum<T>::value, std::ostream>::type& stream, const T& e)
{
    return stream << static_cast<typename std::underlying_type<T>::type>(e);
}

int main()
{
    std::cout << Color::Blue << "\n";
    std::cout << Vertical << "\n";
    std::cout << ExecStatus::Running << "\n";
    return 0;
}

How to measure the a time-span in seconds using System.currentTimeMillis()?

From your code it would appear that you are trying to measure how long a computation took (as opposed to trying to figure out what the current time is).

In that case, you need to call currentTimeMillis before and after the computation, take the difference, and divide the result by 1000 to convert milliseconds to seconds.

Creating hard and soft links using PowerShell

I found this the simple way without external help. Yes, it uses an archaic DOS command but it works, it's easy, and it's clear.

$target = cmd /c dir /a:l | ? { $_ -match "mySymLink \[.*\]$" } | % `
{
    $_.Split([char[]] @( '[', ']' ), [StringSplitOptions]::RemoveEmptyEntries)[1]
}

This uses the DOS dir command to find all entries with the symbolic link attribute, filters on the specific link name followed by target "[]" brackets, and for each - presumably one - extracts just the target string.

How to hide console window in python?

In linux, just run it, no problem. In Windows, you want to use the pythonw executable.

Update

Okay, if I understand the question in the comments, you're asking how to make the command window in which you've started the bot from the command line go away afterwards?

  • UNIX (Linux)

$ nohup mypythonprog &

  • Windows

C:/> start pythonw mypythonprog

I think that's right. In any case, now you can close the terminal.

PHP post_max_size overrides upload_max_filesize

upload_max_filesize is the limit of any single file. post_max_size is the limit of the entire body of the request, which could include multiple files.

Given post_max_size = 20M and upload_max_filesize = 6M you could upload up to 3 files of 6M each. If instead post_max_size = 6M and upload_max_filesize = 20M then you could only upload one 6M file before hitting post_max_size. It doesn't help to have upload_max_size > post_max_size.

It's not obvious how to recognize going over post_max_size. $_POST and $_FILES will be empty, but $_SERVER['CONTENT_LENGTH'] will be > 0. If the client just didn't upload any post variables or files, then $_SERVER['CONTENT_LENGTH'] will be 0.

What is Join() in jQuery?

I use join to separate the word in array with "and, or , / , &"

EXAMPLE

HTML

<p>London Mexico Canada</p>
<div></div>

JS

 newText = $("p").text().split(" ").join(" or ");
 $('div').text(newText);

Results

London or Mexico or Canada

Tokenizing strings in C

Here's an example of strtok usage, keep in mind that strtok is destructive of its input string (and therefore can't ever be used on a string constant

char *p = strtok(str, " ");
while(p != NULL) {
    printf("%s\n", p);
    p = strtok(NULL, " ");
}

Basically the thing to note is that passing a NULL as the first parameter to strtok tells it to get the next token from the string it was previously tokenizing.

jQuery - How to dynamically add a validation rule

As well as making sure that you have first called $("#myForm").validate();, make sure that your dynamic control has been added to the DOM before adding the validation rules.

How do I rename a repository on GitHub?

  1. open this url (https://github.com/) from your browser

  2. Go to repositories at the Right end of the page

  3. Open the link of repository that you want to rename

  4. click Settings (you will find in the Navigation bar)

  5. At the top you will find a box Called (Repository name) where you write the new name

  6. Press Rename

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

Here is some testing under Solaris and Linux 64-bit

Solaris 10 - SPARC - T5220 machine with 32 GB RAM (and about 9 GB free)

$ java -XX:PermSize=128M -XX:MaxPermSize=256M -Xms512m -Xmx3750m MaxMemory
Error occurred during initialization of VM
Could not reserve space for ObjectStartArray
$ java -XX:PermSize=128M -XX:MaxPermSize=256M -Xms512m -Xmx3700m MaxMemory
Total Memory: 518520832 (494.5 MiB)
Max Memory:   3451912192 (3292.0 MiB)
Free Memory:  515815488 (491.91998291015625 MiB)
Current PID is: 28274
Waiting for user to press Enter to finish ...

$ java -version
java version "1.6.0_30"
Java(TM) SE Runtime Environment (build 1.6.0_30-b12)
Java HotSpot(TM) Server VM (build 20.5-b03, mixed mode)

$ which java
/usr/bin/java
$ file /usr/bin/java
/usr/bin/java: ELF 32-bit MSB executable SPARC Version 1, dynamically linked, not stripped, no debugging information available

$ prstat -p 28274
   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP
28274 user1     670M   32M sleep   59    0   0:00:00 0.0% java/35

BTW: Apparently Java does not allocate much actual memory with the startup. It seemed to take only about 100 MB per instance started (I started 10)

Solaris 10 - x86 - VMWare VM with 8 GB RAM (about 3 GB free*)

The 3 GB free RAM is not really true. There is a large chunk of RAM that ZFS caches use, but I don't have root access to check how much exactly

$ java -XX:PermSize=128M -XX:MaxPermSize=256M -Xms512m -Xmx3650m MaxMemory
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

$ java -XX:PermSize=128M -XX:MaxPermSize=256M -Xms512m -Xmx3600m MaxMemory
Total Memory: 516423680 (492.5 MiB)
Max Memory:   3355443200 (3200.0 MiB)
Free Memory:  513718336 (489.91998291015625 MiB)
Current PID is: 26841
Waiting for user to press Enter to finish ...

$ java -version
java version "1.6.0_41"
Java(TM) SE Runtime Environment (build 1.6.0_41-b02)
Java HotSpot(TM) Server VM (build 20.14-b01, mixed mode)

$ which java
/usr/bin/java

$ file /usr/bin/java
/usr/bin/java:  ELF 32-bit LSB executable 80386 Version 1 [FPU], dynamically linked, not stripped, no debugging information available

$ prstat -p 26841
   PID USERNAME  SIZE   RSS STATE  PRI NICE      TIME  CPU PROCESS/NLWP
26841 user1     665M   22M sleep   59    0   0:00:00 0.0% java/12

RedHat 5.5 - x86 - VMWare VM with 4 GB RAM (about 3.8 GB used - 200 MB in buffers and 3.1 GB in caches, so about 3 GB free)

$ alias java='$HOME/jre/jre1.6.0_34/bin/java'

$ java -XX:PermSize=128M -XX:MaxPermSize=256M -Xms512m -Xmx3500m MaxMemory
Error occurred during initialization of VM
Could not reserve enough space for object heap
Could not create the Java virtual machine.

$ java -XX:PermSize=128M -XX:MaxPermSize=256M -Xms512m -Xmx3450m MaxMemory
Total Memory: 514523136 (490.6875 MiB)
Max Memory:   3215654912 (3066.6875 MiB)
Free Memory:  511838768 (488.1274871826172 MiB)
Current PID is: 21879
Waiting for user to press Enter to finish ...

$ java -version
java version "1.6.0_34"
Java(TM) SE Runtime Environment (build 1.6.0_34-b04)
Java HotSpot(TM) Server VM (build 20.9-b04, mixed mode)

$ file $HOME/jre/jre1.6.0_34/bin/java
/home/user1/jre/jre1.6.0_34/bin/java: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.2.5, dynamically linked (uses shared libs), for GNU/Linux 2.2.5, not stripped

$ cat /proc/21879/status | grep ^Vm
VmPeak:  3882796 kB
VmSize:  3882796 kB
VmLck:         0 kB
VmHWM:     12520 kB
VmRSS:     12520 kB
VmData:  3867424 kB
VmStk:        88 kB
VmExe:        40 kB
VmLib:     14804 kB
VmPTE:        96 kB

Same machine using JRE 7

$ alias java='$HOME/jre/jre1.7.0_21/bin/java'

$ java -XX:PermSize=128M -XX:MaxPermSize=256M -Xms512m -Xmx3500m MaxMemory
Error occurred during initialization of VM
Could not reserve enough space for object heap
Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

$ java -XX:PermSize=128M -XX:MaxPermSize=256M -Xms512m -Xmx3450m MaxMemory
Total Memory: 514523136 (490.6875 MiB)
Max Memory:   3215654912 (3066.6875 MiB)
Free Memory:  511838672 (488.1273956298828 MiB)
Current PID is: 23026
Waiting for user to press Enter to finish ...

$ java -version
java version "1.7.0_21"
Java(TM) SE Runtime Environment (build 1.7.0_21-b11)
Java HotSpot(TM) Server VM (build 23.21-b01, mixed mode)

$ file $HOME/jre/jre1.7.0_21/bin/java
/home/user1/jre/jre1.7.0_21/bin/java: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), for GNU/Linux 2.6.9, not stripped

$ cat /proc/23026/status | grep ^Vm
VmPeak:  4040288 kB
VmSize:  4040288 kB
VmLck:         0 kB
VmHWM:     13468 kB
VmRSS:     13468 kB
VmData:  4024800 kB
VmStk:        88 kB
VmExe:         4 kB
VmLib:     10044 kB
VmPTE:       112 kB

How to do a timer in Angular 5

You can simply use setInterval to create such timer in Angular, Use this Code for timer -

timeLeft: number = 60;
  interval;

startTimer() {
    this.interval = setInterval(() => {
      if(this.timeLeft > 0) {
        this.timeLeft--;
      } else {
        this.timeLeft = 60;
      }
    },1000)
  }

  pauseTimer() {
    clearInterval(this.interval);
  }

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{timeLeft}} Seconds Left....</p>

Working Example

Another way using Observable timer like below -

import { timer } from 'rxjs';

observableTimer() {
    const source = timer(1000, 2000);
    const abc = source.subscribe(val => {
      console.log(val, '-');
      this.subscribeTimer = this.timeLeft - val;
    });
  }

<p (click)="observableTimer()">Start Observable timer</p> {{subscribeTimer}}

Working Example

For more information read here