Programs & Examples On #Woodstock

Project Woodstock is an abandoned JSF 1.x component library. It was initially part of the "Visual JSF Editor" of the "Sun Java Studio Creator" IDE which is later known as Netbeans. It uses "webuijsf" as default tag prefix.

How to beautify JSON in Python?

First install pygments

then

echo '<some json>' | python -m json.tool | pygmentize -l json

How do you set EditText to only accept numeric values in Android?

If anyone want to use only number from 0 to 9 with imeOptions enable then use below line in your EditText

android:inputType="number|none"

This will only allow number and if you click on done/next button of keyboard your focus will move to next field.

The APK file does not exist on disk

Sync, Clean, Rebuild and Invalidate Cache and Restart

None of them worked for me.

I have deleted the APK and output.json files in the release folder and debug folder and then tried sync, clean, and build, then it worked fine.

OR simply Delete folder which has the apk and output.json file (in case of debug/ release)

How to implement private method in ES6 class with Traceur

You can use Symbol

var say = Symbol()

function Cat(){
  this[say]() // call private methos
}

Cat.prototype[say] = function(){ alert('im a private') }

P.S. alexpods is not correct. he get protect rather than private, since inheritance is a name conflict

Actually you can use var say = String(Math.random()) instead Symbol

IN ES6:

var say = Symbol()

class Cat {

  constructor(){
    this[say]() // call private
  }

  [say](){
    alert('im private')
  }

}

What is the use of the JavaScript 'bind' method?

The bind function creates a new function with the same function body as the function it is calling .It is called with the this argument .why we use bind fun. : when every time a new instance is created and we have to use first initial instance then we use bind fun.We can't override the bind fun.simply it stores the initial object of the class.

setInterval(this.animate_to.bind(this), 1000/this.difference);

Signing a Windows EXE file

Another option, if you need to sign the executable on a Linux box is to use signcode from the Mono project tools. It is supported on Ubuntu.

Default parameters with C++ constructors

Sam's answer gives the reason that default arguments are preferable for constructors rather than overloading. I just want to add that C++-0x will allow delegation from one constructor to another, thereby removing the need for defaults.

Unicode character in PHP string

PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}

Or with an anonymous function expression instead of create_function:

function unicodeString($str, $encoding=null) {
    if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
    return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
        return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
    }, $str);
}

Its usage:

$str = unicodeString("\u1000");

Reporting (free || open source) Alternatives to Crystal Reports in Winforms

You could always roll your own. I'm getting rid of Crystal Reports in our project because currently, we can't update our old reports without upgrading everyone to XP, because we develop in VS 2008, and the new CR doesn't support Win2K. Also, CR takes about 30 seconds to build and load the report, mine is instantaneous.

I wrote my own XML serializer, and I build custom objects that are populated from List<T>s, DataTables, etc..., serialize the object, load it into an XmlDocument, append an XSLT stylesheet, and write it to a directory containing that XSLT file and any CSS and images. The XSLT file then transforms it to HTML/CSS when the XML file is opened in the user's browser.

I could also probably load it into a WebBrowser control and use one of the free PDF libraries to convert it to PDF and print it. See these threads for more details:

Python Pandas: Get index of rows which column matches certain value

First you may check query when the target column is type bool (PS: about how to use it please check link )

df.query('BoolCol')
Out[123]: 
    BoolCol
10     True
40     True
50     True

After we filter the original df by the Boolean column we can pick the index .

df=df.query('BoolCol')
df.index
Out[125]: Int64Index([10, 40, 50], dtype='int64')

Also pandas have nonzero, we just select the position of True row and using it slice the DataFrame or index

df.index[df.BoolCol.nonzero()[0]]
Out[128]: Int64Index([10, 40, 50], dtype='int64')

Show hide fragment in android

In addittion, you can do in a Fragment (for example when getting server data failed):

 getView().setVisibility(View.GONE);

make: *** [ ] Error 1 error

From GNU Make error appendix, as you see this is not a Make error but an error coming from gcc.

‘[foo] Error NN’ ‘[foo] signal description’ These errors are not really make errors at all. They mean that a program that make invoked as part of a recipe returned a non-0 error code (‘Error NN’), which make interprets as failure, or it exited in some other abnormal fashion (with a signal of some type). See Errors in Recipes. If no *** is attached to the message, then the subprocess failed but the rule in the makefile was prefixed with the - special character, so make ignored the error.

So in order to attack the problem, the error message from gcc is required. Paste the command in the Makefile directly to the command line and see what gcc says. For more details on Make errors click here.

How to get the clicked link's href with jquery?

this in your callback function refers to the clicked element.

   $(".addressClick").click(function () {
        var addressValue = $(this).attr("href");
        alert(addressValue );
    });

What is InputStream & Output Stream? Why and when do we use them?

OutputStream is an abstract class that represents writing output. There are many different OutputStream classes, and they write out to certain things (like the screen, or Files, or byte arrays, or network connections, or etc). InputStream classes access the same things, but they read data in from them.

Here is a good basic example of using FileOutputStream and FileInputStream to write data to a file, then read it back in.

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

What are the benefits to marking a field as `readonly` in C#?

There is a potential case where the compiler can make a performance optimization based on the presence of the readonly keyword.

This only applies if the read-only field is also marked as static. In that case, the JIT compiler can assume that this static field will never change. The JIT compiler can take this into account when compiling the methods of the class.

A typical example: your class could have a static read-only IsDebugLoggingEnabled field that is initialized in the constructor (e.g. based on a configuration file). Once the actual methods are JIT-compiled, the compiler may omit whole parts of the code when debug logging is not enabled.

I have not checked if this optimization is actually implemented in the current version of the JIT compiler, so this is just speculation.

jQuery .ajax() POST Request throws 405 (Method Not Allowed) on RESTful WCF

For same error code i had quite different reason, I'm sharing here to help

I had web api action like below

public IHttpActionResult GetBooks (int id)

I changed the method to accept two parameters category and author so i changed the parameters as below, i also put the attribute [Httppost]

public IHttpActionResult GetBooks (int category, int author)

I also changed ajax options like below and at this point i start getting error 405 method not allowed

var options = {
    url: '/api/books/GetBooks',
    type: 'POST',
    dataType: 'json',
    cache: false,
    traditional: true, 
    data: {
        category: 1,
        author: 15
    }
}

When i created class for web api action parameters like below error was gone

public class BookParam
{
    public int Category { get; set; }
    public int Author { get; set; }
}
public IHttpActionResult GetBooks (BookParam param)

Angular File Upload

Here is how I did it to upload the excel files:
Directory structure:

app
|-----uploadcomponent
           |-----uploadcomponent.module.ts
           |-----uploadcomponent.html
|-----app.module.ts
|-----app.component.ts
|-----app.service.ts

uploadcomponent.html

<div>
   <form [formGroup]="form" (ngSubmit)="onSubmit()">
     <input type="file" name="profile"  enctype="multipart/form-data" accept=".xlsm,application/msexcel" (change)="onChange($event)" />
     <button type="submit">Upload Template</button>
     <button id="delete_button" class="delete_button" type="reset"><i class="fa fa-trash"></i></button> 
   </form>           
</div>

uploadcomponent.ts

    import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
    import { Component, OnInit } from '@angular/core';
    ....
    export class UploadComponent implements OnInit {
        form: FormGroup;
        constructor(private formBuilder: FormBuilder, private uploadService: AppService) {}
        ngOnInit() {  
            this.form = this.formBuilder.group({
               profile: ['']
            });
        }

        onChange(event) {
            if (event.target.files.length > 0) {
              const file = event.target.files[0];

              this.form.get('profile').setValue(file);
              console.log(this.form.get('profile').value)
            }
        }

        onSubmit() {
           const formData = new FormData();
           formData.append('file', this.form.get('profile').value);

           this.uploadService.upload(formData).subscribe(
             (res) => {
               this.response = res;

               console.log(res);

             },
             (err) => {  
               console.log(err);
             });
         }
    }

app.service.ts

    upload(formData) {
        const endpoint = this.service_url+'upload/';
        const httpOptions = headers: new HttpHeaders({    <<<< Changes are here
            'Authorization': 'token xxxxxxx'})
        };
        return this.http.post(endpoint, formData, httpOptions);
    }

In Backend I use DJango REST Framework.
models.py

from __future__ import unicode_literals
from django.db import models
from django.db import connection
from django_mysql.models import JSONField, Model
import uuid
import os


def change_filename(instance, filename):
    extension = filename.split('.')[-1]
    file_name = os.path.splitext(filename)[0]
    uuid_name = uuid.uuid4()
    return file_name+"_"+str(uuid_name)+"."+extension

class UploadTemplate (Model):
    id = models.AutoField(primary_key=True)
    file = models.FileField(blank=False, null=False, upload_to=change_filename)

    def __str__(self):
        return str(self.file.name)

views.py.

class UploadView(APIView):
    serializer_class = UploadSerializer
    parser_classes = [MultiPartParser]       

    def get_queryset(self):
        queryset = UploadTemplate.objects.all()
        return queryset

    def post(self, request, *args, **kwargs):
        file_serializer = UploadSerializer(data=request.data)
        status = None
        message = None
        if file_serializer.is_valid():
            file_serializer.save()
            status = "Success"
            message = "Success"
        else:
            status = "Failure"
            message = "Failure!"
        content = {'status': status, 'message': message}
        return Response(content)

serializers.py.

from uploadtemplate.models import UploadTemplate
from rest_framework import serializers

class UploadSerializer(serializers.ModelSerializer):
    class Meta:
        model = UploadTemplate
        fields = '__all__'   

urls.py.

router.register(r'uploadtemplate', uploadtemplateviews.UploadTemplateView, 
    base_name='UploadTemplate')
urlpatterns = [
    ....
    url(r'upload/', uploadtemplateviews.UploadTemplateView.as_view()),
] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

MEDIA_URL and MEDIA_ROOT is defined in settings.py of the project.

Thanks!

Invoke or BeginInvoke cannot be called on a control until the window handle has been created

var that = this; // this is a form
(new Thread(()=> {

    var action= new Action(() => {
       something
    }));

    if(!that.IsDisposed)
    {
        if(that.IsHandleCreated)
        {
            //if (that.InvokeRequired)
                that.BeginInvoke(action);
            //else
            // action.Invoke();
        }
        else
            that.HandleCreated+=(sender,event) => {
                action.Invoke();
            };
    }


})).Start();

diff to output only the file names

The approach of running diff -qr old/ new/ has one major drawback: it may miss files in newly created directories. E.g. in the example below the file data/pages/playground/playground.txt is not in the output of diff -qr old/ new/ whereas the directory data/pages/playground/ is (search for playground.txt in your browser to quickly compare). I also posted the following solution on Unix & Linux Stack Exchange, but I'll copy it here as well:

To create a list of new or modified files programmatically the best solution I could come up with is using rsync, sort, and uniq:

(rsync -rcn --out-format="%n" old/ new/ && rsync -rcn --out-format="%n" new/ old/) | sort | uniq

Let me explain with this example: we want to compare two dokuwiki releases to see which files were changed and which ones were newly created.

We fetch the tars with wget and extract them into the directories old/ and new/:

wget http://download.dokuwiki.org/src/dokuwiki/dokuwiki-2014-09-29d.tgz
wget http://download.dokuwiki.org/src/dokuwiki/dokuwiki-2014-09-29.tgz
mkdir old && tar xzf dokuwiki-2014-09-29.tgz -C old --strip-components=1
mkdir new && tar xzf dokuwiki-2014-09-29d.tgz -C new --strip-components=1

Running rsync one way might miss newly created files as the comparison of rsync and diff shows here:

rsync -rcn --out-format="%n" old/ new/

yields the following output:

VERSION
doku.php
conf/mime.conf
inc/auth.php
inc/lang/no/lang.php
lib/plugins/acl/remote.php
lib/plugins/authplain/auth.php
lib/plugins/usermanager/admin.php

Running rsync only in one direction misses the newly created files and the other way round would miss deleted files, compare the output of diff:

diff -qr old/ new/

yields the following output:

Files old/VERSION and new/VERSION differ
Files old/conf/mime.conf and new/conf/mime.conf differ
Only in new/data/pages: playground
Files old/doku.php and new/doku.php differ
Files old/inc/auth.php and new/inc/auth.php differ
Files old/inc/lang/no/lang.php and new/inc/lang/no/lang.php differ
Files old/lib/plugins/acl/remote.php and new/lib/plugins/acl/remote.php differ
Files old/lib/plugins/authplain/auth.php and new/lib/plugins/authplain/auth.php differ
Files old/lib/plugins/usermanager/admin.php and new/lib/plugins/usermanager/admin.php differ

Running rsync both ways and sorting the output to remove duplicates reveals that the directory data/pages/playground/ and the file data/pages/playground/playground.txt were missed initially:

(rsync -rcn --out-format="%n" old/ new/ && rsync -rcn --out-format="%n" new/ old/) | sort | uniq

yields the following output:

VERSION
conf/mime.conf
data/pages/playground/
data/pages/playground/playground.txt
doku.php
inc/auth.php
inc/lang/no/lang.php
lib/plugins/acl/remote.php
lib/plugins/authplain/auth.php
lib/plugins/usermanager/admin.php

rsync is run with theses arguments:

  • -r to "recurse into directories",
  • -c to also compare files of identical size and only "skip based on checksum, not mod-time & size",
  • -n to "perform a trial run with no changes made", and
  • --out-format="%n" to "output updates using the specified FORMAT", which is "%n" here for the file name only

