Programs & Examples On #Process monitoring

A top-like utility for monitoring CUDA activity on a GPU

I'm not aware of anything that combines this information, but you can use the nvidia-smi tool to get the raw data, like so (thanks to @jmsu for the tip on -l):

$ nvidia-smi -q -g 0 -d UTILIZATION -l

==============NVSMI LOG==============

Timestamp                       : Tue Nov 22 11:50:05 2011

Driver Version                  : 275.19

Attached GPUs                   : 2

GPU 0:1:0
    Utilization
        Gpu                     : 0 %
        Memory                  : 0 %

PHP Convert String into Float/Double

If the function floatval does not work you can try to make this :

    $string = "2968789218";
    $float = $string * 1.0;
    echo $float;

But for me all the previous answer worked ( try it in http://writecodeonline.com/php/ ) Maybe the problem is on your server ?

PHP - Debugging Curl

Here is a simpler code for the same:

   curl_setopt($ch, CURLOPT_VERBOSE, 1);
   curl_setopt($ch, CURLOPT_STDERR, $fp);

where $fp is a file handle to output errors. For example:

   $fp = fopen(dirname(__FILE__).'/errorlog.txt', 'w');

( Read on http://curl.haxx.se/mail/curlphp-2008-03/0064.html )

Node.js server that accepts POST requests

Receive POST and GET request in nodejs :

1).Server

    var http = require('http');
    var server = http.createServer ( function(request,response){

    response.writeHead(200,{"Content-Type":"text\plain"});
    if(request.method == "GET")
        {
            response.end("received GET request.")
        }
    else if(request.method == "POST")
        {
            response.end("received POST request.");
        }
    else
        {
            response.end("Undefined request .");
        }
});

server.listen(8000);
console.log("Server running on port 8000");

2). Client :

var http = require('http');

var option = {
    hostname : "localhost" ,
    port : 8000 ,
    method : "POST",
    path : "/"
} 

    var request = http.request(option , function(resp){
       resp.on("data",function(chunck){
           console.log(chunck.toString());
       }) 
    })
    request.end();

Illegal Escape Character "\"

do two \'s

"\\"

it's because it's an escape character

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

How can I get a list of all functions stored in the database of a particular schema in PostgreSQL?

If any one is interested here is what query is executed by psql on postgres 9.1:

SELECT n.nspname as "Schema",
  p.proname as "Name",
  pg_catalog.pg_get_function_result(p.oid) as "Result data type",
  pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
 CASE
  WHEN p.proisagg THEN 'agg'
  WHEN p.proiswindow THEN 'window'
  WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
  ELSE 'normal'
 END as "Type"
FROM pg_catalog.pg_proc p
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;

You can get what psql runs for a backslash command by running psql with the -E flag.

How do I clear/delete the current line in terminal?

or if your using vi mode, hit Esc followed by cc

to get back what you just erased, Esc and then p :)

How to find if div with specific id exists in jQuery?

Try to check the length of the selector, if it returns you something then the element must exists else not.

if( $('#selector').length )         // use this if you are using id to check
{
     // it exists
}


if( $('.selector').length )         // use this if you are using class to check
{
     // it exists
}

Use the first if condition for id and the 2nd one for class.

Pass an array of integers to ASP.NET Web API?

In case someone would need - to achieve same or similar thing(like delete) via POST instead of FromUri, use FromBody and on client side(JS/jQuery) format param as $.param({ '': categoryids }, true)

c#:

public IHttpActionResult Remove([FromBody] int[] categoryIds)

jQuery:

$.ajax({
        type: 'POST',
        data: $.param({ '': categoryids }, true),
        url: url,
//...
});

The thing with $.param({ '': categoryids }, true) is that it .net will expect post body to contain urlencoded value like =1&=2&=3 without parameter name, and without brackets.

Passing arguments to C# generic new() of templated type

Since nobody bothered to post the 'Reflection' answer (which I personally think is the best answer), here goes:

public static string GetAllItems<T>(...) where T : new()
{
   ...
   List<T> tabListItems = new List<T>();
   foreach (ListItem listItem in listCollection) 
   {
       Type classType = typeof(T);
       ConstructorInfo classConstructor = classType.GetConstructor(new Type[] { listItem.GetType() });
       T classInstance = (T)classConstructor.Invoke(new object[] { listItem });

       tabListItems.Add(classInstance);
   } 
   ...
}

Edit: This answer is deprecated due to .NET 3.5's Activator.CreateInstance, however it is still useful in older .NET versions.

Python - Extracting and Saving Video Frames

This code extract frames from the video and save the frames in .jpg formate

import cv2
import numpy as np
import os

# set video file path of input video with name and extension
vid = cv2.VideoCapture('VideoPath')


if not os.path.exists('images'):
    os.makedirs('images')

#for frame identity
index = 0
while(True):
    # Extract images
    ret, frame = vid.read()
    # end of frames
    if not ret: 
        break
    # Saves images
    name = './images/frame' + str(index) + '.jpg'
    print ('Creating...' + name)
    cv2.imwrite(name, frame)

    # next frame
    index += 1

Open Windows Explorer and select a file

Check out this snippet:

Private Sub openDialog()
    Dim fd As Office.FileDialog

    Set fd = Application.FileDialog(msoFileDialogFilePicker)

   With fd

      .AllowMultiSelect = False

      ' Set the title of the dialog box.
      .Title = "Please select the file."

      ' Clear out the current filters, and add our own.
      .Filters.Clear
      .Filters.Add "Excel 2003", "*.xls"
      .Filters.Add "All Files", "*.*"

      ' Show the dialog box. If the .Show method returns True, the
      ' user picked at least one file. If the .Show method returns
      ' False, the user clicked Cancel.
      If .Show = True Then
        txtFileName = .SelectedItems(1) 'replace txtFileName with your textbox

      End If
   End With
End Sub

I think this is what you are asking for.

Traverse all the Nodes of a JSON Object Tree with JavaScript

I wanted to use the perfect solution of @TheHippo in an anonymous function, without use of process and trigger functions. The following worked for me, sharing for novice programmers like myself.

(function traverse(o) {
    for (var i in o) {
        console.log('key : ' + i + ', value: ' + o[i]);

        if (o[i] !== null && typeof(o[i])=="object") {
            //going on step down in the object tree!!
            traverse(o[i]);
        }
    }
  })
  (json);

Null vs. False vs. 0 in PHP

In PHP it depends on if you are validating types:

( 
 ( false !== 0 ) && ( false !== -1 ) && ( false == 0 ) && ( false == -1 ) &&
 ( false !== null ) && ( false == null ) 
)

Technically null is 0x00 but in PHP ( null == 0x00 ) && ( null !== 0x00 ).

0 is an integer value.

Add SUM of values of two LISTS into new LIST

You can use this method but it will work only if both the list are of the same size:

first = [1, 2, 3, 4, 5]
second = [6, 7, 8, 9, 10]
third = []

a = len(first)
b = int(0)
while True:
    x = first[b]
    y = second[b]
    ans = x + y
    third.append(ans)
    b = b + 1
    if b == a:
        break

print third

How to open a WPF Popup when another control is clicked, using XAML markup only?

I did something simple, but it works.

I used a typical ToggleButton, which I restyled as a textblock by changing its control template. Then I just bound the IsChecked property on the ToggleButton to the IsOpen property on the popup. Popup has some properties like StaysOpen that let you modify the closing behavior.

The following works in XamlPad.

 <StackPanel>
  <ToggleButton Name="button"> 
    <ToggleButton.Template>
      <ControlTemplate TargetType="ToggleButton">
        <TextBlock>Click Me Here!!</TextBlock>
      </ControlTemplate>      
    </ToggleButton.Template>
  </ToggleButton>
  <Popup IsOpen="{Binding IsChecked, ElementName=button}" StaysOpen="False">
    <Border Background="LightYellow">
      <TextBlock>I'm the popup</TextBlock>
    </Border>
  </Popup> 
 </StackPanel>

selecting unique values from a column

Depends on what you need.

In this case I suggest:

SELECT DISTINCT(Date) AS Date FROM buy ORDER BY Date DESC;

because there are few fields and the execution time of DISTINCT is lower than the execution of GROUP BY.

In other cases, for example where there are many fields, I prefer:

SELECT * FROM buy GROUP BY date ORDER BY date DESC;

How to set up file permissions for Laravel?

I'd do it like this:

sudo chown -R $USER:www-data laravel-project/ 

find laravel-project/ -type f -exec chmod 664 {} \;

find laravel-project/ -type d -exec chmod 775 {} \;

then finally, you need to give webserver permission to modify the storage and bootstrap/cache directories:

sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache

How to call an async method from a getter or setter?

Since your "async property" is in a viewmodel, you could use AsyncMVVM:

class MyViewModel : AsyncBindableBase
{
    public string Title
    {
        get
        {
            return Property.Get(GetTitleAsync);
        }
    }

    private async Task<string> GetTitleAsync()
    {
        //...
    }
}

It will take care of the synchronization context and property change notification for you.

Convert integer to class Date

Another way to get the same result:

date <- strptime(v,format="%Y%m%d")

what is trailing whitespace and how can I handle this?

I have got similar pep8 warning W291 trailing whitespace

long_text = '''Lorem Ipsum is simply dummy text  <-remove whitespace
of the printing and typesetting industry.'''

Try to explore trailing whitespaces and remove them. ex: two whitespaces at the end of Lorem Ipsum is simply dummy text

How do I compare two Integers?

Use the equals method. Why are you so worried that it's expensive?

Get Mouse Position

If you're using Swing as your UI layer, you can use a Mouse-Motion Listener for this.

Is there a method to generate a UUID with go language

For Windows, I did recently this:

// +build windows

package main

import (
    "syscall"
    "unsafe"
)

var (
    modrpcrt4 = syscall.NewLazyDLL("rpcrt4.dll")
    procUuidCreate = modrpcrt4.NewProc("UuidCreate")
)

const (
    RPC_S_OK = 0
)

func NewUuid() ([]byte, error) {
    var uuid [16]byte
    rc, _, e := syscall.Syscall(procUuidCreate.Addr(), 1,
             uintptr(unsafe.Pointer(&uuid[0])), 0, 0)
    if int(rc) != RPC_S_OK {
        if e != 0 {
            return nil, error(e)
        } else {
            return nil, syscall.EINVAL
        }
    }
    return uuid[:], nil
}

Javascript to display the current date and time

(new Date()).toLocaleString()

Will output the date and time using your local format. For example: "5/1/2020, 10:35:41 AM"

Parsing Json rest api response in C#

1> Add this namspace. using Newtonsoft.Json.Linq;

2> use this source code.

JObject joResponse = JObject.Parse(response);                   
JObject ojObject = (JObject)joResponse["response"];
JArray array= (JArray)ojObject ["chats"];
int id = Convert.ToInt32(array[0].toString());

CSS Flex Box Layout: full-width row and columns

You've almost done it. However setting flex: 0 0 <basis> declaration to the columns would prevent them from growing/shrinking; And the <basis> parameter would define the width of columns.

In addition, you could use CSS3 calc() expression to specify the height of columns with the respect to the height of the header.

#productShowcaseTitle {
  flex: 0 0 100%; /* Let it fill the entire space horizontally */
  height: 100px;
}

#productShowcaseDetail,
#productShowcaseThumbnailContainer {
  height: calc(100% - 100px); /* excluding the height of the header */
}

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-flow: row wrap;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  flex: 0 0 100%; /* Let it fill the entire space horizontally */_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 0 0 66%; /* ~ 2 * 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 0 0 34%;  /* ~ 33.33% */_x000D_
  height: calc(100% - 100px); /* excluding the height of the header */_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
  <div id="productShowcaseDetail"></div>_x000D_
  <div id="productShowcaseThumbnailContainer"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)


Alternatively, if you could change your markup e.g. wrapping the columns by an additional <div> element, it would be achieved without using calc() as follows:

<div class="contentContainer"> <!-- Added wrapper -->
    <div id="productShowcaseDetail"></div>
    <div id="productShowcaseThumbnailContainer"></div>
</div>
#productShowcaseContainer {
  display: flex;
  flex-direction: column;
  height: 600px; width: 580px;
}

.contentContainer { display: flex; flex: 1; }
#productShowcaseDetail { flex: 3; }
#productShowcaseThumbnailContainer { flex: 2; }

_x000D_
_x000D_
#productShowcaseContainer {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
_x000D_
  height: 600px;_x000D_
  width: 580px;_x000D_
}_x000D_
_x000D_
.contentContainer {_x000D_
  display: flex;_x000D_
  flex: 1;_x000D_
}_x000D_
_x000D_
#productShowcaseTitle {_x000D_
  height: 100px;_x000D_
  background-color: silver;_x000D_
}_x000D_
_x000D_
#productShowcaseDetail {_x000D_
  flex: 3;_x000D_
  background-color: lightgray;_x000D_
}_x000D_
_x000D_
#productShowcaseThumbnailContainer {_x000D_
  flex: 2;_x000D_
  background-color: black;_x000D_
}
_x000D_
<div id="productShowcaseContainer">_x000D_
  <div id="productShowcaseTitle"></div>_x000D_