The output (list of files) of rsync in both directions is combined and sorted using sort, and this sorted list is then condensed by removing all duplicates with uniq

Calculate business days

PHPClasses have a nice class for this named PHP Working Days. You can check this class.

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Replacing:

$_SERVER["REMOTE_ADDR"];

With:

$_SERVER["HTTP_X_REAL_IP"];

Worked for me.

What underlies this JavaScript idiom: var self = this?

See this article on alistapart.com. (Ed: The article has been updated since originally linked)

self is being used to maintain a reference to the original this even as the context is changing. It's a technique often used in event handlers (especially in closures).

Edit: Note that using self is now discouraged as window.self exists and has the potential to cause errors if you are not careful.

What you call the variable doesn't particularly matter. var that = this; is fine, but there's nothing magic about the name.

Functions declared inside a context (e.g. callbacks, closures) will have access to the variables/function declared in the same scope or above.

For example, a simple event callback:

_x000D_
_x000D_
function MyConstructor(options) {_x000D_
  let that = this;_x000D_
_x000D_
  this.someprop = options.someprop || 'defaultprop';_x000D_
_x000D_
  document.addEventListener('click', (event) => {_x000D_
    alert(that.someprop);_x000D_
  });_x000D_
}_x000D_
_x000D_
new MyConstructor({_x000D_
  someprop: "Hello World"_x000D_
});
_x000D_
_x000D_
_x000D_

is not JSON serializable

It's worth noting that the QuerySet.values_list() method doesn't actually return a list, but an object of type django.db.models.query.ValuesListQuerySet, in order to maintain Django's goal of lazy evaluation, i.e. the DB query required to generate the 'list' isn't actually performed until the object is evaluated.

Somewhat irritatingly, though, this object has a custom __repr__ method which makes it look like a list when printed out, so it's not always obvious that the object isn't really a list.

The exception in the question is caused by the fact that custom objects cannot be serialized in JSON, so you'll have to convert it to a list first, with...

my_list = list(self.get_queryset().values_list('code', flat=True))

...then you can convert it to JSON with...

json_data = json.dumps(my_list)

You'll also have to place the resulting JSON data in an HttpResponse object, which, apparently, should have a Content-Type of application/json, with...

response = HttpResponse(json_data, content_type='application/json')

...which you can then return from your function.

How do I convert a factor into date format?

Take a look at the formats in ?strptime

R> foo <-  factor("1/15/2006 0:00:00")
R> foo <- as.Date(foo, format = "%m/%d/%Y %H:%M:%S")                                           
R> foo                                                                                       
 [1] "2006-01-15"                                                                             
R> class(foo)                                                                                
 [1] "Date"  

Note that this will work even if foo starts out as a character. It will also work if using other date formats (as.POSIXlt, as.POSIXct).

How to convert a std::string to const char* or char*?

If you just want to pass a std::string to a function that needs const char* you can use

std::string str;
const char * c = str.c_str();

If you want to get a writable copy, like char *, you can do that with this:

std::string str;
char * writable = new char[str.size() + 1];
std::copy(str.begin(), str.end(), writable);
writable[str.size()] = '\0'; // don't forget the terminating 0

// don't forget to free the string after finished using it
delete[] writable;

Edit: Notice that the above is not exception safe. If anything between the new call and the delete call throws, you will leak memory, as nothing will call delete for you automatically. There are two immediate ways to solve this.

boost::scoped_array

boost::scoped_array will delete the memory for you upon going out of scope:

std::string str;
boost::scoped_array<char> writable(new char[str.size() + 1]);
std::copy(str.begin(), str.end(), writable.get());
writable[str.size()] = '\0'; // don't forget the terminating 0

// get the char* using writable.get()

// memory is automatically freed if the smart pointer goes 
// out of scope

std::vector

This is the standard way (does not require any external library). You use std::vector, which completely manages the memory for you.

std::string str;
std::vector<char> writable(str.begin(), str.end());
writable.push_back('\0');

// get the char* using &writable[0] or &*writable.begin()

Django - "no module named django.core.management"

I got the same error and I fixed it in this manner:

I had to activate my virtual environment using the following command

source python2.7/bin/activate

Paritition array into N chunks with Numpy

Try numpy.array_split.

From the documentation:

>>> x = np.arange(8.0)
>>> np.array_split(x, 3)
    [array([ 0.,  1.,  2.]), array([ 3.,  4.,  5.]), array([ 6.,  7.])]

Identical to numpy.split, but won't raise an exception if the groups aren't equal length.

If number of chunks > len(array) you get blank arrays nested inside, to address that - if your split array is saved in a, then you can remove empty arrays by:

[x for x in a if x.size > 0]

Just save that back in a if you wish.

Function pointer as parameter

The correct way to do this is:

typedef void (*callback_function)(void); // type for conciseness

callback_function disconnectFunc; // variable to store function pointer type

void D::setDisconnectFunc(callback_function pFunc)
{
    disconnectFunc = pFunc; // store
}

void D::disconnected()
{
    disconnectFunc(); // call
    connected = false;
}

Horizontal list items

This fiddle shows how

http://jsfiddle.net/9th7X/

ul, li {
    display:inline
}

Great references on lists and css here:

http://alistapart.com/article/taminglists/

Close Bootstrap Modal

some times the solution up doesn't work so you d have properly to remove the in class and add the css display:none manually .

$("#modal").removeClass("in");
$("#modal").css("display","none");

how to add picasso library in android studio

Add this to your dependencies in build.gradle:

enter image description here

dependencies {
 implementation 'com.squareup.picasso:picasso:2.71828'
  ...

The latest version can be found here

Make sure you are connected to the Internet. When you sync Gradle, all related files will be added to your project

Take a look at your libraries folder, the library you just added should be in there.

enter image description here

How to set env variable in Jupyter notebook

A related (short-term) solution is to store your environment variables in a single file, with a predictable format, that can be sourced when starting a terminal and/or read into the notebook. For example, I have a file, .env, that has my environment variable definitions in the format VARIABLE_NAME=VARIABLE_VALUE (no blank lines or extra spaces). You can source this file in the .bashrc or .bash_profile files when beginning a new terminal session and you can read this into a notebook with something like,

import os
env_vars = !cat ../script/.env
for var in env_vars:
    key, value = var.split('=')
    os.environ[key] = value

I used a relative path to show that this .env file can live anywhere and be referenced relative to the directory containing the notebook file. This also has the advantage of not displaying the variable values within your code anywhere.

How do I make an http request using cookies on Android?

A cookie is just another HTTP header. You can always set it while making a HTTP call with the apache library or with HTTPUrlConnection. Either way you should be able to read and set HTTP cookies in this fashion.

You can read this article for more information.

I can share my peace of code to demonstrate how easy you can make it.

public static String getServerResponseByHttpGet(String url, String token) {

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(url);
            get.setHeader("Cookie", "PHPSESSID=" + token + ";");
            Log.d(TAG, "Try to open => " + url);

            HttpResponse httpResponse = client.execute(get);
            int connectionStatusCode = httpResponse.getStatusLine().getStatusCode();
            Log.d(TAG, "Connection code: " + connectionStatusCode + " for request: " + url);

            HttpEntity entity = httpResponse.getEntity();
            String serverResponse = EntityUtils.toString(entity);
            Log.d(TAG, "Server response for request " + url + " => " + serverResponse);

            if(!isStatusOk(connectionStatusCode))
                return null;

            return serverResponse;

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

I don't use the same version, but uninstall actions are the same: Looking for file uninstall-postgresql inside directory

/Library/PostgreSQL/9.6

enter image description here

then run it.

enter image description here

(Screenshot in macOS 10.13)

then

sudo rm -rf /Library/PostgreSQL/

to delete all unnecessary directory.

No internet on Android emulator - why and how to fix?

Try launching the Emulator from the command line as follows:

emulator -verbose -avd <AVD name>

This will give you detailed output and may show the error that's preventing the emulator from connecting to the Internet.

How to change webservice url endpoint?

To change the end address property edit your wsdl file

<wsdl:definitions.......
  <wsdl:service name="serviceMethodName">
    <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
      <soap:address location="http://service_end_point_adress"/>
    </wsdl:port>
  </wsdl:service>
</wsdl:definitions>

@RequestBody and @ResponseBody annotations in Spring

There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody javadocs, @ResponseBody javadocs

Usage examples would be something like this:

Using a JavaScript-library like JQuery, you would post a JSON-Object like this:

{ "firstName" : "Elmer", "lastName" : "Fudd" }

Your controller method would look like this:

// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
    return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}

// domain / value objects
public class UserStats{
    private String firstName;
    private String lastName;
    // + getters, setters
}
public class Description{
    private String description;
    // + getters, setters, constructor
}

Now if you have Jackson on your classpath (and have an <mvc:annotation-driven> setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody annotation). So the Browser / Client would see this JSON result:

{ "description" : "Elmer Fudd hates wacky wabbits" }

See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852

Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.


Update

Ever since Spring 4.x, you usually won't use @ResponseBody on method level, but rather @RestController on class level, with the same effect.

Here is a quote from the official Spring MVC documentation:

@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody to indicate a controller whose every method inherits the type-level @ResponseBody annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

How to use jQuery with Angular?

Using jQuery from Angular2 is a breeze compared to ng1. If you are using TypeScript you could first reference jQuery typescript definition.

tsd install jquery --save
or
typings install dt~jquery --global --save

TypescriptDefinitions are not required since you could just use any as the type for $ or jQuery

In your angular component you should reference a DOM element from the template using @ViewChild() After the view has been initialized you can use the nativeElement property of this object and pass to jQuery.

Declaring $ (or jQuery) as JQueryStatic will give you a typed reference to jQuery.

import {bootstrap}    from '@angular/platform-browser-dynamic';
import {Component, ViewChild, ElementRef, AfterViewInit} from '@angular/core';
declare var $:JQueryStatic;

@Component({
    selector: 'ng-chosen',
    template: `<select #selectElem>
        <option *ngFor="#item of items" [value]="item" [selected]="item === selectedValue">{{item}} option</option>
        </select>
        <h4> {{selectedValue}}</h4>`
})
export class NgChosenComponent implements AfterViewInit {
    @ViewChild('selectElem') el:ElementRef;
    items = ['First', 'Second', 'Third'];
    selectedValue = 'Second';

    ngAfterViewInit() {
        $(this.el.nativeElement)
            .chosen()
            .on('change', (e, args) => {
                this.selectedValue = args.selected;
            });
    }
}

bootstrap(NgChosenComponent);

This example is available on plunker: http://plnkr.co/edit/Nq9LnK?p=preview

tslint will complain about chosen not being a property on $, to fix this you can add a definition to the JQuery interface in your custom *.d.ts file

interface JQuery {
    chosen(options?:any):JQuery;
}    

R memory management / cannot allocate vector of size n Mb

I encountered a similar problem, and I used 2 flash drives as 'ReadyBoost'. The two drives gave additional 8GB boost of memory (for cache) and it solved the problem and also increased the speed of the system as a whole. To use Readyboost, right click on the drive, go to properties and select 'ReadyBoost' and select 'use this device' radio button and click apply or ok to configure.

Casting int to bool in C/C++

The following cites the C11 standard (final draft).

6.3.1.2: When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.

bool (mapped by stdbool.h to the internal name _Bool for C) itself is an unsigned integer type:

... The type _Bool and the unsigned integer types that correspond to the standard signed integer types are the standard unsigned integer types.

According to 6.2.5p2:

An object declared as type _Bool is large enough to store the values 0 and 1.

AFAIK these definitions are semantically identical to C++ - with the minor difference of the built-in(!) names. bool for C++ and _Bool for C.

Note that C does not use the term rvalues as C++ does. However, in C pointers are scalars, so assigning a pointer to a _Bool behaves as in C++.

Change default date time format on a single database in SQL Server

For SQL Server 2008 run:

EXEC sp_defaultlanguage 'username', 'british'

How to get the index of an element in an IEnumerable?

Stumbled across this today in a search for answers and I thought I'd add my version to the list (No pun intended). It utlises the null conditional operator of c#6.0

IEnumerable<Item> collection = GetTheCollection();

var index = collection
.Select((item,idx) => new { Item = item, Index = idx })
//or .FirstOrDefault(_ =>  _.Item.Prop == something)
.FirstOrDefault(_ => _.Item == itemToFind)?.Index ?? -1;

I've done some 'racing of the old horses' (testing) and for large collections (~100,000), worst case scenario that item you want is at the end, this is 2x faster than doing ToList().FindIndex(). If the Item you want is in the middle its ~4x faster.

For smaller collections (~10,000) it seems to be only marginally faster

Heres how I tested it https://gist.github.com/insulind/16310945247fcf13ba186a45734f254e

dropdownlist set selected value in MVC3 Razor

To have the IT department selected, when the departments are loaded from tblDepartment table, use the following overloaded constructor of SelectList class. Notice that we are passing a value of 1 for selectedValue parameter.

ViewBag.Departments = new SelectList(db.Departments, "Id", "Name", "1");

Remove all special characters, punctuation and spaces from string

After seeing this, I was interested in expanding on the provided answers by finding out which executes in the least amount of time, so I went through and checked some of the proposed answers with timeit against two of the example strings:

  • string1 = 'Special $#! characters spaces 888323'
  • string2 = 'how much for the maple syrup? $20.99? That s ricidulous!!!'

Example 1

'.join(e for e in string if e.isalnum())

  • string1 - Result: 10.7061979771
  • string2 - Result: 7.78372597694

Example 2

import re re.sub('[^A-Za-z0-9]+', '', string)

  • string1 - Result: 7.10785102844
  • string2 - Result: 4.12814903259

Example 3

import re re.sub('\W+','', string)

  • string1 - Result: 3.11899876595
  • string2 - Result: 2.78014397621

The above results are a product of the lowest returned result from an average of: repeat(3, 2000000)

Example 3 can be 3x faster than Example 1.

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

Public void ConfigureServices(IServiceCollection services)
{
    services.AddScoped<IEventRepository, EventRepository>();           
}

You forgot to add "services.AddScoped" in startup ConfigureServices method.

Can you create nested WITH clauses for Common Table Expressions?

Nested 'With' is not supported, but you can always use the second With as a subquery, for example:

WITH A AS (
                --WITH B AS ( SELECT COUNT(1) AS _CT FROM C ) SELECT CASE _CT WHEN 1 THEN 1 ELSE 0 END FROM B --doesn't work
                SELECT CASE WHEN count = 1 THEN 1 ELSE 0 END AS CT FROM (SELECT COUNT(1) AS count FROM dual)
                union all
                select 100 AS CT from dual
           )
              select CT FROM A

How to run a bash script from C++ program

Use the system function.

system("myfile.sh"); // myfile.sh should be chmod +x

How to install python modules without root access?

Install Python package without Admin rights

import sys

!{sys.executable} -m pip install package_name

Example

import sys

!{sys.executable} -m pip install kivy

Reference: https://docs.python.org/3.4/library/sys.html#sys.executable

Ruby: How to convert a string to boolean

In a rails 5.1 app, I use this core extension built on top of ActiveRecord::Type::Boolean. It is working perfectly for me when I deserialize boolean from JSON string.

https://api.rubyonrails.org/classes/ActiveModel/Type/Boolean.html

# app/lib/core_extensions/string.rb
module CoreExtensions
  module String
    def to_bool
      ActiveRecord::Type::Boolean.new.deserialize(downcase.strip)
    end
  end
end

initialize core extensions

# config/initializers/core_extensions.rb
String.include CoreExtensions::String

rspec

# spec/lib/core_extensions/string_spec.rb
describe CoreExtensions::String do
  describe "#to_bool" do
    %w[0 f F false FALSE False off OFF Off].each do |falsey_string|
      it "converts #{falsey_string} to false" do
        expect(falsey_string.to_bool).to eq(false)
      end
    end
  end
end

Write-back vs Write-Through caching?

The benefit of write-through to main memory is that it simplifies the design of the computer system. With write-through, the main memory always has an up-to-date copy of the line. So when a read is done, main memory can always reply with the requested data.

If write-back is used, sometimes the up-to-date data is in a processor cache, and sometimes it is in main memory. If the data is in a processor cache, then that processor must stop main memory from replying to the read request, because the main memory might have a stale copy of the data. This is more complicated than write-through.

Also, write-through can simplify the cache coherency protocol because it doesn't need the Modify state. The Modify state records that the cache must write back the cache line before it invalidates or evicts the line. In write-through a cache line can always be invalidated without writing back since memory already has an up-to-date copy of the line.

One more thing - on a write-back architecture software that writes to memory-mapped I/O registers must take extra steps to make sure that writes are immediately sent out of the cache. Otherwise writes are not visible outside the core until the line is read by another processor or the line is evicted.

Run local python script on remote server

ssh user@machine python < script.py - arg1 arg2

Because cat | is usually not necessary

How to completely remove node.js from Windows

The best thing to do is to remove Node.js from the control panel. Once deleted download the desired version of Node.js and install it and it works.

Count multiple columns with group by in one query

One solution is to wrap it in a subquery

SELECT *
FROM
(
    SELECT COUNT(column1),column1 FROM table GROUP BY column1
    UNION ALL
    SELECT COUNT(column2),column2 FROM table GROUP BY column2
    UNION ALL
    SELECT COUNT(column3),column3 FROM table GROUP BY column3
) s

Remove all special characters with RegExp

var desired = stringToReplace.replace(/[^\w\s]/gi, '')

As was mentioned in the comments it's easier to do this as a whitelist - replace the characters which aren't in your safelist.

The caret (^) character is the negation of the set [...], gi say global and case-insensitive (the latter is a bit redundant but I wanted to mention it) and the safelist in this example is digits, word characters, underscores (\w) and whitespace (\s).

With ng-bind-html-unsafe removed, how do I inject HTML?

Strict Contextual Escaping can be disabled entirely, allowing you to inject html using ng-html-bind. This is an unsafe option, but helpful when testing.

Example from the AngularJS documentation on $sce:

angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
  // Completely disable SCE.  For demonstration purposes only!
  // Do not use in new projects.
  $sceProvider.enabled(false);
});