_x000D_
  <div class="contentContainer"> <!-- Added wrapper -->_x000D_
    <div id="productShowcaseDetail"></div>_x000D_
    <div id="productShowcaseThumbnailContainer"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vendor prefixes omitted due to brevity)

How do you stylize a font in Swift?

I am assuming this is a custom font. For any custom font this is what you do.

  1. First download and add your font files to your project in Xcode (The files should appear as well in “Target -> Build Phases -> Copy Bundle Resources”).

  2. In your Info.plist file add the key “Fonts provided by application” with type “Array”.

  3. For each font you want to add to your project, create an item for the array you have created with the full name of the file including its extension (e.g. HelveticaNeue-UltraLight.ttf). Save your “Info.plist” file.

label.font = UIFont (name: "HelveticaNeue-UltraLight", size: 30)

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

If you have another variable also referring to the same dictionary, there is a big difference:

>>> d = {"stuff": "things"}
>>> d2 = d
>>> d = {}
>>> d2
{'stuff': 'things'}
>>> d = {"stuff": "things"}
>>> d2 = d
>>> d.clear()
>>> d2
{}

This is because assigning d = {} creates a new, empty dictionary and assigns it to the d variable. This leaves d2 pointing at the old dictionary with items still in it. However, d.clear() clears the same dictionary that d and d2 both point at.

How can I replace non-printable Unicode characters in Java?

I propose it remove the non printable characters like below instead of replacing it

private String removeNonBMPCharacters(final String input) {
    StringBuilder strBuilder = new StringBuilder();
    input.codePoints().forEach((i) -> {
        if (Character.isSupplementaryCodePoint(i)) {
            strBuilder.append("?");
        } else {
            strBuilder.append(Character.toChars(i));
        }
    });
    return strBuilder.toString();
}

How do I compile jrxml to get jasper?

with maven it is automatic:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>jasperreports-maven-plugin</artifactId>
  <configuration>
    <outputDirectory>target/${project.artifactId}/WEB-INF/reports</outputDirectory>
  </configuration>
  <executions>
    <execution>
      <phase>prepare-package</phase>
      <inherited>false</inherited>
      <goals>
         <goal>compile-reports</goal>
      </goals>
    </execution>
  </executions>
  <dependencies>
    <dependency>
       <groupId>net.sf.jasperreports</groupId>
       <artifactId>jasperreports</artifactId>
       <version>3.7.6</version> 
    </dependency>
    <dependency>
       <groupId>log4j</groupId>
       <artifactId>log4j</artifactId>
       <version>1.2.16</version>
       <type>jar</type>
     </dependency>
  </dependencies>
</plugin>

Curl: Fix CURL (51) SSL error: no alternative certificate subject name matches

It usually happens when the certificate does not match with the host name.

The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k (or --insecure) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.

More can be found in here: http://curl.haxx.se/docs/sslcerts.html

How to scroll to top of the page in AngularJS?

Ideally we should do it from either controller or directive as per applicable. Use $anchorScroll, $location as dependency injection.

Then call this two method as

$location.hash('scrollToDivID');
$anchorScroll();

Here scrollToDivID is the id where you want to scroll.

Assumed you want to navigate to a error message div as

<div id='scrollToDivID'>Your Error Message</div>

For more information please see this documentation

How can I disable a button in a jQuery dialog from a function?

I found a workaround that may apply to people trying to do something similar. Instead of disabling the button I put a simple if statement in the function to check if the checkbox was checked.

If it wasn't, it displayed a simple message saying the box had to be checked before submission.

For example:

$("#confirmation-dialog").dialog({
    modal: true,
    autoOpen: false,
    width: 600,
    overlay: {
        backgroundColor: '#000',
        opacity: 0.5
    },
    close: function() {
        $('input[type="submit"]')
      .val('Record Reading')
      .attr('disabled', false);
    },
    buttons: {
        'Confirm Reading': function() {
            if($('#check-box').attr("checked")){
                $(this).dialog('close')
                $('form')
                .addClass('confirmed')
                .submit();
            }
            else {
                $('#please-check').show("slide");
            }
        }
    }
});

Anyway, I hope that helps someone.

Select rows with same id but different value in another column

This ought to do it:

SELECT *
FROM YourTable
WHERE ARIDNR IN (
    SELECT ARIDNR
    FROM YourTable
    GROUP BY ARIDNR
    HAVING COUNT(*) > 1
)

The idea is to use the inner query to identify the records which have a ARIDNR value that occurs 1+ times in the data, then get all columns from the same table based on that set of values.

How to get the IP address of the docker host from inside a docker container

Try this:

docker run --rm -i --net=host alpine ifconfig

SMTPAuthenticationError when sending mail using gmail and python

I have just sent an email with gmail through Python. Try to use smtplib.SMTP_SSL to make the connection. Also, you may try to change the gmail domain and port.

So, you may get a chance with:

server = smtplib.SMTP_SSL('smtp.googlemail.com', 465)
server.login(gmail_user, password)
server.sendmail(gmail_user, TO, BODY)

As a plus, you could check the email builtin module. In this way, you can improve the readability of you your code and handle emails headers easily.

How to rename files and folder in Amazon S3?

As answered by Naaz direct renaming of s3 is not possible.

i have attached a code snippet which will copy all the contents

code is working just add your aws access key and secret key

here's what i did in code

-> copy the source folder contents(nested child and folders) and pasted in the destination folder

-> when the copying is complete, delete the source folder

package com.bighalf.doc.amazon;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CopyObjectRequest;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.S3ObjectSummary;

public class Test {

public static boolean renameAwsFolder(String bucketName,String keyName,String newName) {
    boolean result = false;
    try {
        AmazonS3 s3client = getAmazonS3ClientObject();
        List<S3ObjectSummary> fileList = s3client.listObjects(bucketName, keyName).getObjectSummaries();
        //some meta data to create empty folders start
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(0);
        InputStream emptyContent = new ByteArrayInputStream(new byte[0]);
        //some meta data to create empty folders end

        //final location is the locaiton where the child folder contents of the existing folder should go
        String finalLocation = keyName.substring(0,keyName.lastIndexOf('/')+1)+newName;
        for (S3ObjectSummary file : fileList) {
            String key = file.getKey();
            //updating child folder location with the newlocation
            String destinationKeyName = key.replace(keyName,finalLocation);
            if(key.charAt(key.length()-1)=='/'){
                //if name ends with suffix (/) means its a folders
                PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, destinationKeyName, emptyContent, metadata);
                s3client.putObject(putObjectRequest);
            }else{
                //if name doesnot ends with suffix (/) means its a file
                CopyObjectRequest copyObjRequest = new CopyObjectRequest(bucketName, 
                        file.getKey(), bucketName, destinationKeyName);
                s3client.copyObject(copyObjRequest);
            }
        }
        boolean isFodlerDeleted = deleteFolderFromAws(bucketName, keyName);
        return isFodlerDeleted;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

public static boolean deleteFolderFromAws(String bucketName, String keyName) {
    boolean result = false;
    try {
        AmazonS3 s3client = getAmazonS3ClientObject();
        //deleting folder children
        List<S3ObjectSummary> fileList = s3client.listObjects(bucketName, keyName).getObjectSummaries();
        for (S3ObjectSummary file : fileList) {
            s3client.deleteObject(bucketName, file.getKey());
        }
        //deleting actual passed folder
        s3client.deleteObject(bucketName, keyName);
        result = true;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return result;
}

public static void main(String[] args) {
    intializeAmazonObjects();
    boolean result = renameAwsFolder(bucketName, keyName, newName);
    System.out.println(result);
}

private static AWSCredentials credentials = null;
private static AmazonS3 amazonS3Client = null;
private static final String ACCESS_KEY = "";
private static final String SECRET_ACCESS_KEY = "";
private static final String bucketName = "";
private static final String keyName = "";
//renaming folder c to x from key name
private static final String newName = "";

public static void intializeAmazonObjects() {
    credentials = new BasicAWSCredentials(ACCESS_KEY, SECRET_ACCESS_KEY);
    amazonS3Client = new AmazonS3Client(credentials);
}

public static AmazonS3 getAmazonS3ClientObject() {
    return amazonS3Client;
}

}

How to search in array of object in mongodb

The right way is:

db.users.find({awards: {$elemMatch: {award:'National Medal', year:1975}}})

$elemMatch allows you to match more than one component within the same array element.

Without $elemMatch mongo will look for users with National Medal in some year and some award in 1975s, but not for users with National Medal in 1975.

See MongoDB $elemMatch Documentation for more info. See Read Operations Documentation for more information about querying documents with arrays.

Foreach in a Foreach in MVC View

You have:

foreach (var category in Model.Categories)

and then

@foreach (var product in Model)

Based on that view and model it seems that Model is of type Product if yes then the second foreach is not valid. Actually the first one could be the one that is invalid if you return a collection of Product.

UPDATE:

You are right, I am returning the model of type Product. Also, I do understand what is wrong now that you've pointed it out. How am I supposed to do what I'm trying to do then if I can't do it this way?

I'm surprised your code compiles when you said you are returning a model of Product type. Here's how you can do it:

@foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>

    <div>
        <ul>    
            @foreach (var product in category.Products)
            {
                <li>
                    put the rest of your code
                </li>
            }
        </ul>
    </div>
}

That suggest that instead of returning a Product, you return a collection of Category with Products. Something like this in EF:

// I am typing it here directly 
// so I'm not sure if this is the correct syntax.
// I assume you know how to do this,
// anyway this should give you an idea.
context.Categories.Include(o=>o.Product)

How to scroll table's "tbody" independent of "thead"?

thead {
  position: fixed;
  height: 10px; /* This is whatever height you want */
}
  tbody {
  position: fixed;
  margin-top: 10px; /* This has to match the height of thead */
  height: 300px; /* This is whatever height you want */
}

Access maven properties defined in the pom

Maven already has a solution to do what you want:

Get MavenProject from just the POM.xml - pom parser?

btw: first hit at google search ;)

Model model = null;
FileReader reader = null;
MavenXpp3Reader mavenreader = new MavenXpp3Reader();

try {
     reader = new FileReader(pomfile); // <-- pomfile is your pom.xml
     model = mavenreader.read(reader);
     model.setPomFile(pomfile);
}catch(Exception ex){
     // do something better here
     ex.printStackTrace()
}

MavenProject project = new MavenProject(model);
project.getProperties() // <-- thats what you need

JSONResult to String

json = " { \"success\" : false, \"errors\": { \"text\" : \"??????!\" } }";            
return new MemoryStream(Encoding.UTF8.GetBytes(json));

Image is not showing in browser?

I don't know where you're running the site from on your computer, but you have an absolute file path to your C drive: C:\Users\VIRK\Desktop\66.jpg

Try this instead:

<img  src="[PATH_RELATIVE_TO_ROOT]/66.jpg" width="400" height="400" />

UPDATE:

I don't know what your $PROJECTHOME is set to. But say for example your site files are located at C:\Users\VIRK\MyWebsite. And let's say your images are in an 'images' folder within your main site, like so: C:\Users\VIRK\MyWebsite\images.

Then in your HTML you can simply reference the image within the images folder relative to the site, like so:

<img  src="images/66.jpg" width="400" height="400" />

Or, assuming you're hosting at the root of localhost and not within another virtual directory, you can do this (note the slash in the beginning):

<img  src="/images/66.jpg" width="400" height="400" />

What is the difference between a stored procedure and a view?

Mahesh is not quite correct when he suggests that you can't alter the data in a view. So with patrick's view

CREATE View vw_user_profile AS 
Select A.user_id, B.profile_description
FROM tbl_user A left join tbl_profile B on A.user_id = b.user_id

I CAN update the data ... as an example I can do either of these ...

Update vw_user_profile Set profile_description='Manager' where user_id=4

or

Update tbl_profile Set profile_description='Manager' where user_id=4

You can't INSERT to this view as not all of the fields in all of the table are present and I'm assuming that PROFILE_ID is the primary key and can't be NULL. However you can sometimes INSERT into a view ...

I created a view on an existing table using ...

Create View Junk as SELECT * from [TableName]

THEN

Insert into junk (Code,name) values 
('glyn','Glyn Roberts'),
('Mary','Maryann Roberts')

and

DELETE from Junk Where ID>4

Both the INSERT and the DELETE worked in this case

Obviously you can't update any fields which are aggregated or calculated but any view which is just a straight view should be updateable.

If the view contains more than one table then you can't insert or delete but if the view is a subset of one table only then you usually can.

More Pythonic Way to Run a Process X Times

The for loop is definitely more pythonic, as it uses Python's higher level built in functionality to convey what you're doing both more clearly and concisely. The overhead of range vs xrange, and assigning an unused i variable, stem from the absence of a statement like Verilog's repeat statement. The main reason to stick to the for range solution is that other ways are more complex. For instance:

from itertools import repeat

for unused in repeat(None, 10):
    del unused   # redundant and inefficient, the name is clear enough
    print "This is run 10 times"

Using repeat instead of range here is less clear because it's not as well known a function, and more complex because you need to import it. The main style guides if you need a reference are PEP 20 - The Zen of Python and PEP 8 - Style Guide for Python Code.

We also note that the for range version is an explicit example used in both the language reference and tutorial, although in that case the value is used. It does mean the form is bound to be more familiar than the while expansion of a C-style for loop.

Maven : error in opening zip file when running maven

This issue is a pain in my a$$, I have this issue in my Mac, if I run

mvn clean install | grep "error reading"
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/velocity/velocity/1.7/velocity-1.7.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/commons-net/commons-net/3.3/commons-net-3.3.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/commons/commons-lang3/3.0/commons-lang3-3.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/bouncycastle/bcprov-jdk15on/1.54/bcprov-jdk15on-1.54.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/javax/mail/mail/1.4/mail-1.4.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/pdfbox/pdfbox/2.0.0/pdfbox-2.0.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/slf4j/slf4j-api/1.7.24/slf4j-api-1.7.24.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/aspose/aspose-pdf/11.5.0/aspose-pdf-11.5.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/velocity/velocity/1.7/velocity-1.7.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/commons-net/commons-net/3.3/commons-net-3.3.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/commons/commons-lang3/3.0/commons-lang3-3.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/bouncycastle/bcprov-jdk15on/1.54/bcprov-jdk15on-1.54.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/javax/mail/mail/1.4/mail-1.4.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/pdfbox/pdfbox/2.0.0/pdfbox-2.0.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/slf4j/slf4j-api/1.7.24/slf4j-api-1.7.24.jar; error in opening zip file

Removing all corrupted libs is the only solution

So I want to remove all of them at once.

mvn clean install | grep "error reading" | awk '{print "rm " $4 | "/bin/sh"  }'

The command needs AWK to take libPath string from column $4

Then rerun

mvn clean install

How can I solve the error LNK2019: unresolved external symbol - function?

Another way you can get this linker error (as I was) is if you are exporting an instance of a class from a DLL file, but have not declared that class itself as import/export.

#ifdef  MYDLL_EXPORTS
   #define DLLEXPORT __declspec(dllexport)
#else
   #define DLLEXPORT __declspec(dllimport)
#endif

class DLLEXPORT Book // <--- This class must also be declared as export/import
{
    public:
        Book();
        ~Book();
        int WordCount();
};

DLLEXPORT extern Book book; // <-- This is what I really wanted, to export book object

So even though primarily I was exporting just an instance of the Book class called book above, I had to declare the Book class as export/import class as well otherwise calling book.WordCount() in the other DLL file was causing a link error.

Android Use Done button on Keyboard to click button

Kotlin and Numeric keyboard

If you are using the numeric keyboard you have to dismiss the keyboard, it will be like:

editText.setOnEditorActionListener { v, actionId, event ->
  if (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_NEXT || action == EditorInfo.IME_ACTION_UNSPECIFIED) {
      //hide the keyboard
      val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
      imm.hideSoftInputFromWindow(windowToken, 0)
      //Take action
      editValue.clearFocus()
      return true
  } else {
      return false
  }
}

Getting IP address of client

I believe it is more to do with how your network is configured. Servlet is simply giving you the address it is finding.

I can suggest two workarounds. First try using IPV4. See this SO Answer

Also, try using the request.getRemoteHost() method to get the names of the machines. Surely the names are independent of whatever IP they are mapped to.

I still think you should discuss this with your infrastructure guys.

How to wrap text in LaTeX tables?

I like the simplicity of tabulary package:

\usepackage{tabulary}
...
\begin{tabulary}{\linewidth}{LCL}
    \hline
    Short sentences      & \#  & Long sentences                                                 \\
    \hline
    This is short.       & 173 & This is much loooooooonger, because there are many more words.  \\
    This is not shorter. & 317 & This is still loooooooonger, because there are many more words. \\
    \hline
\end{tabulary} 

In the example, you arrange the whole width of the table with respect to \textwidth. E.g 0.4 of it. Then the rest is automatically done by the package.

Most of the example is taken from http://en.wikibooks.org/wiki/LaTeX/Tables .

Passing a URL with brackets to curl

Never mind, I found it in the docs:

-g/--globoff
              This  option  switches  off  the "URL globbing parser". When you set this option, you can
              specify URLs that contain the letters {}[] without having them being interpreted by  curl
              itself.  Note  that  these  letters  are not normal legal URL contents but they should be
              encoded according to the URI standard.

Apache 2.4.6 on Ubuntu Server: Client denied by server configuration (PHP FPM) [While loading PHP file]

In apache2.conf, replace or delete <Directory /> AllowOverride None Require all denied </Directory>, like suggested Jan Czarny.

For example:

<Directory />
    Options FollowSymLinks
    AllowOverride None
    #Require all denied
    Require all granted
</Directory>

This worked in Ubuntu 14.04 (Trusty Tahr).

Writing MemoryStream to Response Object

Try with this

Response.Clear();
Response.AppendHeader("Content-Type", "application/vnd.openxmlformats-officedocument.presentationml.presentation");
Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}.pptx;", getLegalFileName(CurrentPresentation.Presentation_NM)));
Response.Flush();                
Response.BinaryWrite(masterPresentation.ToArray());
Response.End();

Generating random numbers in C

int *generate_randomnumbers(int start, int end){
    int *res = malloc(sizeof(int)*(end-start));
    srand(time(NULL));
    for (int i= 0; i < (end -start)+1; i++){
        int r = rand()%end + start;
        int dup = 0;
        for (int j = 0; j < (end -start)+1; j++){
            if (res[j] == r){
                i--;
                dup = 1;
                break;
            }
        }
        if (!dup)
            res[i] = r;
    }
    return res;
}

Shell script not running, command not found

Try chmod u+x MigrateNshell.sh

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

SQL Server doesn't support the SQL standard interval data type. Your best bet is to calculate the difference in seconds, and use a function to format the result. The native function CONVERT() might appear to work fine as long as your interval is less than 24 hours. But CONVERT() isn't a good solution for this.

create table test (
  id integer not null,
  ts datetime not null
  );

insert into test values (1, '2012-01-01 08:00');
insert into test values (1, '2012-01-01 09:00');
insert into test values (1, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 08:30');
insert into test values (2, '2012-01-01 10:30');
insert into test values (2, '2012-01-01 09:00');
insert into test values (3, '2012-01-01 09:00');
insert into test values (3, '2012-01-02 12:00');

Values were chosen in such a way that for

  • id = 1, elapsed time is 1 hour
  • id = 2, elapsed time is 2 hours, and
  • id = 3, elapsed time is 3 hours.

This SELECT statement includes one column that calculates seconds, and one that uses CONVERT() with subtraction.

select t.id,
       min(ts) start_time,
       max(ts) end_time,
       datediff(second, min(ts),max(ts)) elapsed_sec,
       convert(varchar, max(ts) - min(ts), 108) do_not_use
from test t
group by t.id;

ID  START_TIME                 END_TIME                   ELAPSED_SEC  DO_NOT_USE
1   January, 01 2012 08:00:00  January, 01 2012 09:00:00  3600         01:00:00
2   January, 01 2012 08:30:00  January, 01 2012 10:30:00  7200         02:00:00
3   January, 01 2012 09:00:00  January, 02 2012 12:00:00  97200        03:00:00

Note the misleading "03:00:00" for the 27-hour difference on id number 3.

Function to format elapsed time in SQL Server

Include headers when using SELECT INTO OUTFILE?

Actually you can make it work even with an ORDER BY.

Just needs some trickery in the order by statement - we use a case statement and replace the header value with some other value that is guaranteed to sort first in the list (obviously this is dependant on the type of field and whether you are sorting ASC or DESC)

Let's say you have three fields, name (varchar), is_active (bool), date_something_happens (date), and you want to sort the second two descending:

select 
        'name'
      , 'is_active' as is_active
      , date_something_happens as 'date_something_happens'

 union all

 select name, is_active, date_something_happens

 from
    my_table

 order by
     (case is_active when 'is_active' then 0 else is_active end) desc
   , (case date when 'date' then '9999-12-30' else date end) desc

How to delete a record in Django models?

you can delete the objects directly from the admin panel or else there is also an option to delete specific or selected id from an interactive shell by typing in python3 manage.py shell (python3 in Linux). If you want the user to delete the objects through the browser (with provided visual interface) e.g. of an employee whose ID is 6 from the database, we can achieve this with the following code, emp = employee.objects.get(id=6).delete()

THIS WILL DELETE THE EMPLOYEE WITH THE ID is 6.

If you wish to delete the all of the employees exist in the DB instead of get(), specify all() as follows: employee.objects.all().delete()

Best way to check for nullable bool in a condition expression (if ...)

If you're in a situation where you don't have control over whether part of the condition is checking a nullable value, you can always try the following:

if( someInt == 6 && someNullableBool == null ? false : (bool)someNullableBool){
    //perform your actions if true
}

I know it's not exactly a purist approach putting a ternary in an if statement but it does resolve the issue cleanly.

This is, of course, a manual way of saying GetValueOrDefault(false)

Best way to call a JSON WebService from a .NET Console

WebClient to fetch the contents from the remote url and JavaScriptSerializer or Json.NET to deserialize the JSON into a .NET object. For example you define a model class which will reflect the JSON structure and then:

using (var client = new WebClient())
{
    var json = client.DownloadString("http://example.com/json");
    var serializer = new JavaScriptSerializer();
    SomeModel model = serializer.Deserialize<SomeModel>(json);
    // TODO: do something with the model
}

There are also some REST client frameworks you may checkout such as RestSharp.

How should the ViewModel close the form?

FYI, I ran into this same problem and I think I figured out a work around that doesn't require globals or statics, although it may not be the best answer. I let the you guys decide that for yourself.

In my case, the ViewModel that instantiates the Window to be displayed (lets call it ViewModelMain) also knows about the LoginFormViewModel (using the situation above as an example).

So what I did was to create a property on the LoginFormViewModel that was of type ICommand (Lets call it CloseWindowCommand). Then, before I call .ShowDialog() on the Window, I set the CloseWindowCommand property on the LoginFormViewModel to the window.Close() method of the Window I instantiated. Then inside the LoginFormViewModel all I have to do is call CloseWindowCommand.Execute() to close the window.

It is a bit of a workaround/hack I suppose, but it works well without really breaking the MVVM pattern.

Feel free to critique this process as much as you like, I can take it! :)

How can I join on a stored procedure?

I resolved this problem writing function instead of procedure and using CROSS APPLY in SQL statement. This solution works on SQL 2005 and later versions.

removing new line character from incoming stream using sed

This might work for you:

printf "{new\nto\nlinux}" | paste -sd' '            
{new to linux}

or:

printf "{new\nto\nlinux}" | tr '\n' ' '            
{new to linux}

or:

printf "{new\nto\nlinux}" |sed -e ':a' -e '$!{' -e 'N' -e 'ba' -e '}' -e 's/\n/ /g'
{new to linux}

What's the difference between emulation and simulation?

Here's an example - we recently developed a simulation model to measure the remote transmission response time of a yet-to-be-developed system. An emulation analysis would not have given us the answer in time to upgrade the bandwidth capacity so simulation was our approach. Because we were mostly interested in determining bandwidth needs, we cared primarily about transaction size and volume, not the processing of the system. The simulation model was on a stand-alone piece of software that was designed to model discrete-event processes. To summarize in response to your question, emulation is a type of simulation. But, in this case, simulation was NOT an emulation because it didn't fully represent the new system, only the size and volume of transactions.

How to make an app's background image repeat

Expanding on plowman's answer, here is the non-deprecated version of changing the background image with java.

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bitmap bmp = BitmapFactory.decodeResource(getResources(),
            R.drawable.texture);
    BitmapDrawable bitmapDrawable = new BitmapDrawable(getResources(),bmp);
    bitmapDrawable.setTileModeXY(Shader.TileMode.REPEAT,
            Shader.TileMode.REPEAT);
    setBackground(bitmapDrawable);
}

C/C++ Struct vs Class

In C++, structs and classes are pretty much the same; the only difference is that where access modifiers (for member variables, methods, and base classes) in classes default to private, access modifiers in structs default to public.

However, in C, a struct is just an aggregate collection of (public) data, and has no other class-like features: no methods, no constructor, no base classes, etc. Although C++ inherited the keyword, it extended the semantics. (This, however, is why things default to public in structs—a struct written like a C struct behaves like one.)

While it's possible to fake some OOP in C—for instance, defining functions which all take a pointer to a struct as their first parameter, or occasionally coercing structs with the same first few fields to be "sub/superclasses"—it's always sort of bolted on, and isn't really part of the language.

What characters are valid for JavaScript variable names?

Javascript Variables

You can start a variable with any letter, $, or _ character. As long as it doesn't start with a number, you can include numbers as well.

Start: [a-z], $, _

Contain: [a-z], [0-9], $, _

jQuery

You can use _ for your library so that it will stand side-by-side with jQuery. However, there is a configuration you can set so that jQuery will not use $. It will instead use jQuery. To do this, simply set:

jQuery.noConflict();

This page explains how to do this.

IOS - How to segue programmatically using swift

Another option is to use modal segue

STEP 1: Go to the storyboard, and give the View Controller a Storyboard ID. You can find where to change the storyboard ID in the Identity Inspector on the right. Lets call the storyboard ID ModalViewController