Attaching the above config section to your app will allow you inject html into ng-html-bind, but as the doc remarks:

SCE gives you a lot of security benefits for little coding overhead. It will be much harder to take an SCE disabled application and either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE for cases where you have a lot of existing code that was written before SCE was introduced and you're migrating them a module at a time.

Foreign Key Django Model

You create the relationships the other way around; add foreign keys to the Person type to create a Many-to-One relationship:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        Anniversary, on_delete=models.CASCADE)
    address = models.ForeignKey(
        Address, on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

Any one person can only be connected to one address and one anniversary, but addresses and anniversaries can be referenced from multiple Person entries.

Anniversary and Address objects will be given a reverse, backwards relationship too; by default it'll be called person_set but you can configure a different name if you need to. See Following relationships "backward" in the queries documentation.

How to fix JSP compiler warning: one JAR was scanned for TLDs yet contained no TLDs?

For Tomcat 8, I had to add the following line to catalina.properties for preventing jars scanned by Tomcat:

tomcat.util.scan.StandardJarScanFilter.jarsToSkip=jsp-api.jar,servlet-api.jar

How to convert Integer to int?

Java converts Integer to int and back automatically (unless you are still with Java 1.4).

How should I choose an authentication library for CodeIgniter?

I've come across Flexi Auth (http://haseydesign.com/flexi-auth/). It looks very promising, and I've started using it. It has wonderfful features. Fully integrates with CI, and comes with two different library files, in which one is very heavy loaded with all the functions and the other one contains only the validations.

One of the best is that the newly registered member gets temporary access for a given amount of time on the site, until they click on the link from their email and activate.

Regular Expression Match to test for a valid year

you can go with sth like [^-]\d{4}$: you prevent the minus sign - to be before your 4 digits.
you can also use ^\d{4}$ with ^ to catch the beginning of the string. It depends on your scenario actually...

What is the "assert" function?

The assert computer statement is analogous to the statement make sure in English.

Pygame mouse clicking detection

The MOUSEBUTTONDOWN event occurs once when you click the mouse button and the MOUSEBUTTONUP event occurs once when the mouse button is released. The pygame.event.Event() object has two attributes that provide information about the mouse event. pos is a tuple that stores the position that was clicked. button stores the button that was clicked. Each mouse button is associated a value. For instance the value of the attributes is 1, 2, 3, 4, 5 for the left mouse button, middle mouse button, right mouse button, mouse wheel up respectively mouse wheel down. When multiple keys are pressed, multiple mouse button events occur. Further explanations can be found in the documentation of the module pygame.event.

Use the rect attribute of the pygame.sprite.Sprite object and the collidepoint method to see if the Sprite was clicked. Pass the list of events to the update method of the pygame.sprite.Group so that you can process the events in the Sprite class:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseClick

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.click_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.click_image, color, (25, 25), 25)
        pygame.draw.circle(self.click_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.clicked = False

    def update(self, event_list):
        for event in event_list:
            if event.type == pygame.MOUSEBUTTONDOWN:
                if self.rect.collidepoint(event.pos):
                    self.clicked = not self.clicked

        self.image = self.click_image if self.clicked else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    event_list = pygame.event.get()
    for event in event_list:
        if event.type == pygame.QUIT:
            run = False 

    group.update(event_list)

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

See further Creating multiple sprites with different update()'s from the same sprite class in Pygame


The current position of the mouse can be determined via pygame.mouse.get_pos(). The return value is a tuple that represents the x and y coordinates of the mouse cursor. pygame.mouse.get_pressed() returns a list of Boolean values ??that represent the state (True or False) of all mouse buttons. The state of a button is True as long as a button is held down. When multiple buttons are pressed, multiple items in the list are True. The 1st, 2nd and 3rd elements in the list represent the left, middle and right mouse buttons.

Detect evaluate the mouse states in the Update method of the pygame.sprite.Sprite object:

class SpriteObject(pygame.sprite.Sprite):
    # [...]

    def update(self, event_list):

        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        if  self.rect.collidepoint(mouse_pos) and any(mouse_buttons):
            # [...]

my_sprite = SpriteObject()
group = pygame.sprite.Group(my_sprite)

# [...]

run = True
while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    group.update(event_list)

    # [...]

Minimal example: repl.it/@Rabbid76/PyGame-MouseHover

import pygame

class SpriteObject(pygame.sprite.Sprite):
    def __init__(self, x, y, color):
        super().__init__() 
        self.original_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.original_image, color, (25, 25), 25)
        self.hover_image = pygame.Surface((50, 50), pygame.SRCALPHA)
        pygame.draw.circle(self.hover_image, color, (25, 25), 25)
        pygame.draw.circle(self.hover_image, (255, 255, 255), (25, 25), 25, 4)
        self.image = self.original_image 
        self.rect = self.image.get_rect(center = (x, y))
        self.hover = False

    def update(self):
        mouse_pos = pygame.mouse.get_pos()
        mouse_buttons = pygame.mouse.get_pressed()

        #self.hover = self.rect.collidepoint(mouse_pos)
        self.hover = self.rect.collidepoint(mouse_pos) and any(mouse_buttons)

        self.image = self.hover_image if self.hover else self.original_image

pygame.init()
window = pygame.display.set_mode((300, 300))
clock = pygame.time.Clock()