STEP 2: Open up the 'sender' view controller (let's call it ViewController) and add this code to it

public class ViewController {
  override func viewDidLoad() {
    showModalView()
  }

  func showModalView() {
    if let mvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController {
      self.present(mvc, animated: true, completion: nil)
    }
  }
}

Note that the View Controller we want to open is also called ModalViewController

STEP 3: To close ModalViewController, add this to it

public class ModalViewController {
   @IBAction func closeThisViewController(_ sender: Any?) {
      self.presentingViewController?.dismiss(animated: true, completion: nil)
   }
}

Batchfile to create backup and rename with timestamp

I've modified Foxidrive's answer to copy entire folders and all their contents. this script will create a folder and backup another folder's contents into it, including any subfolders underneath.

If you put this in say an hourly scheduled task you need to be careful as you could fill up your drive quickly with copies of your original folder. Before bitbucket etc i was using as similar script to save my code offline.

@echo off
for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
set YYYY=%dt:~0,4%
set MM=%dt:~4,2%
set DD=%dt:~6,2%
set HH=%dt:~8,2%
set Min=%dt:~10,2%
set Sec=%dt:~12,2%

set stamp=YourPrefixHere_%YYYY%%MM%%DD%@%HH%%Min%
rem you could for example want to create a folder in Gdrive and save backup there
cd C:\YourGoogleDriveFolder
mkdir %stamp%
cd %stamp%

 xcopy C:\FolderWithDataToBackup\*.* /s 

Find a value in an array of objects in Javascript

Either use a simple for-loop:

var result = null;
for (var i = 0; i < array.length; i++) { 
  if (array[i].name === "string 1") { 
    result = array[i];
    break;
  } 
}

Or if you can, that is, if your browser supports it, use Array.filter, which is much more terse:

var result = array.filter(function (obj) {
  return obj.name === "string 1";
})[0];

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

Migration: Cannot add foreign key constraint

Some times this error may come because of sequence of migrations.

Like Users and Order are two tables

Order table have foriegn key of users (During migration if Order table migrate first then it will cause the problem because there is no users to match foreign key)

Solution: Just Put your Order Update table under the users for update

Example: In my case Education and University tables Education Table

public function up()
{
    Schema::create('doc_education', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('uni_id')->unsigned()->nullable();
        $table->timestamps();
    });
}

In the University

    Schema::create('doc_universties', function (Blueprint $table) {
        $table->increments('id');
        $table->string('uni_name');
        $table->string('location')->nullable();
        $table->timestamps();

        //
    });



Schema::table('doc_education', function(Blueprint $table) {
        $table->foreign('uni_id')->references('id')
        ->on('doc_universties')->onDelete('cascade');
    });

How to my "exe" from PyCharm project

You cannot directly save a Python file as an exe and expect it to work -- the computer cannot automatically understand whatever code you happened to type in a text file. Instead, you need to use another program to transform your Python code into an exe.

I recommend using a program like Pyinstaller. It essentially takes the Python interpreter and bundles it with your script to turn it into a standalone exe that can be run on arbitrary computers that don't have Python installed (typically Windows computers, since Linux tends to come pre-installed with Python).

To install it, you can either download it from the linked website or use the command:

pip install pyinstaller

...from the command line. Then, for the most part, you simply navigate to the folder containing your source code via the command line and run:

pyinstaller myscript.py

You can find more information about how to use Pyinstaller and customize the build process via the documentation.


You don't necessarily have to use Pyinstaller, though. Here's a comparison of different programs that can be used to turn your Python code into an executable.

How to loop over files in directory and change path and add suffix to filename

Looks like you're trying to execute a windows file (.exe) Surely you ought to be using powershell. Anyway on a Linux bash shell a simple one-liner will suffice.

[/home/$] for filename in /Data/*.txt; do for i in {0..3}; do ./MyProgam.exe  Data/filenameLogs/$filename_log$i.txt; done done

Or in a bash

#!/bin/bash

for filename in /Data/*.txt; 
   do
     for i in {0..3}; 
       do ./MyProgam.exe Data/filename.txt Logs/$filename_log$i.txt; 
     done 
 done

Authenticating against Active Directory with Java on Linux

I just finished a project that uses AD and Java. We used Spring ldapTemplate.

AD is LDAP compliant (almost), I don't think you will have any issues with the task you have. I mean the fact that it is AD or any other LDAP server it doesn't matter if you want just to connect.

I would take a look at: Spring LDAP

They have examples too.

As for encryption, we used SSL connection (so it was LDAPS). AD had to be configured on a SSL port/protocol.

But first of all, make sure you can properly connect to your AD via an LDAP IDE. I use Apache Directory Studio, it is really cool, and it is written in Java. That is all I needed. For testing purposes you could also install Apache Directory Server

How to get HttpContext.Current in ASP.NET Core?

There is a solution to this if you really need a static access to the current context. In Startup.Configure(….)

app.Use(async (httpContext, next) =>
{
    CallContext.LogicalSetData("CurrentContextKey", httpContext);
    try
    {
        await next();
    }
    finally
    {
        CallContext.FreeNamedDataSlot("CurrentContextKey");
    }
});

And when you need it you can get it with :

HttpContext context = CallContext.LogicalGetData("CurrentContextKey") as HttpContext;

I hope that helps. Keep in mind this workaround is when you don’t have a choice. The best practice is to use de dependency injection.

How can I have linebreaks in my long LaTeX equations?

If it is inline equation, then use \allowbreak. Use it like:

$x_1,x_2,x_3,\allowbreak x_4,x_5$.

Latex will break equation in this place only if necessary.

How can I find a specific file from a Linux terminal?

In general, the best way to find any file in any arbitrary location is to start a terminal window and type in the classic Unix command "find":

find / -name index.html -print

Since the file you're looking for is the root file in the root directory of your web server, it's probably easier to find your web server's document root. For example, look under:

/var/www/*

Or type:

find /var/www -name index.html -print

Genymotion, "Unable to load VirtualBox engine." on Mavericks. VBox is setup correctly

It happens when upgrading to el capitan from yosemite. Virtual box needs to be installed again. Reinstalling geny motion does nothing. You will keep all your virtual devices unchanged.

Spring MVC 4: "application/json" Content Type is not being set correctly

Use jackson library and @ResponseBody annotation on return type for the Controller.

This works if you wish to return POJOs represented as JSon. If you woud like to return String and not POJOs as JSon please refer to Sotirious answer.

Export MySQL database using PHP only

In *nix systems, use the WHICH command to show the location of the mysqldump, try this :

<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = 'password';
$dbname = 'test';
$mysqldump=exec('which mysqldump');


$command = "$mysqldump --opt -h $dbhost -u $dbuser -p $dbpass $dbname > $dbname.sql";

exec($command);
?>

How to take column-slices of dataframe in pandas

Note: .ix has been deprecated since Pandas v0.20. You should instead use .loc or .iloc, as appropriate.

The DataFrame.ix index is what you want to be accessing. It's a little confusing (I agree that Pandas indexing is perplexing at times!), but the following seems to do what you want:

>>> df = DataFrame(np.random.rand(4,5), columns = list('abcde'))
>>> df.ix[:,'b':]
      b         c         d         e
0  0.418762  0.042369  0.869203  0.972314
1  0.991058  0.510228  0.594784  0.534366
2  0.407472  0.259811  0.396664  0.894202
3  0.726168  0.139531  0.324932  0.906575

where .ix[row slice, column slice] is what is being interpreted. More on Pandas indexing here: http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-advanced

jQuery check if it is clicked or not

    <script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
var val;
        $(document).ready(function () {
            $("#click").click(function () {
                val = 1;
                get();
                });
                });
          function get(){
            if (val == 1){
                alert(val);
                }

          }
</script>
    <table>
    <tr><td id='click'>ravi</td></tr>
    </table>

How do JavaScript closures work?

The more I think about closure the more I see it as a 2-step process: init - action

init: pass first what's needed...
action: in order to achieve something for later execution.

To a 6-year old, I'd emphasize on the practical aspect of closure:

Daddy: Listen. Could you bring mum some milk (2).
Tom: No problem.
Daddy: Take a look at the map that Daddy has just made: mum is there and daddy is here.
Daddy: But get ready first. And bring the map with you (1), it may come in handy
Daddy: Then off you go (3). Ok?
Tom: A piece of cake!

Example: Bring some milk to mum (=action). First get ready and bring the map (=init).

function getReady(map) {
    var cleverBoy = 'I examine the ' + map;
    return function(what, who) {
        return 'I bring ' + what + ' to ' + who + 'because + ' cleverBoy; //I can access the map
    }
}
var offYouGo = getReady('daddy-map');
offYouGo('milk', 'mum');

Because if you bring with you a very important piece of information (the map), you're knowledgeable enough to execute other similar actions:

offYouGo('potatoes', 'great mum');

To a developer I'd make a parallel between closures and OOP. The init phase is similar to passing arguments to a constructor in a traditional OO language; the action phase is ultimately the method you call to achieve what you want. And the method has access these init arguments using a mechanism called closure.

See my another answer illustrating the parallelism between OO and closures:

How to "properly" create a custom object in JavaScript?

Image scaling causes poor quality in firefox/internet explorer but not chrome

This is possible! At least now that css transforms have good support:

You need to use a CSS transform to scale the image - the trick is not just to use a scale(), but also to apply a very small rotation. This triggers IE to use a smoother interpolation of the image:

img {
    /* double desired size */
    width: 56px; 
    height: 56px;

    /* margins to reduce layout size to match the transformed size */ 
    margin: -14px -14px -14px -14px; 

    /* transform to scale with smooth interpolation: */
    transform: scale(0.5) rotate(0.1deg);
}

File Not Found when running PHP with Nginx

I just spent like 40 minutes trying to debug a non-working /status with:

$ SCRIPT_NAME=/status SCRIPT_FILENAME=/status QUERY_STRING= REQUEST_METHOD=GET cgi-fcgi -bind -connect /var/run/php5-fpm.sock

It just produced "File not found" error, while the actual scripts (that are found on the filesystem) worked just fine.

Turned out, I had a couple of orphaned processes of php5-fpm. After I killed everything and restarted php5-fpm cleanly, it just went back to normal.

Hope this helps.

Deserialize json object into dynamic object using Json.net

I know this is old post but JsonConvert actually has a different method so it would be

var product = new { Name = "", Price = 0 };
var jsonResponse = JsonConvert.DeserializeAnonymousType(json, product);

How to change the remote a branch is tracking?

This is the easiest command:

git push --set-upstream <new-origin> <branch-to-track>

For example, given the command git remote -v produces something like:

origin  ssh://[email protected]/~myself/projectr.git (fetch)
origin  ssh://[email protected]/~myself/projectr.git (push)
team    ssh://[email protected]/vbs/projectr.git (fetch)
team    ssh://[email protected]/vbs/projectr.git (push)

To change to tracking the team instead:

git push --set-upstream team master

Numpy array dimensions

rows = a.shape[0] # 2 
cols = a.shape[1] # 2
a.shape #(2,2)
a.size # rows * cols = 4

How to use format() on a moment.js duration?

This can be used to get the first two characters as hours and last two as minutes. Same logic may be applied to seconds.

_x000D_
_x000D_
/**_x000D_
     * PT1H30M -> 0130_x000D_
     * @param {ISO String} isoString_x000D_
     * @return {string} absolute 4 digit number HH:mm_x000D_
     */_x000D_