sprite_object = SpriteObject(*window.get_rect().center, (128, 128, 0))
group = pygame.sprite.Group([
    SpriteObject(window.get_width() // 3, window.get_height() // 3, (128, 0, 0)),
    SpriteObject(window.get_width() * 2 // 3, window.get_height() // 3, (0, 128, 0)),
    SpriteObject(window.get_width() // 3, window.get_height() * 2 // 3, (0, 0, 128)),
    SpriteObject(window.get_width() * 2// 3, window.get_height() * 2 // 3, (128, 128, 0)),
])

run = True
while run:
    clock.tick(60)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False 

    group.update()

    window.fill(0)
    group.draw(window)
    pygame.display.flip()

pygame.quit()
exit()

Java - Search for files in a directory

I have used a different approach to search for a file using stack.. keeping in mind that there could be folders inside a folder. Though its not faster than windows search(and I was not expecting that though) but it definitely gives out correct result. Please modify the code as you wish to. This code was originally made to extract the file path of certain file extension :). Feel free to optimize.

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Deepankar Sinha
 */
public class GetList {
    public List<String> stack;
    static List<String> lnkFile;
    static List<String> progName;

    int index=-1;
    public static void main(String args[]) throws IOException
    {

        //var-- progFile:Location of the file to be search. 
        String progFile="C:\\";
        GetList obj=new GetList();
        String temp=progFile;
        int i;
        while(!"&%@#".equals(temp))
        {
            File dir=new File(temp);
            String[] directory=dir.list();
            if(directory!=null){
            for(String name: directory)
            {
                if(new File(temp+name).isDirectory())
                    obj.push(temp+name+"\\");
                else
                    if(new File(temp+name).isFile())
                    {
                        try{
                            //".exe can be replaced with file name to be searched. Just exclude name.substring()... you know what to do.:)
                        if(".exe".equals(name.substring(name.lastIndexOf('.'), name.length())))
                        {
                            //obj.addFile(temp+name,name);
                            System.out.println(temp+name);
                        }
                        }catch(StringIndexOutOfBoundsException e)
                        {
                            //debug purpose
                            System.out.println("ERROR******"+temp+name);
                        }

                    }
            }}
            temp=obj.pop();
        }
        obj.display();

//        for(int i=0;i<directory.length;i++)
//        System.out.println(directory[i]);
    }

    public GetList() {
        this.stack = new ArrayList<>();
        this.lnkFile=new ArrayList<>();
        this.progName=new ArrayList<>();
    }
    public void push(String dir)
    {
        index++;
        //System.out.println("PUSH : "+dir+" "+index);
        this.stack.add(index,dir);

    }
    public String pop()
    {
        String dir="";
        if(index==-1)
            return "&%@#";
        else
        {
            dir=this.stack.get(index);
            //System.out.println("POP : "+dir+" "+index);
            index--;

        }
        return dir;
    }

    public void addFile(String name,String name2)
    {
        lnkFile.add(name);
        progName.add(name2);
    }

    public void display()
    {
        GetList.lnkFile.stream().forEach((lnkFile1) -> {
            System.out.println(lnkFile1);
        });
    }

}

Choose newline character in Notepad++

on windows 10, Notepad 7.8.5, i found this solution to convert from CRLF to LF.
Edit > Format end of line
and choose either Windows(CR+LF) or Unix(LF)

connecting to MySQL from the command line

This worked for me ::-

mysql --host=hostNameorIp --user=username --password=password  

or

mysql --host=hostNameorIp --user=username --password=password database_name

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

I'm using Phonegap, but this thread keeps coming as the first one when Googling about the error message.

For me this issue went away by defining the imagetype to PNG.

encodingType : Camera.EncodingType.PNG

So the whole line being:

 navigator.camera.getPicture(successFunction, failFunction, { encodingType : Camera.EncodingType.PNG, correctOrientation:true, sourceType : Camera.PictureSourceType    .PHOTOLIBRARY, quality: 70, allowEdit : false , destinationType: Camera.DestinationType.DATA_URL});

Your mileage may vary, but that did the trick for me.

How do I store data in local storage using Angularjs?

Use ngStorage For All Your AngularJS Local Storage Needs. Please note that this is NOT a native part of the Angular JS framework.

ngStorage contains two services, $localStorage and $sessionStorage

angular.module('app', [
   'ngStorage'
]).controller('Ctrl', function(
    $scope,
    $localStorage,
    $sessionStorage
){});

Check the Demo

How can I wrap or break long text/word in a fixed width span?

You can use the CSS property word-wrap:break-word;, which will break words if they are too long for your span width.

_x000D_
_x000D_
span { _x000D_
    display:block;_x000D_
    width:150px;_x000D_
    word-wrap:break-word;_x000D_
}
_x000D_
<span>VeryLongLongLongLongLongLongLongLongLongLongLongLongExample</span>
_x000D_
_x000D_
_x000D_

How to execute mongo commands through shell scripts?

Create a script file; write commands:

#!/bin/sh
mongo < file.js

In file.js write your mongo query:

db.collection.find({"myValue":null}).count();

How to localise a string inside the iOS info.plist file?

I would highly recommend reading Apple's guides, and viewing the WWDC resources listed here: Internationalization and Localization Topics

To specifically answer your question, when you add a new language to your projectenter image description here, you get an opportunity to choose what InfoPlist files to include (if you have multiple targets, you'll have multiple Info plist files). All you need to do to get the following screen is hit the + under Localizations and choose a new language to add support for. enter image description here

Once you've added, it will create the necessary string files in the appropriate lproj directories for the given language.

--EDIT--

Just to be clear, iOS will swap out the string for your Plist file based upon the user's currently selected language using the plist entry's key as the key in the localized strings file.

What values can I pass to the event attribute of the f:ajax tag?

I just input some value that I knew was invalid and here is the output:

'whatToInput' is not a supported event for HtmlPanelGrid. Please specify one of these supported event names: click, dblclick, keydown, keypress, keyup, mousedown, mousemove, mouseout, mouseover, mouseup.

So values you can pass to event are

  • click
  • dblclick
  • keydown
  • mousedown
  • mousemove
  • mouseover
  • mouseup

INNER JOIN in UPDATE sql for DB2

for you ask

update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%'

if join give multiple result you can force update like this

update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
fetch first rows only
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%' 

template methode

update table1 f1
set (f1.field1, f1.field2, f1.field3, f1.field4)=
(
select f2.field1, f2.field2, f2.field3, 'CONSTVALUE'
from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2) 
)
where exists 
(
select * from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2)
) 

How should a model be structured in MVC?

Everything that is business logic belongs in a model, whether it is a database query, calculations, a REST call, etc.

You can have the data access in the model itself, the MVC pattern doesn't restrict you from doing that. You can sugar coat it with services, mappers and what not, but the actual definition of a model is a layer that handles business logic, nothing more, nothing less. It can be a class, a function, or a complete module with a gazillion objects if that's what you want.

It's always easier to have a separate object that actually executes the database queries instead of having them being executed in the model directly: this will especially come in handy when unit testing (because of the easiness of injecting a mock database dependency in your model):

class Database {
   protected $_conn;

   public function __construct($connection) {
       $this->_conn = $connection;
   }

   public function ExecuteObject($sql, $data) {
       // stuff
   }
}

abstract class Model {
   protected $_db;

   public function __construct(Database $db) {
       $this->_db = $db;
   }
}

class User extends Model {
   public function CheckUsername($username) {
       // ...
       $sql = "SELECT Username FROM" . $this->usersTableName . " WHERE ...";
       return $this->_db->ExecuteObject($sql, $data);
   }
}

$db = new Database($conn);
$model = new User($db);
$model->CheckUsername('foo');

Also, in PHP, you rarely need to catch/rethrow exceptions because the backtrace is preserved, especially in a case like your example. Just let the exception be thrown and catch it in the controller instead.

How to round the minute of a datetime object

Based on Stijn Nevens and modified for Django use to round current time to the nearest 15 minute.

from datetime import date, timedelta, datetime, time

    def roundTime(dt=None, dateDelta=timedelta(minutes=1)):

        roundTo = dateDelta.total_seconds()

        if dt == None : dt = datetime.now()
        seconds = (dt - dt.min).seconds
        # // is a floor division, not a comment on following line:
        rounding = (seconds+roundTo/2) // roundTo * roundTo
        return dt + timedelta(0,rounding-seconds,-dt.microsecond)

    dt = roundTime(datetime.now(),timedelta(minutes=15)).strftime('%H:%M:%S')

 dt = 11:45:00

if you need full date and time just remove the .strftime('%H:%M:%S')

Use virtualenv with Python with Visual Studio Code in Ubuntu

On Mac OS X using Visual Studio Code version 1.34.0 (1.34.0) I had to do the following to get Visual Studio Code to recognise the virtual environments:

Location of my virtual environment (named ml_venv):

/Users/auser/.pyvenv/ml_venv

auser@HOST:~/.pyvenv$ tree -d -L 2
.
+-- ml_venv
    +-- bin
    +-- include
    +-- lib

I added the following entry in Settings.json: "python.venvPath": "/Users/auser/.pyvenv"

I restarted the IDE, and now I could see the interpreter from my virtual environment:

Enter image description here

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

make iframe height dynamic based on content inside- JQUERY/Javascript

A slightly improved answer to Aristos...

<script type="text/javascript">
  function resizeIframe(iframe) {
    iframe.height = iframe.contentWindow.document.body.scrollHeight + "px";
  }
</script>  

Then declare in your iframe as follows:

<iframe onload="resizeIframe(this)" ...

There are two minor improvements:

  1. You don't need to get the element via document.getElementById - as you already have it in the onload callback.
  2. There's no need to set the iframe.height = "" if you're going to reassign it in the very next statement. Doing so actually incurs an overhead as you're dealing with a DOM element.

Edit: If the content in the frame is always changing then call:

parent.resizeIframe(this.frameElement); 

from within the iframe after the update. Works for same origin.

Or to auto detect:

  // on resize
  this.container = this.frameElement.contentWindow.document.body;

  this.watch = () => {
    cancelAnimationFrame(this.watcher);

    if (this.lastScrollHeight !== container.scrollHeight) {
      parent.resizeIframeToContentSize(this.frameElement);  
    }
    this.lastScrollHeight = container.scrollHeight;
    this.watcher = requestAnimationFrame(this.watch);
  };
  this.watcher = window.requestAnimationFrame(this.watch);

How to concatenate two strings in SQL Server 2005

so if you have a table with a row like:

firstname lastname
Bill      smith

you can do something like

select firstname + ' ' + lastname from thetable

and you will get "Bill Smith"

Automated Python to Java translation

Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc

In fact, this is probably pretty easy to knock up in Python.

I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.

Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.

How to prevent a jQuery Ajax request from caching in Internet Explorer?

If you set unique parameters, then the cache does not work, for example:

$.ajax({
    url : "my_url",
    data : {
        'uniq_param' : (new Date()).getTime(),
        //other data
    }});

cURL POST command line on WINDOWS RESTful service

Alternative solution: A More Userfriendly solution than command line:

If you are looking for a user friendly way to send and request data using HTTP Methods other than simple GET's probably you are looking for a chrome extention just like this one http://goo.gl/rVW22f called AVANCED REST CLIENT

For guys looking to stay with command-line i recommend cygwin:

I ended up installing cygwin with CURL which allow us to Get that Linux feeling - on Windows!

Using Cygwin command line this issues have stopped and most important, the request syntax used on 1. worked fine.

Useful links:

Where i was downloading the curl for windows command line?

For more information on how to install and get curl working with cygwin just go here

I hope it helps someone because i spent all morning on this.

Eclipse "cannot find the tag library descriptor" for custom tags (not JSTL!)

I had the same problem with MyEclipse and Eclipse 6.6.0. It red lined the uri value in every

<%@ taglib prefix="s" uri="/struts-tags"%>. I fixed it by going to 'Project/MyEclipse/Web/Tag Libraries' and setting the Default TLD Prefix for Struts 1.2 Tiles Tags to 's'. I also had to do the same under 'Project/MyEclipse/Web/Configure workspace settings.../Tag Libraries'.

Taking pictures with camera on Android programmatically

You can use Magical Take Photo library.

1. try with compile in gradle

compile 'com.frosquivel:magicaltakephoto:1.0'

2. You need this permission in your manifest.xml

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA"/>

3. instance the class like this

// "this" is the current activity param

MagicalTakePhoto magicalTakePhoto =  new MagicalTakePhoto(this,ANY_INTEGER_0_TO_4000_FOR_QUALITY);

4. if you need to take picture use the method

magicalTakePhoto.takePhoto("my_photo_name");

5. if you need to select picture in device, try with the method:

magicalTakePhoto.selectedPicture("my_header_name");

6. You need to override the method onActivityResult of the activity or fragment like this:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     magicalTakePhoto.resultPhoto(requestCode, resultCode, data);

     // example to get photo
     // imageView.setImageBitmap(magicalTakePhoto.getMyPhoto());
}

Note: Only with this Library you can take and select picture in the device, this use a min API 15.

Programmatically set image to UIImageView with Xcode 6.1/Swift

This code is in the wrong place:

var image : UIImage = UIImage(named:"afternoon")!
bgImage = UIImageView(image: image)
bgImage.frame = CGRect(x: 0, y: 0, width: 100, height: 200)
view.addSubview(bgImage)

You must place it inside a function. I recommend moving it inside the viewDidLoad function.

In general, the only code you can add within the class that's not inside of a function are variable declarations like:

@IBOutlet weak var bgImage: UIImageView!

What is MATLAB good for? Why is it so used by universities? When is it better than Python?

The main reason it is useful in industry is the plug-ins built on top of the core functionality. Almost all active Matlab development for the last few years has focused on these.

Unfortunately, you won't have much opportunity to use these in an academic environment.

How to navigate to to different directories in the terminal (mac)?

To check that the file you're trying to open actually exists, you can change directories in terminal using cd. To change to ~/Desktop/sass/css: cd ~/Desktop/sass/css. To see what files are in the directory: ls.

If you want information about either of those commands, use the man page: man cd or man ls, for example.

Google for "basic unix command line commands" or similar; that will give you numerous examples of moving around, viewing files, etc in the command line.

On Mac OS X, you can also use open to open a finder window: open . will open the current directory in finder. (open ~/Desktop/sass/css will open the ~/Desktop/sass/css).

Get the short Git version hash

You can do just about any format you want with --pretty=format:

git log -1 --pretty=format:%h 

How to display length of filtered ng-repeat data

For completeness, in addition to previous answers (perform calculation of visible people inside controller) you can also perform that calculations in your HTML template as in the example below.

Assuming your list of people is in data variable and you filter people using query model, the following code will work for you:

<p>Number of visible people: {{(data|filter:query).length}}</p>
<p>Total number of people: {{data.length}}</p>
  • {{data.length}} - prints total number of people
  • {{(data|filter:query).length}} - prints filtered number of people

Note that this solution works fine if you want to use filtered data only once in a page. However, if you use filtered data more than once e.g. to present items and to show length of filtered list, I would suggest using alias expression (described below) for AngularJS 1.3+ or the solution proposed by @Wumms for AngularJS version prior to 1.3.

New Feature in Angular 1.3

AngularJS creators also noticed that problem and in version 1.3 (beta 17) they added "alias" expression which will store the intermediate results of the repeater after the filters have been applied e.g.

<div ng-repeat="person in data | filter:query as results">
    <!-- template ... -->
</div>

<p>Number of visible people: {{results.length}}</p>

The alias expression will prevent multiple filter execution issue.

I hope that will help.

"No backupset selected to be restored" SQL Server 2012

I had the same issue with SQL Server 2014 (Management Studio could not see the folder in which the backup file resided, when attempting to locate it for a Restore operation). This thread held the answer that solved my problem. Quote:

The SQL Server service account can be found by Start->Control Panel->Administrative Tools->Services. Double-click on the SQL Server service->Log On tab. You'll either be using the "Local System account" or "This account" to define a specific account. If you are using the Local System account, you won't be able to reference backups that are not local to the server. If, instead, you have defined the account to use, this is the account that needs to have access to the backup file location. Your ability to access the backups using your personal logon is irrelevant; it is the SQL Server account that is used, even though you are initiating the backup. Your IT people should be able to determine what rights are granted to each account.

Hope that helps someone.

Asp.net - Add blank item at top of dropdownlist

I think a better way is to insert the blank item first, then bind the data just as you have been doing. However you need to set the AppendDataBoundItems property of the list control.

We use the following method to bind any data source to any list control...

public static void BindList(ListControl list, IEnumerable datasource, string valueName, string textName)
{
    list.Items.Clear();
    list.Items.Add("", "");
    list.AppendDataBoundItems = true;
    list.DataValueField = valueName;
    list.DataTextField = textName;
    list.DataSource = datasource;
    list.DataBind();
}

Apache Cordova - uninstall globally

Try this for Windows:

    npm uninstall -g cordova

Try this for MAC:

    sudo npm uninstall -g cordova

You can also add Cordova like this:

  1. If You Want To install the previous version of Cordova through the Node Package Manager (npm):

    npm install -g [email protected]
    
  2. If You Want To install the latest version of Cordova:

    npm install -g cordova 
    

Enjoy!

How to solve privileges issues when restore PostgreSQL Database

Try using the -L flag with pg_restore by specifying the file taken from pg_dump -Fc

-L list-file --use-list=list-file

Restore only those archive elements that are listed in list-file, and restore them in the order they appear in the file. Note that if filtering switches such as -n or -t are used with -L, they will further restrict the items restored.

list-file is normally created by editing the output of a previous -l operation. Lines can be moved or removed, and can also be commented out by placing a semicolon (;) at the start of the line. See below for examples.

https://www.postgresql.org/docs/9.5/app-pgrestore.html

pg_dump -Fc -f pg.dump db_name
pg_restore -l pg.dump | grep -v 'COMMENT - EXTENSION' > pg_restore.list
pg_restore -L pg_restore.list pg.dump

Here you can see the Inverse is true by outputting only the comment:

pg_dump -Fc -f pg.dump db_name
pg_restore -l pg.dump | grep 'COMMENT - EXTENSION' > pg_restore_inverse.list
pg_restore -L pg_restore_inverse.list pg.dump
--
-- PostgreSQL database dump
--

-- Dumped from database version 9.4.15
-- Dumped by pg_dump version 9.5.14

SET statement_timeout = 0;
SET lock_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET client_min_messages = warning;
SET row_security = off;

--
-- Name: EXTENSION plpgsql; Type: COMMENT; Schema: -; Owner: 
--

COMMENT ON EXTENSION plpgsql IS 'PL/pgSQL procedural language';


--
-- PostgreSQL database dump complete
--

Insert line break inside placeholder attribute of a textarea?

This issue can be tackled by using the placeholder-shown selector and super imposed backgrounds, if your implementation allows:

textarea:not(:placeholder-shown) {
  background: #fff;
}

div {
  top: 0;
  left: 14px;
  color: rgba(0,0,0,0.4);
  z-index: -1;
  position: absolute;
  line-height: 1.2;
  white-space: pre-wrap;
}

https://codepen.io/franciscoaquino/pen/YzyBPYK

Selector support:

https://caniuse.com/#feat=css-placeholder-shown

Convert 4 bytes to int

try something like this:

a = buffer[3];
a = a*256 + buffer[2];
a = a*256 + buffer[1];
a = a*256 + buffer[0];

this is assuming that the lowest byte comes first. if the highest byte comes first you might have to swap the indices (go from 0 to 3).

basically for each byte you want to add, you first multiply a by 256 (which equals a shift to the left by 8 bits) and then add the new byte.

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

Regular expression replace in C#

Try this::

sb_trim = Regex.Replace(stw, @"(\D+)\s+\$([\d,]+)\.\d+\s+(.)",
    m => string.Format(
        "{0},{1},{2}",
        m.Groups[1].Value,
        m.Groups[2].Value.Replace(",", string.Empty),
        m.Groups[3].Value));

This is about as clean an answer as you'll get, at least with regexes.

  • (\D+): First capture group. One or more non-digit characters.
  • \s+\$: One or more spacing characters, then a literal dollar sign ($).
  • ([\d,]+): Second capture group. One or more digits and/or commas.
  • \.\d+: Decimal point, then at least one digit.
  • \s+: One or more spacing characters.
  • (.): Third capture group. Any non-line-breaking character.

The second capture group additionally needs to have its commas stripped. You could do this with another regex, but it's really unnecessary and bad for performance. This is why we need to use a lambda expression and string format to piece together the replacement. If it weren't for that, we could just use this as the replacement, in place of the lambda expression:

"$1,$2,$3"

How to get the last value of an ArrayList

A one liner that takes into account empty lists would be:

T lastItem = list.size() == 0 ? null : list.get(list.size() - 1);

Or if you don't like null values (and performance isn't an issue):

Optional<T> lastItem = list.stream().reduce((first, second) -> second);

How can I loop over entries in JSON?

Try this :

import urllib, urllib2, json
url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
request = urllib2.Request(url)
request.add_header('User-Agent','Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)')
request.add_header('Content-Type','application/json')
response = urllib2.urlopen(request)
json_object = json.load(response)
#print json_object['results']
if json_object['team'] == []:
    print 'No Data!'
else:
    for rows in json_object['team']:
        print 'Team ID:' + rows['team_id']
        print 'Team Name:' + rows['team_name']
        print 'Team URL:' + rows['team_icon_url']

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());

jQuery issue in Internet Explorer 8

I was fixing a template created by somebody else who forgot to include the doctype.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

If you don't declare the doctype IE8 does strange things in Quirks mode.

How to allow <input type="file"> to accept only image files?

Steps:
1. Add accept attribute to input tag
2. Validate with javascript
3. Add server side validation to verify if the content is really an expected file type

For HTML and javascript:

<html>
<body>
<input name="image" type="file" id="fileName" accept=".jpg,.jpeg,.png" onchange="validateFileType()"/>
<script type="text/javascript">
    function validateFileType(){
        var fileName = document.getElementById("fileName").value;
        var idxDot = fileName.lastIndexOf(".") + 1;
        var extFile = fileName.substr(idxDot, fileName.length).toLowerCase();
        if (extFile=="jpg" || extFile=="jpeg" || extFile=="png"){
            //TO DO
        }else{
            alert("Only jpg/jpeg and png files are allowed!");
        }   
    }
</script>
</body>
</html>

Explanation:

  1. The accept attribute filters the files that will be displayed in the file chooser popup. However, it is not a validation. It is only a hint to the browser. The user can still change the options in the popup.
  2. The javascript only validates for file extension, but cannot really verify if the select file is an actual jpg or png.
  3. So you have to write for file content validation on server side.

Encrypt and decrypt a password in Java

EDIT : this answer is old. Usage of MD5 is now discouraged as it can easily be broken.


MD5 must be good enough for you I imagine? You can achieve it with MessageDigest.

MessageDigest.getInstance("MD5");

There are also other algorithms listed here.

And here's an third party version of it, if you really want: Fast MD5

Increase distance between text and title on the y-axis

Based on this forum post: https://groups.google.com/forum/#!topic/ggplot2/mK9DR3dKIBU

Sounds like the easiest thing to do is to add a line break (\n) before your x axis, and after your y axis labels. Seems a lot easier (although dumber) than the solutions posted above.

ggplot(mpg, aes(cty, hwy)) + 
    geom_point() + 
    xlab("\nYour_x_Label") + ylab("Your_y_Label\n")

Hope that helps!

Declaring variable workbook / Worksheet vba