_x000D_
    const parseIsoToAbsolute = (isoString) => {_x000D_
    _x000D_
      const durations = moment.duration(isoString).as('seconds');_x000D_
      const momentInSeconds = moment.duration(durations, 'seconds');_x000D_
    _x000D_
      let hours = momentInSeconds.asHours().toString().length < 2_x000D_
        ? momentInSeconds.asHours().toString().padStart(2, '0') : momentInSeconds.asHours().toString();_x000D_
        _x000D_
      if (!Number.isInteger(Number(hours))) hours = '0'+ Math.floor(hours);_x000D_
    _x000D_
      const minutes = momentInSeconds.minutes().toString().length < 2_x000D_
        ? momentInSeconds.minutes().toString().padEnd(2, '0') : momentInSeconds.minutes().toString();_x000D_
    _x000D_
      const absolute = hours + minutes;_x000D_
      return absolute;_x000D_
    };_x000D_
    _x000D_
    console.log(parseIsoToAbsolute('PT1H30M'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment-with-locales.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
_x000D_
_x000D_
_x000D_

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

There's this bug in the latest version of pandas (pandas 0.23) that gives you an error on importing pandas.

But this can be easily fixed by installing an earlier version of pandas (pandas 0.22) using the command pip install pandas==0.22 on Windows Command Prompt.

Trigger 404 in Spring-MVC controller?

Rewrite your method signature so that it accepts HttpServletResponse as a parameter, so that you can call setStatus(int) on it.

http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments

jQuery check if an input is type checkbox?

$("#myinput").attr('type') == 'checkbox'

Get value when selected ng-option changes

Please, use for it ngChange directive. For example:

<select ng-model="blisterPackTemplateSelected" 
        ng-options="blisterPackTemplate as blisterPackTemplate.name for blisterPackTemplate in blisterPackTemplates" 
        ng-change="changeValue(blisterPackTemplateSelected)"/>

And pass your new model value in controller as a parameter:

ng-change="changeValue(blisterPackTemplateSelected)"

Create mysql table directly from CSV file using the CSV Storage engine?

MySQL for excel plugin can help you.

http://dev.mysql.com/doc/refman/5.6/en/mysql-for-excel.html

Open your CSV file in excel. You can use this plugin to export excel data into a new table of remote or local mysql server. It will analyze your data (top 100 to 1000 rows) and create a corresponding table schema.

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

Detecting iOS / Android Operating system

For this and other kind of client detections I suggest this js library: http://hictech.github.io/navJs/tester/index.html

For your specific answer use:

navJS.isIOS() || navJS.isAndroid()

MySql Proccesslist filled with "Sleep" Entries leading to "Too many Connections"?

Increasing number of max-connections will not solve the problem.

We were experiencing the same situation on our servers. This is what happens

User open a page/view, that connect to the database, query the database, still query(queries) were not finished and user leave the page or move to some other page. So the connection that was open, will remains open, and keep increasing number of connections, if there are more users connecting with the db and doing something similar.

You can set interactive_timeout MySQL, bydefault it is 28800 (8hours) to 1 hour

SET interactive_timeout=3600

Add primary key to existing table

I think something like this should work

-- drop current primary key constraint
ALTER TABLE dbo.persion 
DROP CONSTRAINT PK_persionId;
GO

-- add new auto incremented field
ALTER TABLE dbo.persion 
ADD pmid BIGINT IDENTITY;
GO

-- create new primary key constraint
ALTER TABLE dbo.persion 
ADD CONSTRAINT PK_persionId PRIMARY KEY NONCLUSTERED (pmid, persionId);
GO

What does "atomic" mean in programming?

Just found a post Atomic vs. Non-Atomic Operations to be very helpful to me.

"An operation acting on shared memory is atomic if it completes in a single step relative to other threads.

When an atomic store is performed on a shared memory, no other thread can observe the modification half-complete.

When an atomic load is performed on a shared variable, it reads the entire value as it appeared at a single moment in time."

How can I issue a single command from the command line through sql plus?

@find /v "@" < %0 | sqlplus -s scott/tiger@orcl & goto :eof

select sysdate from dual;

Excel VBA - select multiple columns not in sequential order

Working on a project I was stuck for some time on this concept - I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I'm working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn't include the entire code because at this point it's fairly long - if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable "SelectRanges" as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

AngularJS error: 'argument 'FirstCtrl' is not a function, got undefined'

You have 2 unnamed ng-app directives in your html.
Lose the one in your div.

Update
Let's try a different approach.
Define a module in your js file and assign the ng-appdirective to it. After that, define the controller like an ng component, not as a simple function:

<div ng-app="myAppName">  
<!-- or what's the root node of your angular app -->

and the js part:

angular.module('myAppName', [])
    .controller('FirstCtrl', function($scope) {
         $scope.data = {message: 'Hello'};
    });

Here's an online demo that is doing just that : http://jsfiddle.net/FssbL/1/

how to instanceof List<MyType>?

If this can't be wrapped with generics (@Martijn's answer) it's better to pass it without casting to avoid redundant list iteration (checking the first element's type guarantees nothing). We can cast each element in the piece of code where we iterate the list.

Object attVal = jsonMap.get("attName");
List<Object> ls = new ArrayList<>();
if (attVal instanceof List) {
    ls.addAll((List) attVal);
} else {
    ls.add(attVal);
}

// far, far away ;)
for (Object item : ls) {
    if (item instanceof String) {
        System.out.println(item);
    } else {
        throw new RuntimeException("Wrong class ("+item .getClass()+") of "+item );
    }
}

Accessing the index in 'for' loops?

First of all, the indexes will be from 0 to 4. Programming languages start counting from 0; don't forget that or you will come across an index out of bounds exception. All you need in the for loop is a variable counting from 0 to 4 like so:

for x in range(0, 5):

Keep in mind that I wrote 0 to 5 because the loop stops one number before the max. :)

To get the value of an index use

list[index]

Android: Storing username and password?

Most Android and iPhone apps I have seen use an initial screen or dialog box to ask for credentials. I think it is cumbersome for the user to have to re-enter their name/password often, so storing that info makes sense from a usability perspective.

The advice from the (Android dev guide) is:

In general, we recommend minimizing the frequency of asking for user credentials -- to make phishing attacks more conspicuous, and less likely to be successful. Instead use an authorization token and refresh it.

Where possible, username and password should not be stored on the device. Instead, perform initial authentication using the username and password supplied by the user, and then use a short-lived, service-specific authorization token.

Using the AccountManger is the best option for storing credentials. The SampleSyncAdapter provides an example of how to use it.

If this is not an option to you for some reason, you can fall back to persisting credentials using the Preferences mechanism. Other applications won't be able to access your preferences, so the user's information is not easily exposed.

Delete keychain items when an app is uninstalled

For those looking for a Swift version of @amro's answer:

    let userDefaults = NSUserDefaults.standardUserDefaults()

    if userDefaults.boolForKey("hasRunBefore") == false {

        // remove keychain items here


        // update the flag indicator
        userDefaults.setBool(true, forKey: "hasRunBefore")
        userDefaults.synchronize() // forces the app to update the NSUserDefaults

        return
    }

Remove ListView items in Android

At first you should remove the item from your list. Later you may empty your adapter and refill it with new list.

private void add(final List<Track> trackList) {
    MyAdapter bindingData = new MyAdapter(MyActivity.this, trackList);

    list = (ListView) findViewById(R.id.my_list); // TODO

    list.setAdapter(bindingData);


    // Click event for single list row
    list.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View view,
                final int position, long id) {
            // ShowPlacePref(places, position);
            AlertDialog.Builder showPlace = new AlertDialog.Builder(
                    Favoriler.this);
            showPlace.setMessage("Remove from list?");
            showPlace.setPositiveButton("DELETE", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {    

                    trackList.remove(position); //FIRST OF ALL REMOVE ITEM FROM LIST
                    list.setAdapter(null); // THEN EMPTY YOUR ADAPTER

                    add(trackList); // AT LAST REFILL YOUR LISTVIEW (Recursively)

                }

            });
            showPlace.setNegativeButton("CANCEL", new OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            showPlace.show();
        }

    });

}

What are the differences between C, C# and C++ in terms of real-world applications?

C is the core language that most closely resembles and directly translates into CPU machine code. CPUs follow instructions that move, add, logically combine, compare, jump, push and pop. C does exactly this using much easier syntax. If you study the disassembly, you can learn to write C code that is just as fast and compact as assembly. It is my preferred language on 8 bit micro controllers with limited memory. If you write a large PC program in C you will get into trouble because of its limited organization. That is where object oriented programming becomes powerful. The ability of C++ and C# classes to contain data and functions together enforces organization which in turn allows more complex operability over C. C++ was essential for quick processing in the past when CPUs only had one core. I am beginning to learn C# now. Its class only structure appears to enforce a higher degree of organization than C++ which should ultimately lead to faster development and promote code sharing. C# is not interpreted like VB. It is partially compiled at development time and then further translated at run time to become more platform friendly.

How can I split a JavaScript string by white space or comma?

When I want to take into account extra characters like your commas (in my case each token may be entered with quotes), I'd do a string.replace() to change the other delimiters to blanks and then split on whitespace.

Where is SQL Profiler in my SQL Server 2008?

first get the profiler Exe from: http://expressprofiler.codeplex.com

then you can add it simply to the Management studio:

Tools -> External tools... ->

a- locate the exe file on your disk (If installed, it's typically C:\Program Files (x86)\ExpressProfiler\ExpressProfiler.exe)

b- give it a name e.g. Express Profiler

that's it :) you have your Profiler with your sql express edition

enter image description here

How do I set a JLabel's background color?

Use

label.setOpaque(true);

Otherwise the background is not painted, since the default of opaque is false for JLabel.

From the JavaDocs:

If true the component paints every pixel within its bounds. Otherwise, the component may not paint some or all of its pixels, allowing the underlying pixels to show through.

For more information, read the Java Tutorial How to Use Labels.

How to put scroll bar only for modal-body?

Adding on to Carlos Calla's great answer.

The height of .modal-body must be set, BUT you can use media queries to make sure it's appropriate for the screen size.

.modal-body{
    height: 250px;
    overflow-y: auto;
}

@media (min-height: 500px) {
    .modal-body { height: 400px; }
}

@media (min-height: 800px) {
    .modal-body { height: 600px; }
}

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

First of all, a caveat. Why do you want to use telnet? telnet is an old protocol, unsafe and impractical for remote access. It's been (almost)totally replaced by ssh.

To answer your questions, it depends. It depends on the telnet client you use. If you use microsoft telnet, you can't. Microsoft telnet does not have any mean to send commands from a batch file or a command line.

How do I debug a stand-alone VBScript script?

For posterity, here's Microsoft's article KB308364 on the subject. This no longer exists on their website, it is from an archive.

How to debug Windows Script Host, VBScript, and JScript files

SUMMARY

The purpose of this article is to explain how to debug Windows Script Host (WSH) scripts, which can be written in any ActiveX script language (as long as the proper language engine is installed), but which, by default, are written in VBScript and JScript. There are certain flags in the registry and, depending on the debugger used, certain required procedures to enable debugging.

MORE INFORMATION

To debug WSH scripts in Microsoft Visual InterDev, the Microsoft Script Debugger, or any other debugger, use the following command-line syntax to start the script:

wscript.exe //d <path to WSH file>
           This code informs the user when a runtime error has occurred and gives the user a choice to debug the application. Also, the //x flag

can be used, as follows, to throw an immediate exception, which starts the debugger immediately after the script starts running:

wscript.exe //d //x <path to WSH file>
           After a debug condition exists, the following registry key determines which debugger will be used:

HKEY_CLASSES_ROOT\CLSID\{834128A2-51F4-11D0-8F20-00805F2CD064}\LocalServer32

The script debugger should be Msscrdbg.exe, and the Visual InterDev debugger should be Mdm.exe.

If Visual InterDev is the default debugger, make sure that just-in-time (JIT) functionality is enabled. To do this, follow these steps:

  1. Start Visual InterDev.

  2. On the Tools menu, click Options.

  3. Click Debugger, and then ensure that the Just-In-Time options are selected for both the General and Script categories.

Additionally, if you are trying to debug a .wsf file, make sure that the following registry key is set to 1:

HKEY_CURRENT_USER\Software\Microsoft\Windows Script\Settings\JITDebug

PROPERTIES

Article ID: 308364 - Last Review: June 19, 2014 - Revision: 3.0

Keywords: kbdswmanage2003swept kbinfo KB308364

How to enable Google Play App Signing

While Migrating Android application package file (APK) to Android App Bundle (AAB), publishing app into Play Store i faced this issue and got resolved like this below...

When building .aab file you get prompted for the location to store key export path as below:

enter image description here
enter image description here In second image you find Encrypted key export path Location where our .pepk will store in the specific folder while generating .aab file.

Once you log in to the Google Play Console with play store credential: select your project from left side choose App Signing option Release Management>>App Signing enter image description here

you will find the Google App Signing Certification window ACCEPT it.

After that you will find three radio button select **

Upload a key exported from Android Studio radio button

**, it will expand you APP SIGNING PRIVATE KEY button as below

enter image description here

click on the button and choose the .pepk file (We Stored while generating .aab file as above)

Read the all other option and submit.

Once Successfully you can go back to app release and browse the .aab file and complete RollOut...

@Ambilpura

How can I force WebKit to redraw/repaint to propagate style changes?

the "display/offsetHeight" hack didn't work in my case, at least when it was applied to the element being animated.

i had a dropdown menu that was being open/closed over the page content. the artifacts were being left on the page content after the menu had closed (only in webkit browsers). the only way the "display/offsetHeight" hack worked is if i applied it to the body, which seems nasty.

however, i did find another solution:

  1. before the element starts animating, add a class that defines "-webkit-backface-visibility: hidden;" on the element (you could also use inline style, i'd guess)
  2. when it's done animating, remove the class (or style)

this is still pretty hacky (it uses a CSS3 property to force hardware rendering), but at least it only affects the element in question, and worked for me on both safari and chrome on PC and Mac.

"OverflowError: Python int too large to convert to C long" on windows but not mac

You'll get that error once your numbers are greater than sys.maxsize:

>>> p = [sys.maxsize]
>>> preds[0] = p
>>> p = [sys.maxsize+1]
>>> preds[0] = p
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OverflowError: Python int too large to convert to C long

You can confirm this by checking:

>>> import sys
>>> sys.maxsize
2147483647

To take numbers with larger precision, don't pass an int type which uses a bounded C integer behind the scenes. Use the default float:

>>> preds = np.zeros((1, 3))

How to find a hash key containing a matching value

Heres an easy way to do find the keys of a given value:

    clients = {
      "yellow"=>{"client_id"=>"2178"}, 
      "orange"=>{"client_id"=>"2180"}, 
      "red"=>{"client_id"=>"2179"}, 
      "blue"=>{"client_id"=>"2181"}
    }

    p clients.rassoc("client_id"=>"2180")

...and to find the value of a given key:

    p clients.assoc("orange") 

it will give you the key-value pair.

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

This worked for me. may help some one. Turn off firewall. on RHEL 7

systemctl stop  firewalld

Get screenshot on Windows with Python?

For pyautogui users:

import pyautogui
screenshot = pyautogui.screenshot()

How to remove hashbang from url?

Hash is a default vue-router mode setting, it is set because with hash, application doesn't need to connect server to serve the url. To change it you should configure your server and set the mode to HTML5 History API mode.

For server configuration this is the link to help you set up Apache, Nginx and Node.js servers:

https://router.vuejs.org/guide/essentials/history-mode.html

Then you should make sure, that vue router mode is set like following:

vue-router version 2.x

const router = new VueRouter({
  mode: 'history',
  routes: [...]
})

To be clear, these are all vue-router modes you can choose: "hash" | "history" | "abstract".

Transitions on the CSS display property

I suspect that the reason that transitions are disabled if display is changed is because of what display actually does. It does not change anything that could conceivably be smoothly animated.

display: none; and visibility: hidden; are two entirely different things.
Both do have the effect of making the element invisible, but with visibility: hidden; it’s still rendered in the layout, but just not visibly so.
The hidden element still takes up space, and is still rendered inline or as a block or block-inline or table or whatever the display element tells it to render as, and takes up space accordingly.
Other elements do not automatically move to occupy that space. The hidden element just doesn’t render its actual pixels to the output.

display: none on the other hand actually prevents the element from rendering entirely.
It does not take up any layout space.
Other elements that would’ve occupied some or all of the space taken up by this element now adjust to occupy that space, as if the element simply did not exist at all.

display is not just another visual attribute.
It establishes the entire rendering mode of the element, such as whether it’s a block, inline, inline-block, table, table-row, table-cell, list-item, or whatever!
Each of those have very different layout ramifications, and there would be no reasonable way to animate or smoothly transition them (try to imagine a smooth transition from block to inline or vice-versa, for instance!).

This is why transitions are disabled if display changes (even if the change is to or from nonenone isn’t merely invisibility, it’s its own element rendering mode that means no rendering at all!).

Equivalent of explode() to work with strings in MySQL

MYSQL has no explode() like function built in. But you can easily add similar function to your DB and then use it from php queries. That function will look like:

CREATE FUNCTION SPLIT_STRING(str VARCHAR(255), delim VARCHAR(12), pos INT)
RETURNS VARCHAR(255)
RETURN REPLACE(SUBSTRING(SUBSTRING_INDEX(str, delim, pos),
       CHAR_LENGTH(SUBSTRING_INDEX(str, delim, pos-1)) + 1),
       delim, '');

Usage:

SELECT SPLIT_STRING('apple, pear, melon', ',', 1)

The example above will return apple. I think that it will be impossible to return array in MySQL so you must specify which occurrence to return explicitly in pos. Let me know if you succeed using it.

Android statusbar icons color

@eOnOe has answered how we can change status bar tint through xml. But we can also change it dynamically in code:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    View decor = getWindow().getDecorView();
    if (shouldChangeStatusBarTintToDark) {
        decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    } else {
        // We want to change tint color to white again.
        // You can also record the flags in advance so that you can turn UI back completely if
        // you have set other flags before, such as translucent or full screen.
        decor.setSystemUiVisibility(0);
    }
}

error_reporting(E_ALL) does not produce error

Your file has syntax error, so your file was not interpreted, so settings was not changed and you have blank page.

You can separate your file to two.

index.php

<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
include 'error.php';

error.php

<?
echo('catch this -> ' ;. $thisdoesnotexist);

LINQ to read XML

Try this.

using System.Xml.Linq;

void Main()
{
    StringBuilder result = new StringBuilder();

    //Load xml
    XDocument xdoc = XDocument.Load("data.xml");

    //Run query
    var lv1s = from lv1 in xdoc.Descendants("level1")
               select new { 
                   Header = lv1.Attribute("name").Value,
                   Children = lv1.Descendants("level2")
               };

    //Loop through results
    foreach (var lv1 in lv1s){
            result.AppendLine(lv1.Header);
            foreach(var lv2 in lv1.Children)
                 result.AppendLine("     " + lv2.Attribute("name").Value);
    }

    Console.WriteLine(result);
}

How to set a maximum execution time for a mysql query?

pt_kill has an option for such. But it is on-demand, not continually monitoring. It does what @Rafa suggested. However see --sentinel for a hint of how to come close with cron.

Show history of a file?

Have you tried this:

gitk path/to/file

Can you set a border opacity in CSS?

*Not as far as i know there isn't what i do normally in this kind of circumstances is create a block beneath with a bigger size((bordersize*2)+originalsize) and make it transparent using

filter:alpha(opacity=50);
-moz-opacity:0.5;
-khtml-opacity: 0.5;
opacity: 0.5;

here is an example

#main{
    width:400px;
    overflow:hidden;
    position:relative;
}
.border{
    width:100%;
    position:absolute;
    height:100%;
    background-color:#F00;
    filter:alpha(opacity=50);
    -moz-opacity:0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
}
.content{
    margin:15px;/*size of border*/
    background-color:black;
}
<div id="main">
    <div class="border">
    </div>
    <div class="content">
        testing
    </div>