If the worksheet you want to retrieve exists at compile-time in ThisWorkbook (i.e. the workbook that contains the VBA code you're looking at), then the simplest and most consistently reliable way to refer to that Worksheet object is to use its code name:

Debug.Print Sheet1.Range("A1").Value

You can set the code name to anything you need (as long as it's a valid VBA identifier), independently of its "tab name" (which the user can modify at any time), by changing the (Name) property in the Properties toolwindow (F4):

Sheet1 properties

The Name property refers to the "tab name" that the user can change on a whim; the (Name) property refers to the code name of the worksheet, and the user can't change it without accessing the Visual Basic Editor.

VBA uses this code name to automatically declare a global-scope Worksheet object variable that your code gets to use anywhere to refer to that sheet, for free.

In other words, if the sheet exists in ThisWorkbook at compile-time, there's never a need to declare a variable for it - the variable is already there!


If the worksheet is created at run-time (inside ThisWorkbook or not), then you need to declare & assign a Worksheet variable for it.

Use the Worksheets property of a Workbook object to retrieve it:

Dim wb As Workbook
Set wb = Application.Workbooks.Open(path)

Dim ws As Worksheet
Set ws = wb.Worksheets(nameOrIndex)

Important notes...

  • Both the name and index of a worksheet can easily be modified by the user (accidentally or not), unless workbook structure is protected. If workbook isn't protected, you simply cannot assume that the name or index alone will give you the specific worksheet you're after - it's always a good idea to validate the format of the sheet (e.g. verify that cell A1 contains some specific text, or that there's a table with a specific name, that contains some specific column headings).

  • Using the Sheets collection contains Worksheet objects, but can also contain Chart instances, and a half-dozen more legacy sheet types that are not worksheets. Assigning a Worksheet reference from whatever Sheets(nameOrIndex) returns, risks throwing a type mismatch run-time error for that reason.

  • Not qualifying the Worksheets collection is an implicit ActiveWorkbook reference - meaning the Worksheets collection is pulling from whatever workbook is active at the moment the instruction is executing. Such implicit references make the code frail and bug-prone, especially if the user can navigate and interact with the Excel UI while code is running.

  • Unless you mean to activate a specific sheet, you never need to call ws.Activate in order to do 99% of what you want to do with a worksheet. Just use your ws variable instead.

List<Object> and List<?>

Why cant I do this:

List<Object> object = new List<Object>();

You can't do this because List is an interface, and interfaces cannot be instantiated. Only (concrete) classes can be. Examples of concrete classes implementing List include ArrayList, LinkedList etc.

Here is how one would create an instance of ArrayList:

List<Object> object = new ArrayList<Object>();

I have a method that returns a List<?>, how would I turn that into a List<Object>

Show us the relevant code and I'll update the answer.

Proper way to initialize a C# dictionary with values?

Suppose we have a dictionary like this

Dictionary<int,string> dict = new Dictionary<int, string>();
dict.Add(1, "Mohan");
dict.Add(2, "Kishor");
dict.Add(3, "Pankaj");
dict.Add(4, "Jeetu");

We can initialize it as follow.

Dictionary<int, string> dict = new Dictionary<int, string>  
{
    { 1, "Mohan" },
    { 2, "Kishor" },
    { 3, "Pankaj" },
    { 4, "Jeetu" }
};

OpenCV TypeError: Expected cv::UMat for argument 'src' - What is this?

Is canny your own function? Do you use Canny from OpenCV inside it? If yes check if you feed suitable argument for Canny - first Canny argument should meet following criteria:

  • type: <type 'numpy.ndarray'>
  • dtype: dtype('uint8')
  • being single channel or simplyfing: grayscale, that is 2D array, i.e. its shape should be 2-tuple of ints (tuple containing exactly 2 integers)

You can check it by printing respectively

type(variable_name)
variable_name.dtype
variable_name.shape

Replace variable_name with name of variable you feed as first argument to Canny.

jquery drop down menu closing by clicking outside

how to have a click event outside of the dropdown menu so that it close the dropdown menu ? Heres the code

$(document).click(function (e) {
    e.stopPropagation();
    var container = $(".dropDown");

    //check if the clicked area is dropDown or not
    if (container.has(e.target).length === 0) {
        $('.subMenu').hide();
    }
})

Can't resolve module (not found) in React.js

Deleted the package-lock.json file & then ran

npm install

Read further

New lines inside paragraph in README.md

Interpreting newlines as <br /> used to be a feature of Github-flavored markdown, but the most recent help document no longer lists this feature.

Fortunately, you can do it manually. The easiest way is to ensure that each line ends with two spaces. So, change

a
b
c

into

a__
b__
c

(where _ is a blank space).

Or, you can add explicit <br /> tags.

a <br />
b <br />
c

Using :: in C++

The :: is called scope resolution operator. Can be used like this:

:: identifier
class-name :: identifier
namespace :: identifier

You can read about it here
https://docs.microsoft.com/en-us/cpp/cpp/scope-resolution-operator?view=vs-2017

How to restrict SSH users to a predefined set of commands after login?

You should acquire `rssh', the restricted shell

You can follow the restriction guides mentioned above, they're all rather self-explanatory, and simple to follow. Understand the terms `chroot jail', and how to effectively implement sshd/terminal configurations, and so on.

Being as most of your users access your terminals via sshd, you should also probably look into sshd_conifg, the SSH daemon configuration file, to apply certain restrictions via SSH. Be careful, however. Understand properly what you try to implement, for the ramifications of incorrect configurations are probably rather dire.

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

Unfortunately, the old xkcd comic isn't completely up to date anymore.

https://imgs.xkcd.com/comics/python.png

Since Python 3.0 you have to write:

print("Hello, World!")

And someone has still to write that antigravity library :(

MVC Calling a view from a different controller

It is explained pretty well here: Display a view from another controller in ASP.NET MVC

To quote @Womp:
By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\, but after that, if it doesn't find the view, it checks in \Views\Shared.

ASP MVC's idea is "convention over configuration" which means moving the view to the shared folder is the way to go in such cases.

How can I regenerate ios folder in React Native project?

  1. Open Terminal/cmd
  2. Move to the folder/directory where the project "ProjectName" folder exist(Do not go into project directory)
  3. run command as: react-native init "ProjectName" and it will warn that project directory already exist but you continue.
  4. It will install all updated node modules as well as missing platform (android/ios) folders inside project without disturbing the code already written.
  5. cd "ProjectName" and then cd ios and then run pod install

PS: Take backup of your code in case it changes App.js

CreateProcess error=2, The system cannot find the file specified

Assuming that winrar.exe is in the PATH, then Runtime.exec is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe is installed in C:/Program Files/WinRAR you would need to use something like...

p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");

Personally, I would recommend that you use ProcessBuilder as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String elements, it deals with things like spaces much better then a single String variable, for example...

ProcessBuilder pb = new ProcessBuilder(
    "C:/Program Files/WinRAR/winrar",
    "x",
    "myjar.jar",
    "*.*",
    "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

Don't forget to read the contents of the InputStream from the process, as failing to do so may stall the process

How to get first element in a list of tuples?

Those are tuples, not sets. You can do this:

l1 = [(1, u'abc'), (2, u'def')]
l2 = [(tup[0],) for tup in l1]
l2
>>> [(1,), (2,)]

setImmediate vs. nextTick

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

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

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

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

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

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

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

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

The output of the above code would be:

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

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

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

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

The output of the above code ends up being:

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

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

Hope that helps!

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

Best way to get whole number part of a Decimal number

By the way guys, (int)Decimal.MaxValue will overflow. You can't get the "int" part of a decimal because the decimal is too friggen big to put in the int box. Just checked... its even too big for a long (Int64).

If you want the bit of a Decimal value to the LEFT of the dot, you need to do this:

Math.Truncate(number)

and return the value as... A DECIMAL or a DOUBLE.

edit: Truncate is definitely the correct function!

fork: retry: Resource temporarily unavailable

This is commonly caused by running out of file descriptors.

There is the systems total file descriptor limit, what do you get from the command:

sysctl fs.file-nr

This returns counts of file descriptors:

<in_use> <unused_but_allocated> <maximum>

To find out what a users file descriptor limit is run the commands:

sudo su - <username>
ulimit -Hn

To find out how many file descriptors are in use by a user run the command:

sudo lsof -u <username> 2>/dev/null | wc -l

So now if you are having a system file descriptor limit issue you will need to edit your /etc/sysctl.conf file and add, or modify it it already exists, a line with fs.file-max and set it to a value large enough to deal with the number of file descriptors you need and reboot.

fs.file-max = 204708

Kubernetes pod gets recreated when deleted

I experienced a similar problem: after deleting the deployment (kubectl delete deploy <name>), the pods kept "Running" and where automatically re-created after deletion (kubectl delete po <name>).

It turned out that the associated replica set was not deleted automatically for some reason, and after deleting that (kubectl delete rs <name>), it was possible to delete the pods.

Get list from pandas dataframe column or row?

Example conversion:

Numpy Array -> Panda Data Frame -> List from one Panda Column

Numpy Array

data = np.array([[10,20,30], [20,30,60], [30,60,90]])

Convert numpy array into Panda data frame

dataPd = pd.DataFrame(data = data)
    
print(dataPd)
0   1   2
0  10  20  30
1  20  30  60
2  30  60  90

Convert one Panda column to list

pdToList = list(dataPd['2'])

GROUP BY and COUNT in PostgreSQL

Using OVER() and LIMIT 1:

SELECT COUNT(1) OVER()
FROM posts 
   INNER JOIN votes ON votes.post_id = posts.id 
GROUP BY posts.id
LIMIT 1;

pip or pip3 to install packages for Python 3?

In my system, I use the update alternatives.

sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip2 2

If I want to switch between them I use the following command.

sudo update-alternatives --config pip

Note: The 1st line is enough if you have only pip3 installed and not pip2.

How to specify the private SSH-key to use when executing shell command on Git?

for the gitlab RSAAuthentication yes

Host gitlab.com
  RSAAuthentication yes
  IdentityFile ~/.ssh/your_private_key_name
  IdentitiesOnly yes

doc is here

Artisan, creating tables in database

In order to give a value in the table, we need to give a command:

php artisan make:migration create_users_table

and after then this command line

php artisan migrate

......

When should an Excel VBA variable be killed or set to Nothing?

VBA uses a garbage collector which is implemented by reference counting.

There can be multiple references to a given object (for example, Dim aw = ActiveWorkbook creates a new reference to Active Workbook), so the garbage collector only cleans up an object when it is clear that there are no other references. Setting to Nothing is an explicit way of decrementing the reference count. The count is implicitly decremented when you exit scope.

Strictly speaking, in modern Excel versions (2010+) setting to Nothing isn't necessary, but there were issues with older versions of Excel (for which the workaround was to explicitly set)

what is the use of xsi:schemaLocation?

According to the spec for locating Schemas

there may or may not be a schema retrievable via the namespace name... User community and/or consumer/provider agreements may establish circumstances in which [trying to retrieve an xsd from the namespace url] is a sensible default strategy

(thanks for being unambiguous, spec!)

and

in case a document author (human or not) created a document with a particular schema in view, and warrants that some or all of the document conforms to that schema, the schemaLocation and noNamespaceSchemaLocation [attributes] are provided.

So basically with specifying just a namespace, your XML "might" be attempted to be validated against an xsd at that location (even if it lacks a schemaLocation attribute), depending on your "community." If you specify a specific schemaLocation, then it basically is implying that the xml document "should" be conformant to said xsd, so "please validate it" (as I read it). My guess is that if you don't do a schemaLocation or noNamespaceSchemaLocation attribute it just "isn't validated" most of the time (based on the other answers, appears java does it this way).

Another wrinkle here is that typically, with xsd validation in java libraries [ex: spring config xml files], if your XML files specifies a particular schemaLocation xsd url in an XML file, like xsi:schemaLocation="http://somewhere http://somewhere/something.xsd" typically within one of your dependency jars it will contain a copy of that xsd file, in its resources section, and spring has a "mapping" capability saying to treat that xsd file as if it maps to the url http://somewhere/something.xsd (so you never end up going to web and downloading the file, it just exists locally). See also https://stackoverflow.com/a/41225329/32453 for slightly more info.

Mobile Redirect using htaccess

I modified Tim Stone's solution even further. This allows the cookie to be in 2 states, 1 for mobile and 0 for full. When the mobile cookie is set to 0 even a mobile browser will go to the full site.

Here is the code:

<IfModule mod_rewrite.c>
    RewriteBase /
    RewriteEngine On

    # Check if mobile=1 is set and set cookie 'mobile' equal to 1
    RewriteCond %{QUERY_STRING} (^|&)mobile=1(&|$)
    RewriteRule ^ - [CO=mobile:1:%{HTTP_HOST}]

    # Check if mobile=0 is set and set cookie 'mobile' equal to 0
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [CO=mobile:0:%{HTTP_HOST}]

    # cookie can't be set and read in the same request so check
    RewriteCond %{QUERY_STRING} (^|&)mobile=0(&|$)
    RewriteRule ^ - [S=1]

    # Check if this looks like a mobile device
    RewriteCond %{HTTP:x-wap-profile} !^$ [OR]
    RewriteCond %{HTTP_USER_AGENT} "android|blackberry|ipad|iphone|ipod|iemobile|opera mobile|palmos|webos|googlebot-mobile" [NC,OR]
    RewriteCond %{HTTP:Profile}       !^$

    # Check if we're not already on the mobile site
    RewriteCond %{HTTP_HOST}          !^m\.
    # Check to make sure we haven't set the cookie before
    RewriteCond %{HTTP:Cookie}        !\mobile=0(;|$)
    # Now redirect to the mobile site
    RewriteRule ^ http://m.example.com%{REQUEST_URI} [R,L]
</IfModule>

Creating and Update Laravel Eloquent

$shopOwner = ShopMeta::firstOrNew(array('shopId' => $theID,'metadataKey' => 2001));

Then make your changes and save. Note the firstOrNew doesn't do the insert if its not found, if you do need that then its firstOrCreate.

Where does pip install its packages?

pip when used with virtualenv will generally install packages in the path <virtualenv_name>/lib/<python_ver>/site-packages.

For example, I created a test virtualenv named venv_test with Python 2.7, and the django folder is in venv_test/lib/python2.7/site-packages/django.

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

$(window).scrollTop() vs. $(document).scrollTop()

Cross browser way of doing this is

var top = ($(window).scrollTop() || $("body").scrollTop());

How can one print a size_t variable portably using the printf family?

On some platforms and for some types there are specific printf conversion specifiers available, but sometimes one has to resort to casting to larger types.

I've documented this tricky issue here, with example code: http://www.pixelbeat.org/programming/gcc/int_types/ and update it periodically with info on new platforms and types.

css transform, jagged edges in chrome

In case anyone's searching for this later on, a nice trick to get rid of those jagged edges on CSS transformations in Chrome is to add the CSS property -webkit-backface-visibility with a value of hidden. In my own tests, this has completely smoothed them out. Hope that helps.

-webkit-backface-visibility: hidden;

Style disabled button with CSS

I think you should be able to select a disabled button using the following:

button[disabled=disabled], button:disabled {
    // your css rules
}

Find all files in a directory with extension .txt in Python

To get all '.txt' file names inside 'dataPath' folder as a list in a Pythonic way:

from os import listdir
from os.path import isfile, join
path = "/dataPath/"
onlyTxtFiles = [f for f in listdir(path) if isfile(join(path, f)) and  f.endswith(".txt")]
print onlyTxtFiles

Application Installation Failed in Android Studio

Change your applicationId in the android/app/build.gradle file.

For example:

// Change this
applicationId "com.example.myAndroidApp"
//
// to this
applicationId "com.example.somethingElse"

Then Sync your gradle then you can able to install your app, if the previous applicationId is your production id the again change it the previous one now the device will allow to install the app.

Hope this may help you....

how to change the dist-folder path in angular-cli after 'ng build'

For Angular 6+ things have changed a little.

Define where ng build generates app files

Cli setup is now done in angular.json (replaced .angular-cli.json) in your workspace root directory. The output path in default angular.json should look like this (irrelevant lines removed):

{
  "projects": {
    "my-app-name": {
    "architect": {
      "options": {
         "outputPath": "dist/my-app-name",

Obviously, this will generate your app in WORKSPACE/dist/my-app-name. Modify outputPath if you prefer another directory.

You can overwrite the output path using command line arguments (e.g. for CI jobs):

ng build -op dist/example
ng build --output-path=dist/example

S.a. https://github.com/angular/angular-cli/wiki/build

Hosting angular app in subdirectory

Setting the output path, will tell angular where to place the "compiled" files but however you change the output path, when running the app, angular will still assume that the app is hosted in the webserver's document root.

To make it work in a sub directory, you'll have to set the base href.

In angular.json:

{
  "projects": {
    "my-app-name": {
    "architect": {
      "options": {
         "baseHref": "/my-folder/",

Cli:

ng build --base-href=/my-folder/

If you don't know where the app will be hosted on build time, you can change base tag in generated index.html.

Here's an example how we do it in our docker container:

entrypoint.sh

if [ -n "${BASE_PATH}" ]
then
  files=( $(find . -name "index.html") )
  cp -n "${files[0]}" "${files[0]}.org"
  cp "${files[0]}.org" "${files[0]}"
  sed -i "s*<base href=\"/\">*<base href=\"${BASE_PATH}\">*g" "${files[0]}"
fi

Text on image mouseover?

Here is one way to do this using css

HTML

<div class="imageWrapper">
    <img src="http://lorempixel.com/300/300/" alt="" />
    <a href="http://google.com" class="cornerLink">Link</a>
</div>?

CSS

.imageWrapper {
    position: relative;
    width: 300px;
    height: 300px;
}
.imageWrapper img {
    display: block;
}
.imageWrapper .cornerLink {
    opacity: 0;
    position: absolute;
    bottom: 0px;
    left: 0px;
    right: 0px;
    padding: 2px 0px;
    color: #ffffff;
    background: #000000;
    text-decoration: none;
    text-align: center;
    -webkit-transition: opacity 500ms;
    -moz-transition: opacity 500ms;
    -o-transition: opacity 500ms;
    transition: opacity 500ms;

}
.imageWrapper:hover .cornerLink {
    opacity: 0.8;
}

Demo

Or if you just want it in the bottom left corner:

Demo

Switch with if, else if, else, and loops inside case

but i only wanted the for statement to be attached to the if statement, not the else if statements as well.

Well get rid of the else then. If the else if is not supposed to be part of the for then write it as:

           for(int i=0; i<something_in_the_array.length;i++)
                if(whatever_value==(something_in_the_array[i]))
                {
                    value=2;
                    break;
                }

           if(whatever_value==2)
           {
                value=3;
                break;  // redundant now
           }

           else if(whatever_value==3)
           {
                value=4;
                break;  // redundant now
           }

Having said that:

  • it is not at all clear what you are really trying to do here,
  • not having the else part in the loop doesn't seem to make a lot of sense here,
  • a lot of people (myself included) think it is to always use braces ... so that people don't get tripped up by incorrect indentation when reading your code. (And in this case, it might help us figure out what you are really trying to do here ...)

Finally, braces are less obtrusive if you put the opening brace on the end of the previous line; e.g.

  if (something) {
     doSomething();
  }

rather than:

  if (something) 
  {
     doSomething();
  }

How do I convert an existing callback API to promises?

You can use JavaScript native promises with Node JS.

My Cloud 9 code link: https://ide.c9.io/adx2803/native-promises-in-node

/**
* Created by dixit-lab on 20/6/16.
*/

var express = require('express');
var request = require('request');   //Simplified HTTP request client.


var app = express();

function promisify(url) {
    return new Promise(function (resolve, reject) {
        request.get(url, function (error, response, body) {
            if (!error && response.statusCode == 200) {
                resolve(body);
            }
            else {
                reject(error);
            }
        })
    });
}

//get all the albums of a user who have posted post 100
app.get('/listAlbums', function (req, res) {
    //get the post with post id 100
    promisify('http://jsonplaceholder.typicode.com/posts/100').then(function (result) {
        var obj = JSON.parse(result);
        return promisify('http://jsonplaceholder.typicode.com/users/' + obj.userId + '/albums')
    })
    .catch(function (e) {
        console.log(e);
    })
    .then(function (result) {
        res.end(result);
    })
})

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port

    console.log("Example app listening at http://%s:%s", host, port)
})

//run webservice on browser : http://localhost:8081/listAlbums

How does python numpy.where() work?

Old Answer it is kind of confusing. It gives you the LOCATIONS (all of them) of where your statment is true.

so:

>>> a = np.arange(100)
>>> np.where(a > 30)
(array([31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47,
       48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64,
       65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81,
       82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
       99]),)
>>> np.where(a == 90)
(array([90]),)

a = a*40
>>> np.where(a > 1000)
(array([26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
       43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
       60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
       77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93,
       94, 95, 96, 97, 98, 99]),)
>>> a[25]
1000
>>> a[26]
1040

I use it as an alternative to list.index(), but it has many other uses as well. I have never used it with 2D arrays.

http://docs.scipy.org/doc/numpy/reference/generated/numpy.where.html

New Answer It seems that the person was asking something more fundamental.

The question was how could YOU implement something that allows a function (such as where) to know what was requested.

First note that calling any of the comparison operators do an interesting thing.

a > 1000
array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True,  True,  True,  True,  True,  True,  True,  True,  True,
        True`,  True,  True,  True,  True,  True,  True,  True,  True,  True], dtype=bool)`

This is done by overloading the "__gt__" method. For instance:

>>> class demo(object):
    def __gt__(self, item):
        print item


>>> a = demo()
>>> a > 4
4

As you can see, "a > 4" was valid code.

You can get a full list and documentation of all overloaded functions here: http://docs.python.org/reference/datamodel.html

Something that is incredible is how simple it is to do this. ALL operations in python are done in such a way. Saying a > b is equivalent to a.gt(b)!

Pandas: Appending a row to a dataframe and specify its index label

I shall refer to the same sample of data as posted in the question:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])
print('The original data frame is: \n{}'.format(df))

Running this code will give you

The original data frame is:

          A         B         C         D
0  0.494824 -0.328480  0.818117  0.100290
1  0.239037  0.954912 -0.186825 -0.651935
2 -1.818285 -0.158856  0.359811 -0.345560
3 -0.070814 -0.394711  0.081697 -1.178845
4 -1.638063  1.498027 -0.609325  0.882594
5 -0.510217  0.500475  1.039466  0.187076
6  1.116529  0.912380  0.869323  0.119459
7 -1.046507  0.507299 -0.373432 -1.024795

Now you wish to append a new row to this data frame, which doesn't need to be copy of any other row in the data frame. @Alon suggested an interesting approach to use df.loc to append a new row with different index. The issue, however, with this approach is if there is already a row present at that index, it will be overwritten by new values. This is typically the case for datasets when row index is not unique, like store ID in transaction datasets. So a more general solution to your question is to create the row, transform the new row data into a pandas series, name it to the index you want to have and then append it to the data frame. Don't forget to overwrite the original data frame with the one with appended row. The reason is df.append returns a view of the dataframe and does not modify its contents. Following is the code:

row = pd.Series({'A':10,'B':20,'C':30,'D':40},name=3)
df = df.append(row)
print('The new data frame is: \n{}'.format(df))

Following would be the new output:

The new data frame is:

           A          B          C          D
0   0.494824  -0.328480   0.818117   0.100290
1   0.239037   0.954912  -0.186825  -0.651935
2  -1.818285  -0.158856   0.359811  -0.345560
3  -0.070814  -0.394711   0.081697  -1.178845
4  -1.638063   1.498027  -0.609325   0.882594
5  -0.510217   0.500475   1.039466   0.187076
6   1.116529   0.912380   0.869323   0.119459
7  -1.046507   0.507299  -0.373432  -1.024795
3  10.000000  20.000000  30.000000  40.000000

How to get the caller class in Java

The error message the OP is encountering is just an Eclipse feature. If you are willing to tie your code to a specific maker (and even version) of the JVM, you can effectively use method sun.reflect.Reflection.getCallerClass(). You can then compile the code outside of Eclipse or configure it not to consider this diagnostic an error.

The worse Eclipse configuration is to disable all occurrences of the error by:

Project Properties / Java Compiler / Errors/Warnings / Enable project specific settings set to checked / Deprecated and restrited API / Forbidden reference (access rules) set to Warning or Ignore.

The better Eclipse configuration is to disable a specific occurrence of the error by:

Project Properties / Java Build Path / Libraries / JRE System Library expand / Access rules: select / Edit... / Add... / Resolution: set to Discouraged or Accessible / Rule Pattern set to sun/reflect/Reflection.

How to delete a whole folder and content?

In Kotlin you can use deleteRecursively() extension from kotlin.io package

val someDir = File("/path/to/dir")
someDir.deleteRecursively()

Cannot checkout, file is unmerged

i resolved by doing below 2 easy steps :

step 1: git reset Head step 2: git add .

Android requires compiler compliance level 5.0 or 6.0. Found '1.7' instead. Please use Android Tools > Fix Project Properties

Doing Project -> Clean... fixed it for me.

My eclipse had stopped working so I cleaned workspace directory and after I run eclipse when I import the project I had this problem. Other solutions suggested here didn't work.

Cannot access wamp server on local network

Perhaps your Apache is bounded to localhost only. Look in your apache configuration file for:

Listen 127.0.0.1:80

If you found it, replace it for:

Listen 80

(More info about Apache Binding)

How to add days to the current date?

Add Days in Date in SQL

 DECLARE @NEWDOB DATE=null
 
 SET @NEWDOB= (SELECT DOB, DATEADD(dd,45,DOB)AS NEWDOB FROM tbl_Employees)

Git: Find the most recent common ancestor of two branches

As noted in a prior answer, although git merge-base works,

$ git merge-base myfeature develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

If myfeature is the current branch, as is common, you can use --fork-point:

$ git merge-base --fork-point develop
050dc022f3a65bdc78d97e2b1ac9b595a924c3f2

This argument works only in sufficiently recent versions of git. Unfortunately it doesn't always work, however, and it is not clear why. Please refer to the limitations noted toward the end of this answer.


For full commit info, consider:

$ git log -1 $(git merge-base --fork-point develop) 

How to use greater than operator with date?

In your statement, you are comparing a string called start_date with the time.
If start_date is a column, it should either be

 
  SELECT * FROM `la_schedule` WHERE start_date >'2012-11-18';
 

(no apostrophe) or


SELECT * FROM `la_schedule` WHERE `start_date` >'2012-11-18';

(with backticks).

Hope this helps.

When to use HashMap over LinkedList or ArrayList and vice-versa

Lists and Maps are different data structures. Maps are used for when you want to associate a key with a value and Lists are an ordered collection.

Map is an interface in the Java Collection Framework and a HashMap is one implementation of the Map interface. HashMap are efficient for locating a value based on a key and inserting and deleting values based on a key. The entries of a HashMap are not ordered.

ArrayList and LinkedList are an implementation of the List interface. LinkedList provides sequential access and is generally more efficient at inserting and deleting elements in the list, however, it is it less efficient at accessing elements in a list. ArrayList provides random access and is more efficient at accessing elements but is generally slower at inserting and deleting elements.

What is the difference between localStorage, sessionStorage, session and cookies?

Local storage: It keeps store the user information data without expiration date this data will not be deleted when user closed the browser windows it will be available for day, week, month and year.

In Local storage can store 5-10mb offline data.

//Set the value in a local storage object
localStorage.setItem('name', myName);

//Get the value from storage object
localStorage.getItem('name');

//Delete the value from local storage object
localStorage.removeItem(name);//Delete specifice obeject from local storege
localStorage.clear();//Delete all from local storege

Session Storage: It is same like local storage date except it will delete all windows when browser windows closed by a web user.

In Session storage can store upto 5 mb data

//set the value to a object in session storege
sessionStorage.myNameInSession = "Krishna";

Session: A session is a global variable stored on the server. Each session is assigned a unique id which is used to retrieve stored values.

Cookies: Cookies are data, stored in small text files as name-value pairs, on your computer. Once a cookie has been set, all page requests that follow return the cookie name and value.

Eclipse Error: "Failed to connect to remote VM"

I've encountered like this in Hybris.

  1. Check your port in Resource Monitor > Network. Check if other service is using your port.

1.2 If yes, then you need to change your properties in project.properties

1.3 Change your address, any available address. In my case, I changed from 8000 to 8080. then save.

java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=8080,suspend=n yourServer
  1. In your console, rebuild your ant using command 'ant all'

  2. Then debug again, using the command 'hybrisserver.bat debug'

How do I get the SQLSRV extension to work with PHP, since MSSQL is deprecated?

Download Microsoft Drivers for PHP for SQL Server. Extract the files and use one of:

File                             Thread Safe         VC Bulid
php_sqlsrv_53_nts_vc6.dll           No                  VC6
php_sqlsrv_53_nts_vc9.dll           No                  VC9
php_sqlsrv_53_ts_vc6.dll            Yes                 VC6
php_sqlsrv_53_ts_vc9.dll            Yes                 VC9

You can see the Thread Safety status in phpinfo().

Add the correct file to your ext directory and the following line to your php.ini:

extension=php_sqlsrv_53_*_vc*.dll

Use the filename of the file you used.

As Gordon already posted this is the new Extension from Microsoft and uses the sqlsrv_* API instead of mssql_*

Update:
On Linux you do not have the requisite drivers and neither the SQLSERV Extension.
Look at Connect to MS SQL Server from PHP on Linux? for a discussion on this.

In short you need to install FreeTDS and YES you need to use mssql_* functions on linux. see update 2

To simplify things in the long run I would recommend creating a wrapper class with requisite functions which use the appropriate API (sqlsrv_* or mssql_*) based on which extension is loaded.

Update 2: You do not need to use mssql_* functions on linux. You can connect to an ms sql server using PDO + ODBC + FreeTDS. On windows, the best performing method to connect is via PDO + ODBC + SQL Native Client since the PDO + SQLSRV driver can be incredibly slow.

Same font except its weight seems different on different browsers

There's some great information about this here: https://bugzilla.mozilla.org/show_bug.cgi?id=857142

Still experimenting but so far a minimally invasive solution, aimed only at FF is:

body {
-moz-osx-font-smoothing: grayscale;
}

Stored Procedure parameter default value - is this a constant or a variable

It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.

Look at the definition of sys.all_parameters:

default_value sql_variant If has_default_value is 1, the value of this column is the value of the default for the parameter; otherwise, NULL.

That is, whatever the default for a parameter is, it has to fit in that column.


As Alex K pointed out in the comments, you can just do:

CREATE PROCEDURE [dbo].[problemParam] 
    @StartDate INT = NULL,
    @EndDate INT = NULL
AS  
BEGIN
   SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))

provided that NULL isn't intended to be a valid value for @StartDate.


As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE() within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.

JQuery addclass to selected div, remove class if another div is selected

It's all about the selector. You can change your code to be something like this:

<div class="formbuilder">
    <div class="active">Heading</div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>

Then use this javascript:

$(document).ready(function () {
    $('.formbuilder div').on('click', function () {
        $('.formbuilder div').removeClass('active');
        $(this).addClass('active');
    });
});

The example in a working jsfiddle

See this api about the selector I used: http://api.jquery.com/descendant-selector/

Focusable EditText inside ListView

Just try this

android:windowSoftInputMode="adjustNothing"

in the

activity

section of your manifest. Yes, it adjusts nothings, which means the editText will stay where it is when IME is opening. But that's just an little inconvenience that still completely solves the problem of losing focus.

How to get the current working directory in Java?

This is my silver bullet when ever the moment of confusion bubbles in.(Call it as first thing in main). Maybe for example JVM is slipped to be different version by IDE. This static function searches current process PID and opens VisualVM on that pid. Confusion stops right there because you want it all and you get it...

  public static void callJVisualVM() {
    System.out.println("USER:DIR!:" + System.getProperty("user.dir"));
    //next search current jdk/jre
    String jre_root = null;
    String start = "vir";
    try {
        java.lang.management.RuntimeMXBean runtime =
                java.lang.management.ManagementFactory.getRuntimeMXBean();
        String jvmName = runtime.getName();
        System.out.println("JVM Name = " + jvmName);
        long pid = Long.valueOf(jvmName.split("@")[0]);
        System.out.println("JVM PID  = " + pid);
        Runtime thisRun = Runtime.getRuntime();
        jre_root = System.getProperty("java.home");
        System.out.println("jre_root:" + jre_root);
        start = jre_root.concat("\\..\\bin\\jvisualvm.exe " + "--openpid " + pid);
        thisRun.exec(start);
    } catch (Exception e) {
        System.getProperties().list(System.out);
        e.printStackTrace();
    }
}

How to play ringtone/alarm sound in Android

You can simply play a setted ringtone with this:

Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();

How to submit an HTML form without redirection

You can achieve that by redirecting the form's action to an invisible <iframe>. It doesn't require any JavaScript or any other type of scripts.

<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>

<form action="submitscript.php" target="dummyframe">
    <!-- Form body here -->
</form>

How can I convert a stack trace to a string?

Without java.io.* it can be done like this.

String trace = e.toString() + "\n";                     

for (StackTraceElement e1 : e.getStackTrace()) {
    trace += "\t at " + e1.toString() + "\n";
}   

And then the trace variable holds your stack trace. Output also holds the initial cause, the output is identical to printStackTrace()

Example, printStackTrace() yields:

java.io.FileNotFoundException: / (Is a directory)
    at java.io.FileOutputStream.open0(Native Method)
    at java.io.FileOutputStream.open(FileOutputStream.java:270)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
    at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
    at Test.main(Test.java:9)

The trace String holds, when printed to stdout

java.io.FileNotFoundException: / (Is a directory)
     at java.io.FileOutputStream.open0(Native Method)
     at java.io.FileOutputStream.open(FileOutputStream.java:270)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
     at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
     at Test.main(Test.java:9)

How do you test to see if a double is equal to NaN?

You can check for NaN by using var != var. NaN does not equal NaN.

EDIT: This is probably by far the worst method. It's confusing, terrible for readability, and overall bad practice.

Convert PEM traditional private key to PKCS8 private key

Try using following command. I haven't tried it but I think it should work.

openssl pkcs8 -topk8 -inform PEM -outform DER -in filename -out filename -nocrypt

Convert column classes in data.table

If you have a list of column names in data.table, you want to change the class of do:

convert_to_character <- c("Quarter", "value")

dt[, convert_to_character] <- dt[, lapply(.SD, as.character), .SDcols = convert_to_character]

How to execute a file within the python interpreter?

For Python 3:

>>> exec(open("helloworld.py").read())

Make sure that you're in the correct directory before running the command.

To run a file from a different directory, you can use the below command:

with open ("C:\\Users\\UserName\\SomeFolder\\helloworld.py", "r") as file:
    exec(file.read())

Is there a short cut for going back to the beginning of a file by vi editor?

In command mode: : + 1 will take you to first line

JPA: How to get entity based on field value other than ID?

Best practice is using @NaturalId annotation. It can be used as the business key for some cases it is too complicated, so some fields are using as the identifier in the real world. For example, I have user class with user id as primary key, and email is also unique field. So we can use email as our natural id

@Entity
@Table(name="user")
public class User {
  @Id
  @Column(name="id")
  private int id;

  @NaturalId
  @Column(name="email")
  private String email;

  @Column(name="name")
  private String name;
}

To get our record, just simply use 'session.byNaturalId()'

Session session = sessionFactory.getCurrentSession();
User user = session.byNaturalId(User.class)
                   .using("email","[email protected]")
                   .load()

How to open spss data files in excel?

In order to download that driver you must have a license to SPSS. For those who do not, there is an open source tool that is very much like SPSS and will allow you to import SAV files and export them to CSV.

Here's the software

And here are the steps to export the data.

How to enter in a Docker container already running with a new TTY

docker exec -ti 'CONTAINER_NAME' sh

or

docker exec -ti 'CONTAINER_ID' sh

Select entries between dates in doctrine 2

Look how I format my date $jour in the parameters. It depends if you use a expr()->like or a expr()->lte

$qb
        ->select('e')
        ->from('LdbPlanningBundle:EventEntity', 'e')
        ->where(
            $qb->expr()->andX(
                $qb->expr()->orX(
                    $qb->expr()->like('e.start', ':jour1'),
                    $qb->expr()->like('e.end', ':jour1'),
                    $qb->expr()->andX(
                        $qb->expr()->lte('e.start', ':jour2'),
                        $qb->expr()->gte('e.end', ':jour2')
                    )
                ),
                $qb->expr()->eq('e.user', ':user')
            )
        )
        ->andWhere('e.user = :user ')
        ->setParameter('user', $user)
        ->setParameter('jour1', '%'.$jour->format('Y-m-d').'%')
        ->setParameter('jour2', $jour->format('Y-m-d'))
        ->getQuery()
        ->getArrayResult()
    ;

How to share my Docker-Image without using the Docker-Hub?

Based on this blog, one could share a docker image without a docker registry by executing:

docker save --output latestversion-1.0.0.tar dockerregistry/latestversion:1.0.0

Once this command has been completed, one could copy the image to a server and import it as follows:

docker load --input latestversion-1.0.0.tar

Plotting histograms from grouped data in a pandas DataFrame

With recent version of Pandas, you can do df.N.hist(by=df.Letter)

Just like with the solutions above, the axes will be different for each subplot. I have not solved that one yet.

Allow multiple roles to access controller action

One possible simplification would be to subclass AuthorizeAttribute:

public class RolesAttribute : AuthorizeAttribute
{
    public RolesAttribute(params string[] roles)
    {
        Roles = String.Join(",", roles);
    }
}

Usage:

[Roles("members", "admin")]

Semantically it is the same as Jim Schmehil's answer.

How to create a button programmatically?

You can create like this and you can add action also like this....

import UIKit

let myButton = UIButton(frame: CGRect(x: 0, y: 0, width: 50, height: 50))

init(nibName nibNameOrNil: String!, bundle nibBundleOrNil: NSBundle!)
{       super.init(nibName: nibName, bundle: nibBundle) 
        myButton.targetForAction("tappedButton:", withSender: self)
}

func tappedButton(sender: UIButton!)
{ 
     println("tapped button")
}

How can I change the color of a Google Maps marker?

The simplest way I found is to use BitmapDescriptorFactory.defaultMarker() the documentation even has an example of setting the color. From my own code:

MarkerOptions marker = new MarkerOptions()
            .title(formatInfo(data))
            .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
            .position(new LatLng(data.getLatitude(), data.getLongitude()))

How to do logging in React Native?

Something that just came out about a month ago is "Create React Native App," an awesome boilerplate that allows you (with minimal effort) to show what your app looks like live on your mobile device (ANY with a camera) using the Expo app. It not only has live updates, but it will allow you to see the console logs in your terminal just like when developing for the web, rather than having to use the browser like we did with React Native before.

You would, of course, have to make a new project with that boilerplate... but if you need to migrate your files over, that shouldn't be a problem. Give it a shot.

Edit: Actually it doesn't even require a camera. I said that for scanning a QR code, but you can also type out something to sync it up with your server, not just a QR code.

How to add a bot to a Telegram Group?

You have to use @BotFather, send it command: /setjoingroups There will be dialog like this:

YOU: /setjoingroups

BotFather: Choose a bot to change group membership settings.

YOU: @YourBot

BotFather: 'Enable' - bot can be added to groups. 'Disable' - block group invitations, the bot can't be added to groups. Current status is: DISABLED

YOU: Enable

BotFather: Success! The new status is: ENABLED.

After this you will see button "Add to Group" in your bot's profile.

How can I generate a unique ID in Python?

Maybe this work for u

str(uuid.uuid4().fields[-1])[:5]

How to store JSON object in SQLite database

https://github.com/app-z/Json-to-SQLite

At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/

Main method

void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...

Fields name will create dynamically

Why GDB jumps unpredictably between lines and prints variables as "<value optimized out>"?

The compiler will start doing very clever things with optimisations turned on. The debugger will show the code jumping forward and backwards alot due to the optimized way variables are stored in registers. This is probably the reason why you can't set your variable (or in some cases see its value) as it has been cleverly distributed between registers for speed, rather than having a direct memory location that the debugger can access.

Compile without optimisations?

Writing to an Excel spreadsheet

You can try hfexcel Human Friendly object-oriented python library based on XlsxWriter:

from hfexcel import HFExcel

hf_workbook = HFExcel.hf_workbook('example.xlsx', set_default_styles=False)

hf_workbook.add_style(
    "headline", 
    {
       "bold": 1,
        "font_size": 14,
        "font": "Arial",
        "align": "center"
    }
)

sheet1 = hf_workbook.add_sheet("sheet1", name="Example Sheet 1")

column1, _ = sheet1.add_column('headline', name='Column 1', width=2)
column1.add_row(data='Column 1 Row 1')
column1.add_row(data='Column 1 Row 2')

column2, _ = sheet1.add_column(name='Column 2')
column2.add_row(data='Column 2 Row 1')
column2.add_row(data='Column 2 Row 2')


column3, _ = sheet1.add_column(name='Column 3')
column3.add_row(data='Column 3 Row 1')
column3.add_row(data='Column 3 Row 2')

# In order to get a row with coordinates:
# sheet[column_index][row_index] => row
print(sheet1[1][1].data)
assert(sheet1[1][1].data == 'Column 2 Row 2')

hf_workbook.save()

Git: add vs push vs commit

Very nice pdf about many GIT secrets.

Add is same as svn's add (how ever sometimes it is used to mark file resolved).

Commit also is same as svn's , but it commit change into your local repository.

For Restful API, can GET method use json data?

In theory, there's nothing preventing you from sending a request body in a GET request. The HTTP protocol allows it, but have no defined semantics, so it's up to you to document what exactly is going to happen when a client sends a GET payload. For instance, you have to define if parameters in a JSON body are equivalent to querystring parameters or something else entirely.

However, since there are no clearly defined semantics, you have no guarantee that implementations between your application and the client will respect it. A server or proxy might reject the whole request, or ignore the body, or anything else. The REST way to deal with broken implementations is to circumvent it in a way that's decoupled from your application, so I'd say you have two options that can be considered best practices.

The simple option is to use POST instead of GET as recommended by other answers. Since POST is not standardized by HTTP, you'll have to document how exactly that's supposed to work.

Another option, which I prefer, is to implement your application assuming the GET payload is never tampered with. Then, in case something has a broken implementation, you allow clients to override the HTTP method with the X-HTTP-Method-Override, which is a popular convention for clients to emulate HTTP methods with POST. So, if a client has a broken implementation, it can write the GET request as a POST, sending the X-HTTP-Method-Override: GET method, and you can have a middleware that's decoupled from your application implementation and rewrites the method accordingly. This is the best option if you're a purist.

Changing the color of a clicked table row using jQuery

Create a css class that applies the row color, and use jQuery to toggle the class on/off:

CSS:

.selected {
    background-color: blue;
}

jQuery:

$('#data tr').on('click', function() {
    $(this).toggleClass('selected');
});

The first click will add the class (making the background color blue), and the next click will remove the class, reverting it to whatever it was before. Repeat!

In terms of the two CSS classes you already have, I would change the .nonhighlighted class to apply to all rows of the table by default, then toggle the .highlighted on and off:

<style type="text/css">

.highlighted {
    background: red;
}

#data tr {
    background: white;
}

</style>

$('#data tr').on('click', function() {
    $(this).toggleClass('highlighted');
});

How to tell PowerShell to wait for each command to end before starting the next?

Taking it further you could even parse on the fly

e.g.

& "my.exe" | %{
    if ($_ -match 'OK')
    { Write-Host $_ -f Green }
    else if ($_ -match 'FAIL|ERROR')
    { Write-Host $_ -f Red }
    else 
    { Write-Host $_ }
}

Creating pdf files at runtime in c#

There is a new project, RazorPDF which can be used from ASP.NET MVC. It is available as nuget package (search for RazorPDF).

Here is more info: http://nyveldt.com/blog/post/Introducing-RazorPDF

IMPORTANT UPDATE as @DenNukem pointed out, it depends on iTextsharp, I forgot to edit answer when I found that out (when I tried to use it), so if your project is not open source and eligible for their AGPL licence, it will probably be too expensive to use.

remove white space from the end of line in linux

sed -i 's/[[:blank:]]\{1,\}$//' YourFile

[:blank:] is for space, tab mainly and {1,} to exclude 'no space at the end' of the substitution process (no big significant impact if line are short and file are small)

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object

Pretty sure pk_OrderID is the PK of AC_Shipping_Addresses

And you are trying to insert a duplicate via the _Order.OrderNumber

Do a

select * from AC_Shipping_Addresses where pk_OrderID = 165863;

or select count(*) ....

Pretty sure you will get a row returned.

What it is telling you is you are already using pk_OrderID = 165863 and cannot have another row with that value.

if you want to not insert if there is a row

insert into table (pk, value) 
select 11 as pk, 'val' as value 
where not exists (select 1 from table where pk = 11) 

apc vs eaccelerator vs xcache

APC definitely. It's written by the PHP guys, so even though it might not share the highest speeds, you can bet on the fact it's the highest quality.

Plus you get some other nifty features I use all the time (http://www.php.net/apc).

Invalid URI: The format of the URI could not be determined

I worked around this by using UriBuilder instead.

UriBuilder builder = new UriBuilder(slct.Text);

if (DeleteFileOnServer(builder.Uri))
{
   ...
}

Sequel Pro Alternative for Windows

You can try DBVisualizer some features are not free, but you can get an evaluate license...

How to compare times in Python?

datetime have comparison capability

>>> import datetime
>>> import time
>>> a =  datetime.datetime.now()
>>> time.sleep(2.0)
>>> b =  datetime.datetime.now()
>>> print a < b
True
>>> print a == b
False

Using the slash character in Git branch name

I forgot that I had already an unused labs branch. Deleting it solved my problem:

git branch -d labs
git checkout -b labs/feature

Explanation:

Each name can only be a parent branch or a normal branch, not both. Thats why the branches labs and labs/feature can't exists both at the same time.

The reason: Branches are stored in the file system and there you also can't have a file labs and a directory labs at the same level.