</div>

Update:

This answer is outdated, since after all this question is more than 8 years old. Today all up to date browsers support rgba, box shadows and so on. But this is a decent example how it was 8+ years ago.

Dynamically select data frame columns using $ and a character value

If I understand correctly, you have a vector containing variable names and would like loop through each name and sort your data frame by them. If so, this example should illustrate a solution for you. The primary issue in yours (the full example isn't complete so I"m not sure what else you may be missing) is that it should be order(Q1_R1000[,parameter[X]]) instead of order(Q1_R1000$parameter[X]), since parameter is an external object that contains a variable name opposed to a direct column of your data frame (which when the $ would be appropriate).

set.seed(1)
dat <- data.frame(var1=round(rnorm(10)),
                   var2=round(rnorm(10)),
                   var3=round(rnorm(10)))
param <- paste0("var",1:3)
dat
#   var1 var2 var3
#1    -1    2    1
#2     0    0    1
#3    -1   -1    0
#4     2   -2   -2
#5     0    1    1
#6    -1    0    0
#7     0    0    0
#8     1    1   -1
#9     1    1    0
#10    0    1    0

for(p in rev(param)){
   dat <- dat[order(dat[,p]),]
 }
dat
#   var1 var2 var3
#3    -1   -1    0
#6    -1    0    0
#1    -1    2    1
#7     0    0    0
#2     0    0    1
#10    0    1    0
#5     0    1    1
#8     1    1   -1
#9     1    1    0
#4     2   -2   -2

Excel: Search for a list of strings within a particular string using array formulas?

  1. Arange your word list with delimiter which never occures in the words, f.e. |
  2. swap arguments in find call - we want search if cell value is matching one of the words in pattern string {=FIND("cell I want to search","list of words I want to search for")}
  3. if the patterns are similar, there is a risk of getting more results than wanted, we restrict just correct results via adding &"|" to the cell value tested (works well with array formulas) cell G3 could contain: {=SUM(FIND($A$1:$A$100&"|";A3))} this ensures spreadsheet will compare strings like "cellvlaue|" againts "pattern1|", "pattern2|" etc. which sorts out conflicts like pattern1="newly added", pattern2="added" (sum of all cells matching "added" would be too high, including the target values for cells matching "newly added", which would be a logical error)

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}

How to sum the values of a JavaScript object?

Sum the object key value by parse Integer. Converting string format to integer and summing the values

_x000D_
_x000D_
var obj = {
  pay: 22
};
obj.pay;
console.log(obj.pay);
var x = parseInt(obj.pay);
console.log(x + 20);
_x000D_
_x000D_
_x000D_

Is it possible to install iOS 6 SDK on Xcode 5?

I was also running the same problem when I updated to xcode 5 it removed older sdk. But I taken the copy of older SDK from another computer and the same you can download from following link.

http://www.4shared.com/zip/NlPgsxz6/iPhoneOS61sdk.html
(www.4shared.com test account [email protected]/test)

There are 2 ways to work with.

1) Unzip and paste this folder to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs & restart the xcode.

But this might again removed by Xcode if you update xcode.

2) Another way is Unzip and paste where you want and go to /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs and create a symbolic link here, so that the SDK will remain same even if you update the Xcode.

Another change I made, Build Setting > Architectures > standard (not 64) so list all the versions of Deployment Target

No need to download the zip if you only wanted to change the deployment target.

Here are some screenshots. enter image description here enter image description here

How to force IE10 to render page in IE9 document mode

Do you mean you want to tell your copy of IE 10 to render the pages it views in IE 9 mode?

Or do you mean you want your website to force IE 10 to render it in IE 9 mode?

For the former:

To force a webpage you are viewing in Internet Explorer 10 into a particular document compatibility mode, first open F12 Tools by pressing the F12 key. Then, on the Browser Mode menu, click Internet Explorer 10, and on the Document Mode menu, click Standards.

http://msdn.microsoft.com/en-gb/library/ie/hh920756(v=vs.85).aspx

For the latter, the other answers are correct, but I wouldn't advise doing that. IE 10 is more standards-compliant (i.e. more similar to other browsers) than IE 9.

How to return a resultset / cursor from a Oracle PL/SQL anonymous block that executes Dynamic SQL?

You should be able to declare a cursor to be a bind variable (called parameters in other DBMS')

like Vincent wrote, you can do something like this:

begin
  open :yourCursor
    for 'SELECT "'|| :someField ||'" from yourTable where x = :y'
      using :someFilterValue;
end;

You'd have to bind 3 vars to that script. An input string for "someField", a value for "someFilterValue" and an cursor for "yourCursor" which has to be declared as output var.

Unfortunately, I have no idea how you'd do that from C++. (One could say fortunately for me, though. ;-) )

Depending on which access library you use, it might be a royal pain or straight forward.

How to use zIndex in react-native

I believe there are different ways to do this based on what you need exactly, but one way would be to just put both Elements A and B inside Parent A.

    <View style={{ position: 'absolute' }}>    // parent of A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 1 }} />  // element A
        <View style={{ zIndex: 0, position: 'absolute' }} />  // element B
    </View>

How to replace a character with a newline in Emacs?

inline just: C-M-S-% (if binding keys still default) than replace-string^J

Adding and using header (HTTP) in nginx

You can use upstream headers (named starting with $http_) and additional custom headers. For example:

add_header X-Upstream-01 $http_x_upstream_01;
add_header X-Hdr-01  txt01;

next, go to console and make request with user's header:

curl -H "X-Upstream-01: HEADER1" -I http://localhost:11443/

the response contains X-Hdr-01, seted by server and X-Upstream-01, seted by client:

HTTP/1.1 200 OK
Server: nginx/1.8.0
Date: Mon, 30 Nov 2015 23:54:30 GMT
Content-Type: text/html;charset=UTF-8
Connection: keep-alive
X-Hdr-01: txt01
X-Upstream-01: HEADER1

What's the difference between Cache-Control: max-age=0 and no-cache?

max-age=0

This is equivalent to clicking Refresh, which means, give me the latest copy unless I already have the latest copy.

no-cache

This is holding Shift while clicking Refresh, which means, just redo everything no matter what.

PHP Warning: Unknown: failed to open stream

I just came across of this same problem and in my case it was caused by selinux. Disabling it solved the issue. And no, I don't need selinux on my workstation, thank you.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

Replace last occurrence of a string in a string

Shorthand for accepted answer

function str_lreplace($search, $replace, $subject){ 
    return is_numeric($pos=strrpos($subject,$search))?
    substr_replace($subject,$replace,$pos,strlen($search)):$subject;
}

Shortest distance between a point and a line segment

Python Numpy implementation for 2D coordinate array:

import numpy as np


def dist2d(p1, p2, coords):
    ''' Distance from points to a finite line btwn p1 -> p2 '''
    assert coords.ndim == 2 and coords.shape[1] == 2, 'coords is not 2 dim'
    dp = p2 - p1
    st = dp[0]**2 + dp[1]**2
    u = ((coords[:, 0] - p1[0]) * dp[0] + (coords[:, 1] - p1[1]) * dp[1]) / st

    u[u > 1.] = 1.
    u[u < 0.] = 0.

    dx = (p1[0] + u * dp[0]) - coords[:, 0]
    dy = (p1[1] + u * dp[1]) - coords[:, 1]

    return np.sqrt(dx**2 + dy**2)


# Usage:
p1 = np.array([0., 0.])
p2 = np.array([0., 10.])

# List of coordinates
coords = np.array(
    [[0., 0.],
     [5., 5.],
     [10., 10.],
     [20., 20.]
     ])

d = dist2d(p1, p2, coords)

# Single coordinate
coord = np.array([25., 25.])
d = dist2d(p1, p2, coord[np.newaxis, :])

Set inputType for an EditText Programmatically?

To unhide password:

editText.setInputType(
      InputType.TYPE_CLASS_TEXT|
      InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
);

To hide password again:

editText.setTransformationMethod(PasswordTransformationMethod.getInstance());

SQL grouping by all the columns

No because this fundamentally means that you will not be grouping anything. If you group by all columns (and have a properly defined table w/ a unique index) then SELECT * FROM table is essentially the same thing as SELECT * FROM table GROUP BY *.

Express-js wildcard routing to cover everything under and including a path

I think you will have to have 2 routes. If you look at line 331 of the connect router the * in a path is replaced with .+ so will match 1 or more characters.

https://github.com/senchalabs/connect/blob/master/lib/middleware/router.js

If you have 2 routes that perform the same action you can do the following to keep it DRY.

var express = require("express"),
    app = express.createServer();

function fooRoute(req, res, next) {
  res.end("Foo Route\n");
}

app.get("/foo*", fooRoute);
app.get("/foo", fooRoute);

app.listen(3000);

JavaScript displaying a float to 2 decimal places

float_num.toFixed(2);

Note:toFixed() will round or pad with zeros if necessary to meet the specified length.

react-router (v4) how to go back?

For use with React Router v4 and a functional component anywhere in the dom-tree.

import React from 'react';
import { withRouter } from 'react-router-dom';

const GoBack = ({ history }) => <img src="./images/back.png" onClick={() => history.goBack()} alt="Go back" />;

export default withRouter(GoBack);

How to Solve Max Connection Pool Error

Before you begin to curse your application you need to check this:

  1. Is your application the only one using that instance of SQL Server. a. If the answer to that is NO then you need to investigate how the other applications are consuming resources on your SQl Server.run b. If the answer is yes then you must investigate your application.

  2. Run SQL Server Profiler and check what activity is happening in other applications (1a) using SQL Server and check your application as well (1b).

  3. If indeed your application is starved off of resources then you need to make farther investigations. For more read on this http://sqlserverplanet.com/troubleshooting/sql-server-slowness

How to test if a string contains one of the substrings in a list, in pandas?

Here is a one line lambda that also works:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Input:

searchfor = ['og', 'at']

df = pd.DataFrame([('cat', 1000.0), ('hat', 2000000.0), ('dog', 1000.0), ('fog', 330000.0),('pet', 330000.0)], columns=['col1', 'col2'])

   col1  col2
0   cat 1000.0
1   hat 2000000.0
2   dog 1000.0
3   fog 330000.0
4   pet 330000.0

Apply Lambda:

df["TrueFalse"] = df['col1'].apply(lambda x: 1 if any(i in x for i in searchfor) else 0)

Output:

    col1    col2        TrueFalse
0   cat     1000.0      1
1   hat     2000000.0   1
2   dog     1000.0      1
3   fog     330000.0    1
4   pet     330000.0    0

How do I make Java register a string input with spaces?

This is a sample implementation of taking input in java, I added some fault tolerance on just the salary field to show how it's done. If you notice, you also have to close the input stream .. Enjoy :-)

/* AUTHOR: MIKEQ
 * DATE: 04/29/2016
 * DESCRIPTION: Take input with Java using Scanner Class, Wow, stunningly fun. :-) 
 * Added example of error check on salary input.
 * TESTED: Eclipse Java EE IDE for Web Developers. Version: Mars.2 Release (4.5.2) 
 */

import java.util.Scanner;

public class userInputVersion1 {

    public static void main(String[] args) {

    System.out.println("** Taking in User input **");

    Scanner input = new Scanner(System.in);
    System.out.println("Please enter your name : ");
    String s = input.nextLine(); // getting a String value (full line)
    //String s = input.next(); // getting a String value (issues with spaces in line)

    System.out.println("Please enter your age : ");
    int i = input.nextInt(); // getting an integer

    // version with Fault Tolerance:
    System.out.println("Please enter your salary : ");
    while (!input.hasNextDouble())
    {
        System.out.println("Invalid input\n Type the double-type number:");
        input.next();
    }
    double d = input.nextDouble();    // need to check the data type?

    System.out.printf("\nName %s" +
            "\nAge: %d" +
            "\nSalary: %f\n", s, i, d);

    // close the scanner
    System.out.println("Closing Scanner...");
    input.close();
    System.out.println("Scanner Closed.");      
}
}

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

How to get am pm from the date time string using moment js

You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week, DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

_x000D_
_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Properties private set;

The two common approaches are either that the class should have a constructor for the DAL to use, or the DAL should use reflection to hydrate objects.

Left function in c#

var value = fac.GetCachedValue("Auto Print Clinical Warnings")
// 0 = Start at the first character
// 1 = The length of the string to grab
if (value.ToLower().SubString(0, 1) == "y")
{
    // Do your stuff.
}

How do I create a shortcut via command-line in Windows?

I present a small hybrid script [BAT/VBS] to create a desktop shortcut. And you can of course modifie it to your purpose.

@echo off
mode con cols=87 lines=5 & color 9B
Title Shortcut Creator for your batch and applications files by Hackoo 2015
Set MyFile=%~f0
Set ShorcutName=HackooTest
(
echo Call Shortcut("%MyFile%","%ShorcutName%"^)
echo ^'**********************************************************************************************^)
echo Sub Shortcut(ApplicationPath,Nom^)
echo    Dim objShell,DesktopPath,objShortCut,MyTab
echo    Set objShell = CreateObject("WScript.Shell"^)
echo    MyTab = Split(ApplicationPath,"\"^)
echo    If Nom = "" Then
echo    Nom = MyTab(UBound(MyTab^)^)
echo    End if
echo    DesktopPath = objShell.SpecialFolders("Desktop"^)
echo    Set objShortCut = objShell.CreateShortcut(DesktopPath ^& "\" ^& Nom ^& ".lnk"^)
echo    objShortCut.TargetPath = Dblquote(ApplicationPath^)
echo    ObjShortCut.IconLocation = "Winver.exe,0"
echo    objShortCut.Save
echo End Sub
echo ^'**********************************************************************************************
echo ^'Fonction pour ajouter les doubles quotes dans une variable
echo Function DblQuote(Str^)
echo    DblQuote = Chr(34^) ^& Str ^& Chr(34^)
echo End Function
echo ^'**********************************************************************************************
) > Shortcutme.vbs
Start /Wait Shortcutme.vbs
Del Shortcutme.vbs
::***************************************Main Batch*******************************************
cls
echo Done and your main batch goes here !
echo i am a test 
Pause > Nul
::********************************************************************************************

notifyDataSetChanged not working on RecyclerView

Try this method:

List<Business> mBusinesses2 = mBusinesses;
mBusinesses.clear();
mBusinesses.addAll(mBusinesses2);
//and do the notification

a little time consuming, but it should work.

Set margins in a LinearLayout programmatically

/*
 * invalid margin
 */
private void invalidMarginBottom() {
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) frameLayoutContent.getLayoutParams();
    lp.setMargins(0, 0, 0, 0);
    frameLayoutContent.setLayoutParams(lp);
}

you should be ware of the type of the view's viewGroup.In the code above, for example,I want to change the frameLayout's margin,and the frameLayout's view group is a RelativeLayout,so you need to covert to (RelativeLayout.LayoutParams)

How do I wrap text in a pre tag?

Most succinctly, this forces content to wrap inside of a "pre" tag without breaking words. Cheers!

pre {
  white-space: pre-wrap;
  word-break: keep-all
}

What is the best Java QR code generator library?

QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake.

Vue equivalent of setTimeout?

use this.animationStop, not use this.animationStop ( )

animationRun(){
    this.sliderClass.anim = true;
    setTimeout(this.animationStop, 500);
},

How to use the TextWatcher class in Android?

For Kotlin use KTX extension function: (It uses TextWatcher as previous answers)

yourEditText.doOnTextChanged { text, start, count, after -> 
        // action which will be invoked when the text is changing
    }


import core-KTX:

implementation "androidx.core:core-ktx:1.2.0"

JPanel setBackground(Color.BLACK) does nothing

If your panel is 'not opaque' (transparent) you wont see your background color.

What is the purpose and uniqueness SHTML?

SHTML is a file extension that lets the web server know the file should be processed as using Server Side Includes (SSI).

(HTML is...you know what it is, and DHTML is Microsoft's name for Javascript+HTML+CSS or something).

You can use SSI to include a common header and footer in your pages, so you don't have to repeat code as much. Changing one included file updates all of your pages at once. You just put it in your HTML page as per normal.

It's embedded in a standard XML comment, and looks like this:

<!--#include virtual="top.shtml" -->

It's been largely superseded by other mechanisms, such as PHP includes, but some hosting packages still support it and nothing else.

You can read more in this Wikipedia article.

Time complexity of nested for-loop

Indeed, it is O(n^2). See also a very similar example with the same runtime here.

Unicode characters in URLs

For me this is the correct way, This just worked:

    $linker = rawurldecode("$link");
    <a href="<?php echo $link;?>"   target="_blank"><?php echo $linker ;?></a>

This worked, and now links are displayed properly:

http://newspaper.annahar.com/article/121638-????--????-???-??-??????-?????-????-??????-??????-????-??????-?????-????????

Link found on:

http://www.galeriejaninerubeiz.com/newsite/news

Change date format in a Java string

[edited to include BalusC's corrections] The SimpleDateFormat class should do the trick:

String pattern = "yyyy-MM-dd HH:mm:ss.S";
SimpleDateFormat format = new SimpleDateFormat(pattern);
try {
  Date date = format.parse("2011-01-18 00:00:00.0");
  System.out.println(date);
} catch (ParseException e) {
  e.printStackTrace();
}

"Could not find the main class" error when running jar exported by Eclipse

Right click on the project. Go to properties. Click on Run/Debug Settings. Now delete the run config of your main class that you are trying to run. Now, when you hit run again, things would work just fine.

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

This error message means that you are attempting to use Python 3 to follow an example or run a program that uses the Python 2 print statement:

print "Hello, World!"

The statement above does not work in Python 3. In Python 3 you need to add parentheses around the value to be printed:

print("Hello, World!")

“SyntaxError: Missing parentheses in call to 'print'” is a new error message that was added in Python 3.4.2 primarily to help users that are trying to follow a Python 2 tutorial while running Python 3.

In Python 3, printing values changed from being a distinct statement to being an ordinary function call, so it now needs parentheses:

>>> print("Hello, World!")
Hello, World!

In earlier versions of Python 3, the interpreter just reports a generic syntax error, without providing any useful hints as to what might be going wrong:

>>> print "Hello, World!"
  File "<stdin>", line 1
    print "Hello, World!"
                        ^
SyntaxError: invalid syntax

As for why print became an ordinary function in Python 3, that didn't relate to the basic form of the statement, but rather to how you did more complicated things like printing multiple items to stderr with a trailing space rather than ending the line.

In Python 2:

>>> import sys
>>> print >> sys.stderr, 1, 2, 3,; print >> sys.stderr, 4, 5, 6
1 2 3 4 5 6

In Python 3:

>>> import sys
>>> print(1, 2, 3, file=sys.stderr, end=" "); print(4, 5, 6, file=sys.stderr)
1 2 3 4 5 6

Starting with the Python 3.6.3 release in September 2017, some error messages related to the Python 2.x print syntax have been updated to recommend their Python 3.x counterparts:

>>> print "Hello!"
  File "<stdin>", line 1
    print "Hello!"
                 ^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello!")?

Since the "Missing parentheses in call to print" case is a compile time syntax error and hence has access to the raw source code, it's able to include the full text on the rest of the line in the suggested replacement. However, it doesn't currently try to work out the appropriate quotes to place around that expression (that's not impossible, just sufficiently complicated that it hasn't been done).

The TypeError raised for the right shift operator has also been customised:

>>> print >> sys.stderr
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for >>: 'builtin_function_or_method' and '_io.TextIOWrapper'. Did you mean "print(<message>, file=<output_stream>)"?

Since this error is raised when the code runs, rather than when it is compiled, it doesn't have access to the raw source code, and hence uses meta-variables (<message> and <output_stream>) in the suggested replacement expression instead of whatever the user actually typed. Unlike the syntax error case, it's straightforward to place quotes around the Python expression in the custom right shift error message.

How to query a CLOB column in Oracle

If you are using SQL*Plus try the following...

set long 8000

select ...

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

It looks like someone might have revoked the permissions on sys.configurations for the public role. Or denied access to this view to this particular user. Or the user has been created after the public role was removed from the sys.configurations tables.

Provide SELECT permission to public user sys.configurations object.

how do I query sql for a latest record date for each user

select t.username, t.date, t.value
from MyTable t
inner join (
    select username, max(date) as MaxDate
    from MyTable
    group by username
) tm on t.username = tm.username and t.date = tm.MaxDate

Angular ng-if not true

Use like this

<div ng-if="data.IsActive === 1">InActive</div>
<div ng-if="data.IsActive === 0">Active</div>

Returning a value from callback function in Node.js

Its undefined because, console.log(response) runs before doCall(urlToCall); is finished. You have to pass in a callback function aswell, that runs when your request is done.

First, your function. Pass it a callback:

function doCall(urlToCall, callback) {
    urllib.request(urlToCall, { wd: 'nodejs' }, function (err, data, response) {                              
        var statusCode = response.statusCode;
        finalData = getResponseJson(statusCode, data.toString());
        return callback(finalData);
    });
}

Now:

var urlToCall = "http://myUrlToCall";
doCall(urlToCall, function(response){
    // Here you have access to your variable
    console.log(response);
})

@Rodrigo, posted a good resource in the comments. Read about callbacks in node and how they work. Remember, it is asynchronous code.

What is the difference between exit(0) and exit(1) in C?

exit is a system call used to finish a running process from which it is called. The parameter to exit is used to inform the parent process about the status of child process. So, exit(0) can be used (and often used) to indicate successful execution of a process and exit(1) to flag an error. reference link

awk - concatenate two string variable and assign to a third

Concatenating strings in awk can be accomplished by the print command AWK manual page, and you can do complicated combination. Here I was trying to change the 16 char to A and used string concatenation:

echo    CTCTCTGAAATCACTGAGCAGGAGAAAGATT | awk -v w=15 -v BA=A '{OFS=""; print substr($0, 1, w), BA, substr($0,w+2)}'
Output: CTCTCTGAAATCACTAAGCAGGAGAAAGATT

I used the substr function to extract a portion of the input (STDIN). I passed some external parameters (here I am using hard-coded values) that are usually shell variable. In the context of shell programming, you can write -v w=$width -v BA=$my_charval. The key is the OFS which stands for Output Field Separate in awk. Print function take a list of values and write them to the STDOUT and glue them with the OFS. This is analogous to the perl join function.

It looks that in awk, string can be concatenated by printing variable next to each other:

echo xxx | awk -v a="aaa" -v b="bbb" '{ print a b $1 "string literal"}'
# will produce: aaabbbxxxstring literal

How can I check for NaN values?

All the methods to tell if the variable is NaN or None:

None type

In [1]: from numpy import math

In [2]: a = None
In [3]: not a
Out[3]: True

In [4]: len(a or ()) == 0
Out[4]: True

In [5]: a == None
Out[5]: True

In [6]: a is None
Out[6]: True

In [7]: a != a
Out[7]: False

In [9]: math.isnan(a)
Traceback (most recent call last):
  File "<ipython-input-9-6d4d8c26d370>", line 1, in <module>
    math.isnan(a)
TypeError: a float is required

In [10]: len(a) == 0
Traceback (most recent call last):
  File "<ipython-input-10-65b72372873e>", line 1, in <module>
    len(a) == 0
TypeError: object of type 'NoneType' has no len()

NaN type

In [11]: b = float('nan')
In [12]: b
Out[12]: nan

In [13]: not b
Out[13]: False

In [14]: b != b
Out[14]: True

In [15]: math.isnan(b)
Out[15]: True

GridView Hide Column by code

There is a small change to happen, it will not come under rowdatabound, first all the rows should get bound, only then could we hide that. So it will be a separate method after the grid is dataBound.

Sticky Header after scrolling down

Here's a start. Basically, we copy the header on load, and then check (using .scrollTop() or window.scrollY) to see when the user scrolls beyond a point (e.g. 200pixels). Then we simply toggle a class (in this case .down) which moves the original into view.

Lastly all we need to do is apply a transition: top 0.2s ease-in to our clone, so that when it's in the .down state it slides into view. Dunked does it better, but with a little playing around it's easy to configure

CSS

header {
  position: relative;
  width: 100%;
  height: 60px;
}

header.clone {
  position: fixed;
  top: -65px;
  left: 0;
  right: 0;
  z-index: 999;
  transition: 0.2s top cubic-bezier(.3,.73,.3,.74);
}

body.down header.clone {
  top: 0;
}

either Vanilla JS (polyfill as required)

var sticky = {
  sticky_after: 200,
  init: function() {
    this.header = document.getElementsByTagName("header")[0];
    this.clone = this.header.cloneNode(true);
    this.clone.classList.add("clone");
    this.header.insertBefore(this.clone);
    this.scroll();
    this.events();
  },

  scroll: function() {
    if(window.scrollY > this.sticky_after) {
      document.body.classList.add("down");
    }
    else {
      document.body.classList.remove("down");
    }
  },

  events: function() {
    window.addEventListener("scroll", this.scroll.bind(this));
  }
};

document.addEventListener("DOMContentLoaded", sticky.init.bind(sticky));

or jQuery

$(document).ready(function() {
  var $header = $("header"),
      $clone = $header.before($header.clone().addClass("clone"));

  $(window).on("scroll", function() {
    var fromTop = $("body").scrollTop();
    $('body').toggleClass("down", (fromTop > 200));
  });
});

Newer Reflections

Whilst the above answers the OP's original question of "How does Dunked achieve this effect?", I wouldn't recommend this approach. For starters, copying the entire top navigation could be pretty costly, and there's no real reason why we can't use the original (with a little bit of work).

Furthermore, Paul Irish and others, have written about how animating with translate() is better than animating with top. Not only is it more performant, but it also means that you don't need to know the exact height of your element. The above solution would be modified with the following (See JSFiddle):

header.clone {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  transform: translateY(-100%);
  transition: 0.2s transform cubic-bezier(.3,.73,.3,.74);
}

body.down header.clone {
  transform: translateY(0);
}

The only drawback with using transforms is, that whilst browser support is pretty good, you'll probably want to add vendor prefixed versions to maximize compatibility.

ng-options with simple array init

<select ng-model="option" ng-options="o for o in options">

$scope.option will be equal to 'var1' after change, even you see value="0" in generated html

plunker

How to install SQL Server 2005 Express in Windows 8

Microsoft says the SQL Server 2005 it's not compatible with Windows 8, but I've run it without problems (only using SP3) except the installation.

After you run the install file SQLExpr.exe look for a hidden folder recently created in the C drive. Copy the contents to another folder and cancel the installer (or use WinRar to open the file and extract the contents to a temp folder)

After that, find the file sqlncli_x64.msi in the setup folder, and run it.

Now you are ready the run the setup.exe file and install SQL server 2005 without errors

enter image description here

Removing the remembered login and password list in SQL Server Management Studio

Delete:

C:\Documents and Settings\%Your Username%\Application Data\Microsoft\Microsoft SQL Server\90\Tools\Shell\mru.dat"

Git status ignore line endings / identical files / windows & linux environment / dropbox / mled

Use .gitattributes instead, with the following setting:

# Ignore all differences in line endings
*        -crlf

.gitattributes would be found in the same directory as your global .gitconfig. If .gitattributes doesn't exist, add it to that directory. After adding/changing .gitattributes you will have to do a hard reset of the repository in order to successfully apply the changes to existing files.

Ruby sleep or delay less than a second?

sleep(1.0/24.0)

As to your follow up question if that's the best way: No, you could get not-so-smooth framerates because the rendering of each frame might not take the same amount of time.

You could try one of these solutions:

  • Use a timer which fires 24 times a second with the drawing code.
  • Create as many frames as possible, create the motion based on the time passed, not per frame.

Why doesn't CSS ellipsis work in table cell?

Try using max-width instead of width, the table will still calculate the width automatically.

Works even in ie11 (with ie8 compatibility mode).

_x000D_
_x000D_
td.max-width-50 {_x000D_
  border: 1px solid black;_x000D_
  max-width: 50px;_x000D_
  overflow: hidden;_x000D_
  text-overflow: ellipsis;_x000D_
  white-space: nowrap;_x000D_
}
_x000D_
<table>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td class="max-width-50">Hello Stack Overflow</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hello Stack Overflow</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Hello Stack Overflow</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

jsfiddle.

jQuery if checkbox is checked

See main difference between ATTR | PROP | IS below:

Source: http://api.jquery.com/attr/

_x000D_
_x000D_
$( "input" )_x000D_
  .change(function() {_x000D_
    var $input = $( this );_x000D_
    $( "p" ).html( ".attr( 'checked' ): <b>" + $input.attr( "checked" ) + "</b><br>" +_x000D_
      ".prop( 'checked' ): <b>" + $input.prop( "checked" ) + "</b><br>" +_x000D_
      ".is( ':checked' ): <b>" + $input.is( ":checked" ) + "</b>" );_x000D_
  })_x000D_
  .change();
_x000D_
p {_x000D_
    margin: 20px 0 0;_x000D_
  }_x000D_
  b {_x000D_
    color: blue;_x000D_
  }
_x000D_
<meta charset="utf-8">_x000D_
  <title>attr demo</title>_x000D_
  <script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
</head>_x000D_
<body>_x000D_
 _x000D_
<input id="check1" type="checkbox" checked="checked">_x000D_
<label for="check1">Check me</label>_x000D_
<p></p>_x000D_
 _x000D_
_x000D_
 _x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Difference between "this" and"super" keywords in Java

this refers to a reference of the current class.
super refers to the parent of the current class (which called the super keyword).

By doing this, it allows you to access methods/attributes of the current class (including its own private methods/attributes).

super allows you to access public/protected method/attributes of parent(base) class. You cannot see the parent's private method/attributes.

What's the difference between “mod” and “remainder”?

There is a difference between modulus and remainder. For example:

-21 mod 4 is 3 because -21 + 4 x 6 is 3.

But -21 divided by 4 gives -5 with a remainder of -1.

For positive values, there is no difference.

Setting HTTP headers

All of the above answers are wrong because they fail to handle the OPTIONS preflight request, the solution is to override the mux router's interface. See AngularJS $http get request failed with custom header (alllowed in CORS)

func main() {
    r := mux.NewRouter()
    r.HandleFunc("/save", saveHandler)
    http.Handle("/", &MyServer{r})
    http.ListenAndServe(":8080", nil);

}

type MyServer struct {
    r *mux.Router
}

func (s *MyServer) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
    if origin := req.Header.Get("Origin"); origin != "" {
        rw.Header().Set("Access-Control-Allow-Origin", origin)
        rw.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
        rw.Header().Set("Access-Control-Allow-Headers",
            "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
    }
    // Stop here if its Preflighted OPTIONS request
    if req.Method == "OPTIONS" {
        return
    }
    // Lets Gorilla work
    s.r.ServeHTTP(rw, req)
}

Add x and y labels to a pandas plot

In Pandas version 1.10 and above you can use parameters xlabel and ylabel in the method plot:

df.plot(xlabel='X Label', ylabel='Y Label', title='Plot Title')

enter image description here

jQuery Set Selected Option Using Next

From version 1.6.1 on, it's advisable to use the method prop for boolean attributes/properties such as selected, readonly, enabled,...

var theValue = "whatever";
$("#selectID").val( theValue ).prop('selected',true);

For more info, please refer to to http://blog.jquery.com/2011/05/12/jquery-1-6-1-released/

How to create a horizontal loading progress bar?

Just add a STYLE line and your progress becomes horizontal:

<ProgressBar
        style="?android:attr/progressBarStyleHorizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/progress"
        android:layout_centerHorizontal="true"      
        android:layout_centerVertical="true"      
        android:max="100" 
        android:progress="45"/>

How can I split and parse a string in Python?

Python string parsing walkthrough

Split a string on space, get a list, show its type, print it out:

el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"

>>> mylist = mystring.split(" ")

>>> print type(mylist)
<type 'list'>

>>> print mylist
['What', 'does', 'the', 'fox', 'say?']

If you have two delimiters next to each other, empty string is assumed:

el@apollo:~/foo$ python
>>> mystring = "its  so   fluffy   im gonna    DIE!!!"

>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']

Split a string on underscore and grab the 5th item in the list:

el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."

>>> mystring.split("_")[4]
"Kowalski's"

Collapse multiple spaces into one

el@apollo:~/foo$ python
>>> mystring = 'collapse    these       spaces'

>>> mycollapsedstring = ' '.join(mystring.split())

>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']

When you pass no parameter to Python's split method, the documentation states: "runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace".

Hold onto your hats boys, parse on a regular expression:

el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']

The regular expression "[a-m]+" means the lowercase letters a through m that occur one or more times are matched as a delimiter. re is a library to be imported.

Or if you want to chomp the items one at a time:

el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"

>>> mytuple = mystring.partition(" ")

>>> print type(mytuple)
<type 'tuple'>

>>> print mytuple
('theres', ' ', 'coffee in that nebula')

>>> print mytuple[0]
theres

>>> print mytuple[2]
coffee in that nebula

Installing Google Protocol Buffers on mac

There are some issues with building protobuf 2.4.1 from source on a Mac. There is a patch that also has to be applied. All this is contained within the homebrew protobuf241 formula, so I would advise using it.

To install protocol buffer version 2.4.1 type the following into a terminal:

brew tap homebrew/versions
brew install protobuf241

If you already have a protocol buffer version that you tried to install from source, you can type the following into a terminal to have the source code overwritten by the homebrew version:

brew link --force --overwrite protobuf241

Check that you now have the correct version installed by typing:

protoc --version

It should display 2.4.1

How to get Rails.logger printing to the console/stdout when running rspec?

Tail the log as a background job (&) and it will interleave with rspec output.

tail -f log/test.log &
bundle exec rspec

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

For a simpler pure CSS solution that works in most cases, one could remove children's pointer-events by setting them to none

.parent * {
     pointer-events: none;
}

Browser support: IE11+