Programs & Examples On #Protocol buffers

Protocol Buffers are a language-neutral and platform-neutral way of encoding structured data in an efficient yet extensible format. Google uses Protocol Buffers for almost all of its internal RPC protocols and file formats. It is also the default data encoding used by the open source gRPC framework.

Biggest differences of Thrift vs Protocol Buffers?

As I've said as "Thrift vs Protocol buffers" topic :

Referring to Thrift vs Protobuf vs JSON comparison :

Additionally, there are plenty of interesting additional tools available for those solutions, which might decide. Here are examples for Protobuf: Protobuf-wireshark , protobufeditor.

ImportError: No module named google.protobuf

To find where the name google clashes .... try this:

python3

then >>> help('google')

... I got info about google-auth:

NAME
    google

PACKAGE CONTENTS
    auth (package)
    oauth2 (package)

Also then try

pip show google-auth

Then

sudo pip3 uninstall google-auth

... and re-try >>> help('google')

I then see protobuf:

NAME
    google

PACKAGE CONTENTS
    protobuf (package)

Java: JSON -> Protobuf & back conversion

I don't much like an idea of writing binary protobuf to database, because it can one day become not backward-compatible with newer versions and break the system that way.

Converting protobuf to JSON for storage and then back to protobuf on load is much more likely to create compatibility problems, because:

  • If the process which performs the conversion is not built with the latest version of the protobuf schema, then converting will silently drop any fields that the process doesn't know about. This is true both of the storing and loading ends.
  • Even with the most recent schema available, JSON <-> Protobuf conversion may be lossy in the presence of imprecise floating-point values and similar corner cases.
  • Protobufs actually have (slightly) stronger backwards-compatibility guarantees than JSON. Like with JSON, if you add a new field, old clients will ignore it. Unlike with JSON, Protobufs allow declaring a default value, which can make it somewhat easier for new clients to deal with old data that is otherwise missing the field. This is only a slight advantage, but otherwise Protobuf and JSON have equivalent backwards-compatibility properties, therefore you are not gaining any backwards-compatibility advantages from storing in JSON.

With all that said, there are many libraries out there for converting protobufs to JSON, usually built on the Protobuf reflection interface (not to be confused with the Java reflection interface; Protobuf reflection is offered by the com.google.protobuf.Message interface).

Installing Google Protocol Buffers on mac

It's a new year and there's a new mismatch between the version of protobuf in Homebrew and the cutting edge release. As of February 2016, brew install protobuf will give you version 2.6.1.

If you want the 3.0 beta release instead, you can install it with:

brew install --devel protobuf

How to define an optional field in protobuf 3

Based on Kenton's answer, a simpler yet working solution looks like:

message Foo {
    oneof optional_baz { // "optional_" prefix here just serves as an indicator, not keyword in proto2
        int32 baz = 1;
    }
}

PyCharm shows unresolved references error for valid code

very easy

you just have to mark your root directory as: SOURCE ROOT (red), and your applications: EXCLUDED ROOT (blue),

then the unresolved reference will disappear.

  • enter image description hereif you use PyChram pro it do this for you automaticlly.

Difference between chr(13) and chr(10)

Chr(10) is the Line Feed character and Chr(13) is the Carriage Return character.

You probably won't notice a difference if you use only one or the other, but you might find yourself in a situation where the output doesn't show properly with only one or the other. So it's safer to include both.


Historically, Line Feed would move down a line but not return to column 1:

This  
    is  
        a  
            test.

Similarly Carriage Return would return to column 1 but not move down a line:

This  
is  
a  
test.

Paste this into a text editor and then choose to "show all characters", and you'll see both characters present at the end of each line. Better safe than sorry.

How to get URL of current page in PHP

 $uri = $_SERVER['REQUEST_URI'];

This will give you the requested directory and file name. If you use mod_rewrite, this is extremely useful because it tells you what page the user was looking at.

If you need the actual file name, you might want to try either $_SERVER['PHP_SELF'], the magic constant __FILE__, or $_SERVER['SCRIPT_FILENAME']. The latter 2 give you the complete path (from the root of the server), rather than just the root of your website. They are useful for includes and such.

$_SERVER['PHP_SELF'] gives you the file name relative to the root of the website.

 $relative_path = $_SERVER['PHP_SELF'];
 $complete_path = __FILE__;
 $complete_path = $_SERVER['SCRIPT_FILENAME'];

How do I parse JSON with Ruby on Rails?

require 'json'
out=JSON.parse(input)

This will return a Hash

How does delete[] know it's an array?

It's up to the runtime which is responsible for the memory allocation, in the same way that you can delete an array created with malloc in standard C using free. I think each compiler implements it differently. One common way is to allocate an extra cell for the array size.

However, the runtime is not smart enough to detect whether or not it is an array or a pointer, you have to inform it, and if you are mistaken, you either don't delete correctly (E.g., ptr instead of array), or you end up taking an unrelated value for the size and cause significant damage.

jQuery get textarea text

You should have a div that just contains the console messages, that is, previous commands and their output. And underneath put an input or textarea that just holds the command you are typing.

-------------------------------
| consle output ...           |
| more output                 |
| prevous commands and data   |
-------------------------------
> This is an input box.

That way you just send the value of the input box to the server for processing, and append the result to the console messages div.

How to iterate through a table rows and get the cell values using jQuery

I got it and explained in below:

//This table with two rows containing each row, one select in first td, and one input tags in second td and second input in third td;

<table id="tableID" class="table table-condensed">
       <thead>
          <tr>
             <th><label>From Group</lable></th>
             <th><label>To Group</lable></th>
             <th><label>Level</lable></th>

           </tr>
       </thead>
         <tbody>
           <tr id="rowCount">
             <td>
               <select >
                 <option value="">select</option>
                 <option value="G1">G1</option>
                 <option value="G2">G2</option>
                 <option value="G3">G3</option>
                 <option value="G4">G4</option>
               </select>
            </td>
            <td>
              <input type="text" id="" value="" readonly="readonly" />
            </td>
            <td>
              <input type="text" value=""  readonly="readonly" />
            </td>
         </tr>
         <tr id="rowCount">
          <td>
            <select >
              <option value="">select</option>
              <option value="G1">G1</option>
              <option value="G2">G2</option>
              <option value="G3">G3</option>
              <option value="G4">G4</option>
           </select>
         </td>
         <td>
           <input type="text" id="" value="" readonly="readonly" />
         </td>
         <td>
           <input type="text" value=""  readonly="readonly" />
         </td>
      </tr>
  </tbody>
</table>

  <button type="button" class="btn btn-default generate-btn search-btn white-font border-6 no-border" id="saveDtls">Save</button>


//call on click of Save button;
 $('#saveDtls').click(function(event) {

  var TableData = []; //initialize array;                           
  var data=""; //empty var;

  //Here traverse and  read input/select values present in each td of each tr, ;
  $("table#tableID > tbody > tr").each(function(row, tr) {

     TableData[row]={
        "fromGroup":  $('td:eq(0) select',this).val(),
        "toGroup": $('td:eq(1) input',this).val(),
        "level": $('td:eq(2) input',this).val()
 };

  //Convert tableData array to JsonData
  data=JSON.stringify(TableData)
  //alert('data'+data); 
  });
});

Euclidean distance of two vectors

try using this:

sqrt(sum((x1-x2)^2))

Getting "error": "unsupported_grant_type" when trying to get a JWT by calling an OWIN OAuth secured Web Api via Postman

  1. Note the URL: localhost:55828/token (not localhost:55828/API/token)
  2. Note the request data. Its not in json format, its just plain data without double quotes. [email protected]&password=Test123$&grant_type=password
  3. Note the content type. Content-Type: 'application/x-www-form-urlencoded' (not Content-Type: 'application/json')
  4. When you use JavaScript to make post request, you may use following:

    $http.post("localhost:55828/token", 
      "userName=" + encodeURIComponent(email) +
        "&password=" + encodeURIComponent(password) +
        "&grant_type=password",
      {headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
    ).success(function (data) {//...
    

See screenshots below from Postman:

Postman Request

Postman Request Header

Android Gradle Apache HttpClient does not exist?

In my case, I updated one of my libraries in my android project.

I'm using Reservoir as my cache storage solution: https://github.com/anupcowkur/Reservoir

I went from:

compile 'com.anupcowkur:reservoir:2.1'

To:

compile 'com.anupcowkur:reservoir:3.1.0'

The library author must have removed the commons-io library from the repo so my app no longer worked.

I had to manually include the commons-io by adding this onto gradle:

compile 'commons-io:commons-io:2.5'

https://mvnrepository.com/artifact/commons-io/commons-io/2.5

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

What are the correct version numbers for C#?

Version     .NET Framework  Visual Studio   Important Features
C# 1.0  .NET Framework 1.0/1.1  Visual Studio .NET 2002     

    Basic features

C# 2.0  .NET Framework 2.0  Visual Studio 2005  

    Generics
    Partial types
    Anonymous methods
    Iterators
    Nullable types
    Private setters (properties)
    Method group conversions (delegates)
    Covariance and Contra-variance
    Static classes

C# 3.0  .NET Framework 3.0\3.5  Visual Studio 2008  

    Implicitly typed local variables
    Object and collection initializers
    Auto-Implemented properties
    Anonymous types
    Extension methods
    Query expressions
    Lambda expressions
    Expression trees
    Partial Methods

C# 4.0  .NET Framework 4.0  Visual Studio 2010  

    Dynamic binding (late binding)
    Named and optional arguments
    Generic co- and contravariance
    Embedded interop types

C# 5.0  .NET Framework 4.5  Visual Studio 2012/2013     

    Async features
    Caller information

C# 6.0  .NET Framework 4.6  Visual Studio 2013/2015     

    Expression Bodied Methods
    Auto-property initializer
    nameof Expression
    Primary constructor
    Await in catch block
    Exception Filter
    String Interpolation

C# 7.0  .NET Core 2.0   Visual Studio 2017  

    out variables
    Tuples
    Discards
    Pattern Matching
    Local functions
    Generalized async return types
    Numeric literal syntax improvements
C# 8.0  .NET Core 3.0   Visual Studio 2019  

    
    Readonly members
    Default interface methods
    Pattern matching enhancements:
        Switch expressions
        Property patterns
        Tuple patterns
        Positional patterns
    Using declarations
    Static local functions
    Disposable ref structs
    Nullable reference types
    Asynchronous streams
    Asynchronous disposable
    Indices and ranges
    Null-coalescing assignment
    Unmanaged constructed types
    Stackalloc in nested expressions
    Enhancement of interpolated verbatim strings

Fastest way to check a string contain another substring in JavaScript?

The Fastest

  1. (ES6) includes
    var string = "hello",
    substring = "lo";
    string.includes(substring);
  1. ES5 and older indexOf
    var string = "hello",
    substring = "lo";
    string.indexOf(substring) !== -1;

http://jsben.ch/9cwLJ

enter image description here

Import Libraries in Eclipse?

Extract the jar, and put it somewhere in your Java project (usually under a "lib" subdirectory).

Right click the project, open its preferences, go for Java build path, and then the Libraries tab. You can add the library there with "add a jar".

If your jar is not open source, you may want to store it elsewhere and connect to it as an external jar.

How do I change the color of radio buttons?

simple cross browser custom radio button example for you

_x000D_
_x000D_
.checkbox input{_x000D_
    display: none;_x000D_
}_x000D_
.checkbox input:checked + label{_x000D_
    color: #16B67F;_x000D_
}_x000D_
.checkbox input:checked + label i{_x000D_
    background-image: url('http://kuzroman.com/images/jswiddler/radio-button.svg');_x000D_
}_x000D_
.checkbox label i{_x000D_
    width: 15px;_x000D_
    height: 15px;_x000D_
    display: inline-block;_x000D_
    background: #fff url('http://kuzroman.com/images/jswiddler/circle.svg') no-repeat 50%;_x000D_
    background-size: 12px;_x000D_
    position: relative;_x000D_
    top: 1px;_x000D_
    left: -2px;_x000D_
}
_x000D_
<div class="checkbox">_x000D_
  <input type="radio" name="sort" value="popularity" id="sort1">_x000D_
  <label for="sort1">_x000D_
        <i></i>_x000D_
        <span>first</span>_x000D_
    </label>_x000D_
_x000D_
  <input type="radio" name="sort" value="price" id="sort2">_x000D_
  <label for="sort2">_x000D_
        <i></i>_x000D_
        <span>second</span>_x000D_
    </label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://jsfiddle.net/kuzroman/ae1b34ay/

Regex pattern including all special characters

Here is my regular expression, that I used for removing all the special characters from any string :

String regex = ("[ \\\\s@  [\\\"]\\\\[\\\\]\\\\\\\0-9|^{#%'*/<()>}:`;,!& .?_$+-]+")

Truncate with condition

You can simply export the table with a query clause using datapump and import it back with table_exists_action=replace clause. Its will drop and recreate your table and take very less time. Please read about it before implementing.

How to change the order of DataFrame columns?

If your column names are too-long-to-type then you could specify the new order through a list of integers with the positions:

Data:

          0         1         2         3         4      mean
0  0.397312  0.361846  0.719802  0.575223  0.449205  0.500678
1  0.287256  0.522337  0.992154  0.584221  0.042739  0.485741
2  0.884812  0.464172  0.149296  0.167698  0.793634  0.491923
3  0.656891  0.500179  0.046006  0.862769  0.651065  0.543382
4  0.673702  0.223489  0.438760  0.468954  0.308509  0.422683
5  0.764020  0.093050  0.100932  0.572475  0.416471  0.389390
6  0.259181  0.248186  0.626101  0.556980  0.559413  0.449972
7  0.400591  0.075461  0.096072  0.308755  0.157078  0.207592
8  0.639745  0.368987  0.340573  0.997547  0.011892  0.471749
9  0.050582  0.714160  0.168839  0.899230  0.359690  0.438500

Generic example:

new_order = [3,2,1,4,5,0]
print(df[df.columns[new_order]])  

          3         2         1         4      mean         0
0  0.575223  0.719802  0.361846  0.449205  0.500678  0.397312
1  0.584221  0.992154  0.522337  0.042739  0.485741  0.287256
2  0.167698  0.149296  0.464172  0.793634  0.491923  0.884812
3  0.862769  0.046006  0.500179  0.651065  0.543382  0.656891
4  0.468954  0.438760  0.223489  0.308509  0.422683  0.673702
5  0.572475  0.100932  0.093050  0.416471  0.389390  0.764020
6  0.556980  0.626101  0.248186  0.559413  0.449972  0.259181
7  0.308755  0.096072  0.075461  0.157078  0.207592  0.400591
8  0.997547  0.340573  0.368987  0.011892  0.471749  0.639745
9  0.899230  0.168839  0.714160  0.359690  0.438500  0.050582

Although it might seem like I'm just explicitly typing the column names in a different order, the fact that there's a column 'mean' should make it clear that new_order relates to actual positions and not column names.

For the specific case of OP's question:

new_order = [-1,0,1,2,3,4]
df = df[df.columns[new_order]]
print(df)

       mean         0         1         2         3         4
0  0.500678  0.397312  0.361846  0.719802  0.575223  0.449205
1  0.485741  0.287256  0.522337  0.992154  0.584221  0.042739
2  0.491923  0.884812  0.464172  0.149296  0.167698  0.793634
3  0.543382  0.656891  0.500179  0.046006  0.862769  0.651065
4  0.422683  0.673702  0.223489  0.438760  0.468954  0.308509
5  0.389390  0.764020  0.093050  0.100932  0.572475  0.416471
6  0.449972  0.259181  0.248186  0.626101  0.556980  0.559413
7  0.207592  0.400591  0.075461  0.096072  0.308755  0.157078
8  0.471749  0.639745  0.368987  0.340573  0.997547  0.011892
9  0.438500  0.050582  0.714160  0.168839  0.899230  0.359690

The main problem with this approach is that calling the same code multiple times will create different results each time, so one needs to be careful :)

Including a css file in a blade template?

You should try this :

{{ Html::style('css/styles.css') }}

OR

<link href="{{ asset('css/styles.css') }}" rel="stylesheet">

Hope this help for you !!!

Do Java arrays have a maximum size?

There are actually two limits. One, the maximum element indexable for the array and, two, the amount of memory available to your application. Depending on the amount of memory available and the amount used by other data structures, you may hit the memory limit before you reach the maximum addressable array element.

Best way to convert strings to symbols in hash

Starting on Psych 3.0 you can add the symbolize_names: option

Psych.load("---\n foo: bar") # => {"foo"=>"bar"}

Psych.load("---\n foo: bar", symbolize_names: true) # => {:foo=>"bar"}

Note: if you have a lower Psych version than 3.0 symbolize_names: will be silently ignored.

My Ubuntu 18.04 includes it out of the box with ruby 2.5.1p57

Is it possible to import a whole directory in sass using @import?

You can generate SASS file which imports everything automatically, I use this Gulp task:

concatFilenames = require('gulp-concat-filenames')

let concatFilenamesOptions = {
    root: './',
    prepend: "@import '",
    append: "'"
}
gulp.task('sass-import', () => {
    gulp.src(path_src_sass)
        .pipe(concatFilenames('app.sass', concatFilenamesOptions))
        .pipe(gulp.dest('./build'))
})

You can also control importing order by ordering the folders like this:

path_src_sass = [
    './style/**/*.sass', // mixins, variables - import first
    './components/**/*.sass', // singule components
    './pages/**/*.sass' // higher-level templates that could override components settings if necessary
]

Using querySelectorAll to retrieve direct children

You could extend Element to include a method getDirectDesc() like this:

_x000D_
_x000D_
Element.prototype.getDirectDesc = function() {
    const descendants = Array.from(this.querySelectorAll('*'));
    const directDescendants = descendants.filter(ele => ele.parentElement === this)
    return directDescendants
}

const parent = document.querySelector('.parent')
const directDescendants = parent.getDirectDesc();

document.querySelector('h1').innerHTML = `Found ${directDescendants.length} direct descendants`
_x000D_
<ol class="parent">
    <li class="b">child 01</li>
    <li class="b">child 02</li>
    <li class="b">child 03 <ol>
            <li class="c">Not directDescendants 01</li>
            <li class="c">Not directDescendants 02</li>
        </ol>
    </li>
    <li class="b">child 04</li>
    <li class="b">child 05</li>
    </ol>
    <h1></h1>
_x000D_
_x000D_
_x000D_

The operation cannot be completed because the DbContext has been disposed error

Objects exposed as IQueryable<T> and IEnumerable<T> don't actually "execute" until they are iterated over or otherwise accessed, such as being composed into a List<T>. When EF returns an IQueryable<T> it is essentially just composing something capable of retrieving data, it isn't actually performing the retrieve until you consume it.

You can get a feel for this by putting a breakpoint where the IQueryable is defined, vs. when the .ToList() is called. (From inside the scope of the data context as Jofry has correctly pointed out.) The work to pull the data is done during the ToList() call.

Because of that, you need to keep the IQueryable<T> within the scope of the data context.

Map<String, String>, how to print both the "key string" and "value string" together

There are various ways to achieve this. Here are three.

    Map<String, String> map = new HashMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    System.out.println("using entrySet and toString");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry);
    }
    System.out.println();

    System.out.println("using entrySet and manual string creation");
    for (Entry<String, String> entry : map.entrySet()) {
        System.out.println(entry.getKey() + "=" + entry.getValue());
    }
    System.out.println();

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

Output

using entrySet and toString
key1=value1
key2=value2
key3=value3

using entrySet and manual string creation
key1=value1
key2=value2
key3=value3

using keySet
key1=value1
key2=value2
key3=value3

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

JSON to TypeScript class instance?

The best solution I found when dealing with Typescript classes and json objects: add a constructor in your Typescript class that takes the json data as parameter. In that constructor you extend your json object with jQuery, like this: $.extend( this, jsonData). $.extend allows keeping the javascript prototypes while adding the json object's properties.

export class Foo
{
    Name: string;
    getName(): string { return this.Name };

    constructor( jsonFoo: any )
    {
        $.extend( this, jsonFoo);
    }
}

In your ajax callback, translate your jsons in a your typescript object like this:

onNewFoo( jsonFoos : any[] )
{
  let receviedFoos = $.map( jsonFoos, (json) => { return new Foo( json ); } );

  // then call a method:
  let firstFooName = receviedFoos[0].GetName();
}

If you don't add the constructor, juste call in your ajax callback:

let newFoo = new Foo();
$.extend( newFoo, jsonData);
let name = newFoo.GetName()

...but the constructor will be useful if you want to convert the children json object too. See my detailed answer here.

jQuery .val change doesn't change input value

to expand a bit on Ricardo's answer: https://stackoverflow.com/a/11873775/7672426

http://api.jquery.com/val/#val2

about val()

Setting values using this method (or using the native value property) does not cause the dispatch of the change event. For this reason, the relevant event handlers will not be executed. If you want to execute them, you should call .trigger( "change" ) after setting the value.

Max value of Xmx and Xms in Eclipse?

Why do you need -Xms768 (small heap must be at least 768...)?

That means any java process (search in eclipse) will start with 768m memory allocated, doesn't that? That is why your eclipse isn't able to start properly.

Try -Xms16 -Xmx2048m, for instance.

How to remove components created with Angular-CLI

I had the same issue, couldn't find a right solution so I have manually deleted the component folder and then updated the app.module.ts file (removed the references to the deleted component) and it worked for me.

C# "must declare a body because it is not marked abstract, extern, or partial"

You cannot provide your own implementation for the setter when using automatic properties. In other words, you should either do:

public int Hour { get;set;} // Automatic property, no implementation

or provide your own implementation for both the getter and setter, which is what you want judging from your example:

public int Hour  
{ 
    get { return hour; } 
    set 
    {
        if (value < MIN_HOUR)
        {
            hour = 0;
            MessageBox.Show("Hour value " + value.ToString() + " cannot be negative. Reset to " + MIN_HOUR.ToString(),
                    "Invalid Hour", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        else
        {
                //take the modulus to ensure always less than 24 hours
                //works even if the value is already within range, or value equal to 24
                hour = value % MAX_HOUR;
        }
     }
}

Setting up a git remote origin

Using SSH

git remote add origin ssh://login@IP/path/to/repository

Using HTTP

git remote add origin http://IP/path/to/repository

However having a simple git pull as a deployment process is usually a bad idea and should be avoided in favor of a real deployment script.

How do I instantiate a JAXBElement<String> object?

Other alternative:

JAXBElement<String> element = new JAXBElement<>(new QName("Your localPart"),
                                                String.class, "Your message");

Then:

System.out.println(element.getValue()); // Result: Your message

PuTTY scripting to log onto host

For me it works this way:

putty -ssh [email protected] 22 -pw password

putty, protocol, user name @ ip address port and password. To connect in less than a second.

Get all files and directories in specific path fast

I know this is old, but... Another option may be to use the FileSystemWatcher like so:

void SomeMethod()
{
    System.IO.FileSystemWatcher m_Watcher = new System.IO.FileSystemWatcher();
    m_Watcher.Path = path;
    m_Watcher.Filter = "*.*";
    m_Watcher.NotifyFilter = m_Watcher.NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName | NotifyFilters.DirectoryName;
    m_Watcher.Created += new FileSystemEventHandler(OnChanged);
    m_Watcher.EnableRaisingEvents = true;
}

private void OnChanged(object sender, FileSystemEventArgs e)
    {
        string path = e.FullPath;

        lock (listLock)
        {
            pathsToUpload.Add(path);
        }
    }

This would allow you to watch the directories for file changes with an extremely lightweight process, that you could then use to store the names of the files that changed so that you could back them up at the appropriate time.

Javascript: getFullyear() is not a function

One way to get this error is to forget to use the 'new' keyword when instantiating your Date in javascript like this:

> d = Date();
'Tue Mar 15 2016 20:05:53 GMT-0400 (EDT)'
> typeof(d);
'string'
> d.getFullYear();
TypeError: undefined is not a function

Had you used the 'new' keyword, it would have looked like this:

> el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:08:58 GMT-0400 (EDT)
> typeof(d);
'object'
> d.getFullYear(0);
2016

Another way to get that error is to accidentally re-instantiate a variable in javascript between when you set it and when you use it, like this:

el@defiant $ node
> d = new Date();
Tue Mar 15 2016 20:12:13 GMT-0400 (EDT)
> d.getFullYear();
2016
> d = 57 + 23;
80
> d.getFullYear();
TypeError: undefined is not a function

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

To post JSON, you will need to stringify it. JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Delete all files in directory (but not directory) - one liner solution

import org.apache.commons.io.FileUtils;

FileUtils.cleanDirectory(directory); 

There is this method available in the same file. This will also recursively deletes all sub-folders and files under them.

Docs: org.apache.commons.io.FileUtils.cleanDirectory

Could not load file or assembly 'xxx' or one of its dependencies. An attempt was made to load a program with an incorrect format

If you get this error while running the site in IIS 7+ on 64bit servers, you may have assemblies that are 32bit and your application pool will have the option "Enable 32-Bit Applications" set to False; Set this to true and restart the site to get it working.

Negative regex for Perl string pattern match

What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:

if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }

if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
        && $string !~ /Bush/i) {
    print "$string\n"
}

How to select option in drop down using Capybara

It is not a direct answer, but you can (if your server permit):

1) Create a model for your Organization; extra: It will be easier to populate your HTML.

2) Create a factory (FactoryGirl) for your model;

3) Create a list (create_list) with the factory;

4) 'pick' (sample) a Organization from the list with:

# Random select
option = Organization.all.sample 

# Select the FIRST(0) by id
option = Organization.all[0] 

# Select the SECOND(1) after some restriction
option = Organization.where(some_attr: some_value)[2]
option = Organization.where("some_attr OP some_value")[2] #OP is "=", "<", ">", so on... 

What's the difference between import java.util.*; and import java.util.Date; ?

You probably have some other "Date" class imported somewhere (or you have a Date class in you package, which does not need to be imported). With "import java.util.*" you are using the "other" Date. In this case it's best to explicitly specify java.util.Date in the code.

Or better, try to avoid naming your classes "Date".

What does it mean to "call" a function in Python?

when you invoke a function , it is termed 'calling' a function . For eg , suppose you've defined a function that finds the average of two numbers like this-

def avgg(a,b) :
        return (a+b)/2;

now, to call the function , you do like this .

x=avgg(4,6)
print x

value of x will be 5 .

Table Naming Dilemma: Singular vs. Plural Names

Possible alternatives:

  • Rename the table SystemUser
  • Use brackets
  • Keep the plural table names.

IMO using brackets is technically the safest approach, though it is a bit cumbersome. IMO it's 6 of one, half-a-dozen of the other, and your solution really just boils down to personal/team preference.

Error message "unreported exception java.io.IOException; must be caught or declared to be thrown"

Your method showFile() declares that it can throw an IOException. Since this is a checked exception, any call to showFile() method must handle the exception somehow. One option is to wrap the call to showFile() in a try-catch block.

 try {
     showFile();
 }
 catch(IOException e) {
    // Code to handle an IOException here
 }

Why is the minidlna database not being refreshed?

MiniDLNA uses inotify, which is a functionality within the Linux kernel, used to discover changes in specific files and directories on the file system. To get it to work, you need inotify support enabled in your kernel.

The notify_interval (notice the lack of a leading 'i'), as far as I can tell, is only used if you have inotify disabled. To use the notify_interval (ie. get the server to 'poll' the file system for changes instead of automatically being notified of them), you have to disable the inotify functionality.

This is how it looks in my /etc/minidlna.conf:

# set this to no to disable inotify monitoring to automatically discover new files
# note: the default is yes
inotify=yes

Make sure that inotify is enabled in your kernel.

If it's not enabled, and you don't want to enable it, a forced rescan is the way to force MiniDLNA to re-scan the drive.

Best way to do multiple constructors in PHP

I know I'm super late to the party here, but I came up with a fairly flexible pattern that should allow some really interesting and versatile implementations.

Set up your class as you normally would, with whatever variables you like.

class MyClass{
    protected $myVar1;
    protected $myVar2;

    public function __construct($obj = null){
        if($obj){
            foreach (((object)$obj) as $key => $value) {
                if(isset($value) && in_array($key, array_keys(get_object_vars($this)))){
                    $this->$key = $value;
                }
            }
        }
    }
}

When you make your object just pass an associative array with the keys of the array the same as the names of your vars, like so...

$sample_variable = new MyClass([
    'myVar2'=>123, 
    'i_dont_want_this_one'=> 'This won\'t make it into the class'
    ]);

print_r($sample_variable);

The print_r($sample_variable); after this instantiation yields the following:

MyClass Object ( [myVar1:protected] => [myVar2:protected] => 123 )

Because we've initialize $group to null in our __construct(...), it is also valid to pass nothing whatsoever into the constructor as well, like so...

$sample_variable = new MyClass();

print_r($sample_variable);

Now the output is exactly as expected:

MyClass Object ( [myVar1:protected] => [myVar2:protected] => )

The reason I wrote this was so that I could directly pass the output of json_decode(...) to my constructor, and not worry about it too much.

This was executed in PHP 7.1. Enjoy!

What does \u003C mean?

Those are unicode escapes. The general unicode escapes looks like \uxxxx where xxxx are the hexadecimal digits of the ASCI characters. They are used mainly to insert special characters inside a javascript string.

Easiest way to change font and font size

you can change that using label property in property panel. This screen shot is example that

Rebuild Docker container on file changes

You can run build for a specific service by running docker-compose up --build <service name> where the service name must match how did you call it in your docker-compose file.

Example Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application in docker-compose file. You can then simply run docker-compose up --build application

Extra parameters In case you want to add extra parameters to your command such as -d for running in the background, the parameter must be before the service name: docker-compose up --build -d application

When to use DataContract and DataMember attributes?

DataMember attribute is not mandatory to add to serialize data. When DataMember attribute is not added, old XMLSerializer serializes the data. Adding a DataMember provides useful properties like order, name, isrequired which cannot be used otherwise.

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

Check string for palindrome

/**
 * Check whether a word is a palindrome
 *
 * @param word the word
 * @param low  low index
 * @param high high index
 * @return {@code true} if the word is a palindrome;
 * {@code false} otherwise
 */
private static boolean isPalindrome(char[] word, int low, int high) {
    if (low >= high) {
        return true;
    } else if (word[low] != word[high]) {
        return false;
    } else {
        return isPalindrome(word, low + 1, high - 1);
    }
}

/**
 * Check whether a word is a palindrome
 *
 * @param the word
 * @return {@code true} if the word is a palindrome;
 * @code false} otherwise
 */
private static boolean isPalindrome(char[] word) {
    int length = word.length;
    for (int i = 0; i <= length / 2; i++) {
        if (word[i] != word[length - 1 - i]) {
            return false;
        }
    }
    return true;
}

public static void main(String[] args) {
    char[] word = {'a', 'b', 'c', 'b', 'a' };
    System.out.println(isPalindrome(word, 0, word.length - 1));
    System.out.println(isPalindrome(word));
}

Differences between arm64 and aarch64

AArch64 is the 64-bit state introduced in the Armv8-A architecture (https://en.wikipedia.org/wiki/ARM_architecture#ARMv8-A). The 32-bit state which is backwards compatible with Armv7-A and previous 32-bit Arm architectures is referred to as AArch32. Therefore the GNU triplet for the 64-bit ISA is aarch64. The Linux kernel community chose to call their port of the kernel to this architecture arm64 rather than aarch64, so that's where some of the arm64 usage comes from.

As far as I know the Apple backend for aarch64 was called arm64 whereas the LLVM community-developed backend was called aarch64 (as it is the canonical name for the 64-bit ISA) and later the two were merged and the backend now is called aarch64.

So AArch64 and ARM64 refer to the same thing.

How to convert char to int?

int val = '1' - '0';

This can be done using ascii codes where '0' is the lowest and the number characters count up from there

Saving binary data as file using JavaScript from a browser

This is possible if the browser supports the download property in anchor elements.

var sampleBytes = new Int8Array(4096);

var saveByteArray = (function () {
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    return function (data, name) {
        var blob = new Blob(data, {type: "octet/stream"}),
            url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = name;
        a.click();
        window.URL.revokeObjectURL(url);
    };
}());

saveByteArray([sampleBytes], 'example.txt');


JSFiddle: http://jsfiddle.net/VB59f/2

ImageView in circular through xml

This will do the trick:

rectangle.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/transparent" />
    <padding android:bottom="-14dp" android:left="-14dp" android:right="-14dp" android:top="-14dp" />

</shape>

circle.xml

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:innerRadius="0dp"
    android:shape="oval"

    android:useLevel="false" >
    <solid android:color="@android:color/transparent" />

    <stroke
        android:width="15dp"
        android:color="@color/verification_contact_background" />

</shape>

profile_image.xml ( The layerlist )

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <item android:drawable="@drawable/rectangle" />
    <item android:drawable="@drawable/circle"/>

</layer-list>

Your layout

 <ImageView
        android:id="@+id/profile_image"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/default_org"
        android:src="@drawable/profile_image"/>

SQL Server Express CREATE DATABASE permission denied in database 'master'

Solution for Microsoft SQL Server, Error: 262

Click on Start -> Click in Microsoft SQL Server 2005 Now right click on SQL Server Management Studio Click on Run as administrator

How to prevent a background process from being stopped after closing SSH client in Linux

If you use screen to run a process as root, beware of the possibility of privilege elevation attacks. If your own account gets compromised somehow, there will be a direct way to take over the entire server.

If this process needs to be run regularly and you have sufficient access on the server, a better option would be to use cron the run the job. You could also use init.d (the super daemon) to start your process in the background, and it can terminate as soon as it's done.

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

How to get ALL child controls of a Windows Forms form of a specific type (Button/Textbox)?

I'd like to amend PsychoCoders answer: as the user wants to get all controls of a certain type we could use generics in the following way:

    public IEnumerable<T> FindControls<T>(Control control) where T : Control
    {
        // we can't cast here because some controls in here will most likely not be <T>
        var controls = control.Controls.Cast<Control>();

        return controls.SelectMany(ctrl => FindControls<T>(ctrl))
                                  .Concat(controls)
                                  .Where(c => c.GetType() == typeof(T)).Cast<T>();
    }

This way, we can call the function as follows:

private void Form1_Load(object sender, EventArgs e)
{
    var c = FindControls<TextBox>(this);
    MessageBox.Show("Total Controls: " + c.Count());
}

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

ASP.NET Temporary files cleanup

Yes, it's safe to delete these, although it may force a dynamic recompilation of any .NET applications you run on the server.

For background, see the Understanding ASP.NET dynamic compilation article on MSDN.

Get number of digits with JavaScript

`You can do it by simple loop using Math.trunc() function. if in interview interviewer ask to do it without converting it into string`
    let num = 555194154234 ;
    let len = 0 ;
    const numLen = (num) => {
     for(let i = 0; i < num ||  num == 1 ; i++){
        num = Math.trunc(num/10);
        len++ ;
     }
      return len + 1 ;
    }
    console.log(numLen(num));

Modulo operation with negative numbers

Can a modulus be negative?

% can be negative as it is the remainder operator, the remainder after division, not after Euclidean_division. Since C99 the result may be 0, negative or positive.

 // a % b
 7 %  3 -->  1  
 7 % -3 -->  1  
-7 %  3 --> -1  
-7 % -3 --> -1  

The modulo OP wanted is a classic Euclidean modulo, not %.

I was expecting a positive result every time.

To perform a Euclidean modulo that is well defined whenever a/b is defined, a,b are of any sign and the result is never negative:

int modulo_Euclidean(int a, int b) {
  int m = a % b;
  if (m < 0) {
    // m += (b < 0) ? -b : b; // avoid this form: it is UB when b == INT_MIN
    m = (b < 0) ? m - b : m + b;
  }
  return m;
}

modulo_Euclidean( 7,  3) -->  1  
modulo_Euclidean( 7, -3) -->  1  
modulo_Euclidean(-7,  3) -->  2  
modulo_Euclidean(-7, -3) -->  2   

Where can I set environment variables that crontab will use?

For me I had to set the environment variable for a php application. I resloved it by adding the following code to my crontab.

$ sudo  crontab -e

crontab:

ENVIRONMENT_VAR=production

* * * * * /home/deploy/my_app/cron/cron.doSomethingWonderful.php

and inside doSomethingWonderful.php I could get the environment value with:

<?php     
echo $_SERVER['ENVIRONMENT_VAR']; # => "production"

I hope this helps!

Unicode character in PHP string

PHP 7.0.0 has introduced the "Unicode codepoint escape" syntax.

It's now possible to write Unicode characters easily by using a double-quoted or a heredoc string, without calling any function.

$unicodeChar = "\u{1000}";

Reading an Excel file in python using pandas

import pandas as pd

data = pd.read_excel (r'**YourPath**.xlsx')

print (data)

ERROR : [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

I got a similar error, which was resolved by installing the corresponding MySQL drivers from:

http://www.connectionstrings.com/mysql-connector-odbc-5-2/info-and-download/

and by performing the following steps:

  1. Go to IIS and Application Pools in the left menu.
  2. Select relevant application pool which is assigned to the project.
  3. Click the Set Application Pool Defaults.
  4. In General Tab, set the Enable 32 Bit Application entry to "True".

Reference:

http://www.codeproject.com/Tips/305249/ERROR-IM-Microsoft-ODBC-Driver-Manager-Data-sou

URL string format for connecting to Oracle database with JDBC

if you are using oracle 10g expree Edition then:
1. for loading class use DriverManager.registerDriver (new oracle.jdbc.OracleDriver()); 2. for connecting to database use Connection conn = DriverManager.getConnection("jdbc:oracle:thin:username/password@localhost:1521:xe");

How to get the day of week and the month of the year?

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.

Long form:

const options = { weekday: 'long' };
const date = new Date();
console.log(date.toLocaleDateString('en-US', options));

One liner:

console.log(new Date().toLocaleDateString('en-US', { weekday: 'long' }));

Note: there are other language options for locale, but the one presented here for for US English

Oracle: how to INSERT if a row doesn't exist

INSERT INTO table
SELECT 'jonny', NULL
  FROM dual -- Not Oracle? No need for dual, drop that line
 WHERE NOT EXISTS (SELECT NULL -- canonical way, but you can select
                               -- anything as EXISTS only checks existence
                     FROM table
                    WHERE name = 'jonny'
                  )

Overriding css style?

Instead of override you can add another class to the element and then you have an extra abilities. for example:

HTML

<div class="style1 style2"></div>

CSS

//only style for the first stylesheet
.style1 {
   width: 100%;      
}
//only style for second stylesheet
.style2 {
   width: 50%;     
}
//override all
.style1.style2 { 
   width: 70%;
}

How do I install a module globally using npm?

I had issues installing Express on Ubuntu:

If for some reason NPM command is missing, test npm command with npm help. If not there, follow these steps - http://arnolog.net/post/8424207595/installing-node-js-npm-express-mongoose-on-ubuntu

If just the Express command is not working, try:

sudo npm install -g express

This made everything work as I'm used to with Windows7 and OSX.

Hope this helps!

TypeError: 'list' object is not callable in python

Seems like you've shadowed the builtin name list pointing at a class by the same name pointing at its instance. Here is an example:

>>> example = list('easyhoss')  # here `list` refers to the builtin class
>>> list = list('abc')  # we create a variable `list` referencing an instance of `list`
>>> example = list('easyhoss')  # here `list` refers to the instance
Traceback (most recent call last):
  File "<string>", line 1, in <module>
TypeError: 'list' object is not callable

I believe this is fairly obvious. Python stores object names (functions and classes are objects, too) in namespaces (which are implemented as dictionaries), hence you can rewrite pretty much any name in any scope. It won't show up as an error of some sort. As you might know, Python emphasizes that "special cases aren't special enough to break the rules". And there are two major rules behind the problem you've faced:

  1. Namespaces. Python supports nested namespaces. Theoretically you can endlessly nest namespaces. As I've already mentioned, namespaces are basically dictionaries of names and references to corresponding objects. Any module you create gets its own "global" namespace. In fact it's just a local namespace with respect to that particular module.

  2. Scoping. When you reference a name, the Python runtime looks it up in the local namespace (with respect to the reference) and, if such name does not exist, it repeats the attempt in a higher-level namespace. This process continues until there are no higher namespaces left. In that case you get a NameError. Builtin functions and classes reside in a special high-order namespace __builtins__. If you declare a variable named list in your module's global namespace, the interpreter will never search for that name in a higher-level namespace (that is __builtins__). Similarly, suppose you create a variable var inside a function in your module, and another variable var in the module. Then, if you reference var inside the function, you will never get the global var, because there is a var in the local namespace - the interpreter has no need to search it elsewhere.

Here is a simple illustration.

>>> example = list("abc")  # Works fine
>>> 
>>> # Creating name "list" in the global namespace of the module
>>> list = list("abc")
>>> 
>>> example = list("abc")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'list' object is not callable
>>> # Python looks for "list" and finds it in the global namespace,
>>> # but it's not the proper "list".
>>> 
>>> # Let's remove "list" from the global namespace
>>> del list
>>> # Since there is no "list" in the global namespace of the module,
>>> # Python goes to a higher-level namespace to find the name. 
>>> example = list("abc")  # It works.

So, as you see there is nothing special about Python builtins. And your case is a mere example of universal rules. You'd better use an IDE (e.g. a free version of PyCharm, or Atom with Python plugins) that highlights name shadowing to avoid such errors.

You might as well be wondering what is a "callable", in which case you can read this post. list, being a class, is callable. Calling a class triggers instance construction and initialisation. An instance might as well be callable, but list instances are not. If you are even more puzzled by the distinction between classes and instances, then you might want to read the documentation (quite conveniently, the same page covers namespaces and scoping).

If you want to know more about builtins, please read the answer by Christian Dean.

P.S. When you start an interactive Python session, you create a temporary module.

Xcode 6: Keyboard does not show up in simulator

While testing in the ios8 beta simulator, you may toggle between the "software keyboard" and "hardware keyboard" with ?+K.

UPDATE: Since iOS Simulator 8.0, the shortcut is ?+?+K.

How to "EXPIRE" the "HSET" child key in redis?

You could store key/values in Redis differently to achieve this, by just adding a prefix or namespace to your keys when you store them e.g. "hset_"

  • Get a key/value GET hset_key equals to HGET hset key

  • Add a key/value SET hset_key value equals to HSET hset key

  • Get all keys KEYS hset_* equals to HGETALL hset

  • Get all vals should be done in 2 ops, first get all keys KEYS hset_* then get the value for each key

  • Add a key/value with TTL or expire which is the topic of question:

 SET hset_key value
 EXPIRE hset_key

Note: KEYS will lookup up for matching the key in the whole database which may affect on performance especially if you have big database.

Note:

  • KEYS will lookup up for matching the key in the whole database which may affect on performance especially if you have big database. while SCAN 0 MATCH hset_* might be better as long as it doesn't block the server but still performance is an issue in case of big database.

  • You may create a new database for storing separately these keys that you want to expire especially if they are small set of keys.

Thanks to @DanFarrell who highlighted the performance issue related to KEYS

element not interactable exception in selenium web automation

I got this error because I was using a wrong CSS selector with the Selenium WebDriver Node.js function By.css().

You can check if your selector is correct by using it in the web console of your web browser (Ctrl+Shift+K shortcut), with the JavaScript function document.querySelectorAll().

java.lang.NoClassDefFoundError: org/json/JSONObject

Please add the following dependency http://mvnrepository.com/artifact/org.json/json/20080701

<dependency>
   <groupId>org.json</groupId>
   <artifactId>json</artifactId>
   <version>20080701</version>
</dependency>

Gulp command not found after install

If you're using tcsh (which is my default shell on Mac OS X), you probably just need to type rehash into the shell just after the install completes:

npm install -g gulp

followed immediately by:

rehash

Otherwise, if this is your very first time installing gulp, your shell may not recognize that there's a new executable installed -- so you either need to start a new shell, or type rehash in the current shell.

(This is basically a one-time thing for each command you install globally.)

How Do I Convert an Integer to a String in Excel VBA?

The shortest way without declaring the variable is with Type Hints :

s$ =  123   ' s = "123"
i% = "123"  ' i =  123

This will not compile with Option Explicit. The types will not be Variant but String and Integer

How can I check if the current date/time is past a set date/time?

There's also the DateTime class which implements a function for comparison operators.

// $now = new DateTime();
$dtA = new DateTime('05/14/2010 3:00PM');
$dtB = new DateTime('05/14/2010 4:00PM');

if ( $dtA > $dtB ) {
  echo 'dtA > dtB';
}
else {
  echo 'dtA <= dtB';
}

Check if checkbox is NOT checked on click - jQuery

$(document).ready(function() {
        $("#check1").click(function() {
            var checked = $(this).is(':checked');
            if (checked) {
                alert('checked');
            } else {
                alert('unchecked');
            }
        });
    });

c++ and opencv get and set pixel color to Mat

You did everything except copying the new pixel value back to the image.

This line takes a copy of the pixel into a local variable:

Vec3b color = image.at<Vec3b>(Point(x,y));

So, after changing color as you require, just set it back like this:

image.at<Vec3b>(Point(x,y)) = color;

So, in full, something like this:

Mat image = img;
for(int y=0;y<img.rows;y++)
{
    for(int x=0;x<img.cols;x++)
    {
        // get pixel
        Vec3b & color = image.at<Vec3b>(y,x);

        // ... do something to the color ....
        color[0] = 13;
        color[1] = 13;
        color[2] = 13;

        // set pixel
        //image.at<Vec3b>(Point(x,y)) = color;
        //if you copy value
    }
}

Selecting between two dates within a DateTime field - SQL Server

SELECT * 
FROM tbl 
WHERE myDate BETWEEN #date one# AND #date two#;

Setting PayPal return URL and making it auto return?

Sharing this as I've recently encountered issues similar to this thread

For a long time, my script worked well (basic payment form) and returned the POST variables to my success.php page and the IPN data as POST variables also. However, lately, I noticed the return page (success.php) was no longer receiving any POST vars. I tested in Sandbox and live and I'm pretty sure PayPal have changed something !

The notify_url still receives the correct IPN data allowing me to update DB, but I've not been able to display a success message on my return URL (success.php) page.

Despite trying many combinations to switch options on and off in PayPal website payment preferences and IPN, I've had to make some changes to my script to ensure I can still process a message. I've accomplished this by turning on PDT and Auto Return, after following this excellent guide.

Now it all works fine, but the only issue is the return URL contains all of the PDT variables which is ugly!

You may also find this helpful

You can't specify target table for update in FROM clause

MySQL doesn't allow selecting from a table and update in the same table at the same time. But there is always a workaround :)

This doesn't work >>>>

UPDATE table1 SET col1 = (SELECT MAX(col1) from table1) WHERE col1 IS NULL;

But this works >>>>

UPDATE table1 SET col1 = (SELECT MAX(col1) FROM (SELECT * FROM table1) AS table1_new) WHERE col1 IS NULL;

How to use Google fonts in React.js?

It could be the self-closing tag of link at the end, try:

<link href="https://fonts.googleapis.com/css?family=Bungee+Inline" rel="stylesheet"/> 

and in your main.css file try:

body,div {
  font-family: 'Bungee Inline', cursive;
}

printf with std::string?

The main reason is probably that a C++ string is a struct that includes a current-length value, not just the address of a sequence of chars terminated by a 0 byte. Printf and its relatives expect to find such a sequence, not a struct, and therefore get confused by C++ strings.

Speaking for myself, I believe that printf has a place that can't easily be filled by C++ syntactic features, just as table structures in html have a place that can't easily be filled by divs. As Dykstra wrote later about the goto, he didn't intend to start a religion and was really only arguing against using it as a kludge to make up for poorly-designed code.

It would be quite nice if the GNU project would add the printf family to their g++ extensions.

React js onClick can't pass value to method

There were a lot of performance considerations, all in the vacuum.
The issue with this handlers is that you need to curry them in order to incorporate the argument that you can't name in the props.
This means that the component needs a handler for each and every clickable element. Let's agree that for a few buttons this is not an issue, right?
The problem arises when you are handling tabular data with dozens of columns and thousands of rows. There you notice the impact of creating that many handlers.

The fact is, I only need one.
I set the handler at the table level (or UL or OL...), and when the click happens I can tell which was the clicked cell using data available since ever in the event object:

nativeEvent.target.tagName
nativeEvent.target.parentElement.tagName 
nativeEvent.target.parentElement.rowIndex
nativeEvent.target.cellIndex
nativeEvent.target.textContent

I use the tagname fields to check that the click happened in a valid element, for example ignore clicks in THs ot footers.
The rowIndex and cellIndex give the exact location of the clicked cell.
Textcontent is the text of the clicked cell.

This way I don't need to pass the cell's data to the handler, it can self-service it.
If I needed more data, data that is not to be displayed, I can use the dataset attribute, or hidden elements.
With some simple DOM navigation it's all at hand.
This has been used in HTML since ever, since PCs were much easier to bog.

Multiple condition in single IF statement

Yes that is valid syntax but it may well not do what you want.

Execution will continue after your RAISERROR except if you add a RETURN. So you will need to add a block with BEGIN ... END to hold the two statements.

Also I'm not sure why you plumped for severity 15. That usually indicates a syntax error.

Finally I'd simplify the conditions using IN

CREATE PROCEDURE [dbo].[AddApplicationUser] (@TenantId BIGINT,
                                            @UserType TINYINT,
                                            @UserName NVARCHAR(100),
                                            @Password NVARCHAR(100))
AS
  BEGIN
      IF ( @TenantId IS NULL
           AND @UserType IN ( 0, 1 ) )
        BEGIN
            RAISERROR('The value for @TenantID should not be null',15,1);

            RETURN;
        END
  END 

Angular js init ng-model from default values

As others pointed out, it is not good practice to initialize data on views. Initializing data on Controllers, however, is recommended. (see http://docs.angularjs.org/guide/controller)

So you can write

<input name="card[description]" ng-model="card.description">

and

$scope.card = { description: 'Visa-4242' };

$http.get('/getCardInfo.php', function(data) {
   $scope.card = data;
});

This way the views do not contain data, and the controller initializes the value while the real values are being loaded.

How to return JSon object

First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:

I would use an anonymous type filled with your results type:

string json = JsonConvert.SerializeObject(new
{
    results = new List<Result>()
    {
        new Result { id = 1, value = "ABC", info = "ABC" },
        new Result { id = 2, value = "JKL", info = "JKL" }
    }
});

Also, note that the generated JSON has result items with ids of type Number instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id to string in the C#.

I'd also tweak your results type and get rid of the backing fields:

public class Result
{
    public int id { get ;set; }
    public string value { get; set; }
    public string info { get; set; }
}

Furthermore, classes conventionally are PascalCased and not camelCased.

Here's the generated JSON from the code above:

{
  "results": [
    {
      "id": 1,
      "value": "ABC",
      "info": "ABC"
    },
    {
      "id": 2,
      "value": "JKL",
      "info": "JKL"
    }
  ]
}

Sum rows in data.frame or matrix

you can use rowSums

rowSums(data) should give you what you want.

What are the git concepts of HEAD, master, origin?

HEAD is not the latest revision, it's the current revision. Usually, it's the latest revision of the current branch, but it doesn't have to be.

master is a name commonly given to the main branch, but it could be called anything else (or there could be no main branch).

origin is a name commonly given to the main remote. remote is another repository that you can pull from and push to. Usually it's on some server, like github.

Is it possible to select the last n items with nth-child?

nth-last-child sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.

Difference between x86, x32, and x64 architectures?

x86 refers to the Intel processor architecture that was used in PCs. Model numbers were 8088 (8 bit bus version of 8086 and used in the first IBM PC), 8086, 286, 386, 486. After which they switched to names instead of numbers to stop AMD from copying the processor names. Pentium etc, never a Hexium :).

x64 is the architecture name for the extensions to the x86 instruction set that enable 64-bit code. Invented by AMD and later copied by Intel when they couldn't get their own 64-bit arch to be competitive, Itanium didn't fare well. Other names for it are x86_64, AMD's original name and commonly used in open source tools. And amd64, AMD's next name and commonly used in Microsoft tools. Intel's own names for it (EM64T and "Intel 64") never caught on.

x32 is a fuzzy term that's not associated with hardware. It tends to be used to mean "32-bit" or "32-bit pointer architecture", Linux has an ABI by that name.

SQL Server - Return value after INSERT

No need for a separate SELECT...

INSERT INTO table (name)
OUTPUT Inserted.ID
VALUES('bob');

This works for non-IDENTITY columns (such as GUIDs) too

FlutterError: Unable to load asset

My issue was nested folders.

I had my image in assets/images/logo/xyz.png and thought that - assets/images/ would catch all subfolders.

You have to explicitly add each nested subfolder

Solution: - assets/images/logo/ etc.

'No JUnit tests found' in Eclipse

It looks like you're missing the runner definition on your test class, that could be the cause:

import org.junit.runners.JUnit4;
@RunWith(JUnit4.class)
public class BallTest {
...
}

Centering floating divs within another div

With Flexbox you can easily horizontally (and vertically) center floated children inside a div.

So if you have simple markup like so:

<div class="wpr">
    <span></span>
    <span></span>
    <span></span>
    <span></span>
    <span></span>
</div>

with CSS:

.wpr
{
    width: 400px;
    height: 100px;
    background: pink;
    padding: 10px 30px;
}

.wpr span
{
    width: 50px;
    height: 50px;
    background: green;
    float: left; /* **children floated left** */
    margin: 0 5px;
}

(This is the (expected - and undesirable) RESULT)

Now add the following rules to the wrapper:

display: flex;
justify-content: center; /* align horizontal */

and the floated children get aligned center (DEMO)

Just for fun, to get vertical alignment as well just add:

align-items: center; /* align vertical */

DEMO

How to do multiple conditions for single If statement

As Hogan notes above, use an AND instead of &. See this tutorial for more info.

Check if a div does NOT exist with javascript

Try getting the element with the ID and check if the return value is null:

document.getElementById('some_nonexistent_id') === null

If you're using jQuery, you can do:

$('#some_nonexistent_id').length === 0

How to Edit a row in the datatable

If your data set is too large first select required rows by Select(). it will stop further looping.

DataRow[] selected = table.Select("Product_id = 2")

Then loop through subset and update

    foreach (DataRow row in selected)
    {
        row["Product_price"] = "<new price>";
    }

iframe refuses to display

The reason for the error is that the host server for https://cw.na1.hgncloud.com has provided some HTTP headers to protect the document. One of which is that the frame ancestors must be from the same domain as the original content. It seems you are attempting to put the iframe at a domain location that is not the same as the content of the iframe - thus violating the Content Security Policy that the host has set.

Check out this link on Content Security Policy for more details.

How to enter a multi-line command

I just found out that there must not be any character between the back tick and the line break. Even whitespace will cause the command to not work.

global variable for all controller and views

You can also use Laravel helper which I'm using. Just create Helpers folder under App folder then add the following code:

namespace App\Helpers;
Use SettingModel;
class SiteHelper
{
    public static function settings()
    {
        if(null !== session('settings')){
          $settings = session('settings');
        }else{
          $settings = SettingModel::all();
          session(['settings' => $settings]);
        }
        return $settings;
    }
}

then add it on you config > app.php under alliases

'aliases' => [
....
'Site' => App\Helpers\SiteHelper::class,
]

1. To Use in Controller

use Site;
class SettingsController extends Controller
{
    public function index()
    {
        $settings = Site::settings();
        return $settings;
    }
}

2. To Use in View:

Site::settings()

C++ vector's insert & push_back difference

Beside the fact, that push_back(x) does the same as insert(x, end()) (maybe with slightly better performance), there are several important thing to know about these functions:

  1. push_back exists only on BackInsertionSequence containers - so, for example, it doesn't exist on set. It couldn't because push_back() grants you that it will always add at the end.
  2. Some containers can also satisfy FrontInsertionSequence and they have push_front. This is satisfied by deque, but not by vector.
  3. The insert(x, ITERATOR) is from InsertionSequence, which is common for set and vector. This way you can use either set or vector as a target for multiple insertions. However, set has additionally insert(x), which does practically the same thing (this first insert in set means only to speed up searching for appropriate place by starting from a different iterator - a feature not used in this case).

Note about the last case that if you are going to add elements in the loop, then doing container.push_back(x) and container.insert(x, container.end()) will do effectively the same thing. However this won't be true if you get this container.end() first and then use it in the whole loop.

For example, you could risk the following code:

auto pe = v.end();
for (auto& s: a)
    v.insert(pe, v);

This will effectively copy whole a into v vector, in reverse order, and only if you are lucky enough to not get the vector reallocated for extension (you can prevent this by calling reserve() first); if you are not so lucky, you'll get so-called UndefinedBehavior(tm). Theoretically this isn't allowed because vector's iterators are considered invalidated every time a new element is added.

If you do it this way:

copy(a.begin(), a.end(), back_inserter(v);

it will copy a at the end of v in the original order, and this doesn't carry a risk of iterator invalidation.

[EDIT] I made previously this code look this way, and it was a mistake because inserter actually maintains the validity and advancement of the iterator:

copy(a.begin(), a.end(), inserter(v, v.end());

So this code will also add all elements in the original order without any risk.

How can you create multiple cursors in Visual Studio Code

There is no binding for exactly what you want.

The only thing that comes close is Ctrl+F2 which will select all of them at once.

You can bind it to Ctrl+D doing the following:

  • Click on File > Preferences > Keyboard Shortcuts
    You should see a pane full of the current bindings and on the right a list of custom bindings
  • In the current bindings, search for Ctrl+F2 and copy that whole line and paste it into the right pane.
  • You might have to remove the comma at the end and then change Ctrl+F2 to Ctrl+D and then save the file.

It should look something like this:

// Place your key bindings in this file to overwrite the defaults
[
{ "key": "ctrl+d",               "command": "editor.action.changeAll",
                                    "when": "editorTextFocus" }
]

JavaFX Application Icon

I used this in my application

Image icon = new Image(getClass().getResourceAsStream("icon.png"));
window.getIcons().add(icon);

Here window is the stage.

How do you detect/avoid Memory leaks in your (Unmanaged) code?

I'd like to offer something I've used at times in the past: a rudimentary leak checker which is source level and fairly automatic. I'm giving this away for three reasons:

  1. You might find it useful.

  2. Though it's a bit krufty, I don't let that embarass me.

  3. Even though it's tied to some win32 hooks, that should be easy to alleviate.

There are things of which you must be careful when using it: don't do anything that needs to lean on new in the underlying code, beware of the warnings about cases it might miss at the top of leakcheck.cpp, realize that if you turn on (and fix any issues with) the code that does image dumps, you may generate a huge file.

The design is meant to allow you to turn the checker on and off without recompiling everything that includes its header. Include leakcheck.h where you want to track checking and rebuild once. Thereafter, compile leakcheck.cpp with or without LEAKCHECK #define'd and then relink to turn it on and off. Including unleakcheck.h will turn it off locally in a file. Two macros are provided: CLEARALLOCINFO() will avoid reporting the same file and line inappropriately when you traverse allocating code that didn't include leakcheck.h. ALLOCFENCE() just drops a line in the generated report without doing any allocation.

Again, please realize that I haven't used this in a while and you may have to work with it a bit. I'm dropping it in to illustrate the idea. If there turns out to be sufficient interest, I'd be willing to work up an example, updating the code in the process, and replace the contents of the following URL with something nicer that includes a decently syntax-colored listing.

You can find it here: http://www.cse.ucsd.edu/~tkammeye/leakcheck.html

How to change the floating label color of TextInputLayout

Found the answer, use android.support.design:hintTextAppearance attribute to set your own floating label appearance.

Example:

<android.support.design.widget.TextInputLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:hintTextAppearance="@style/TextAppearance.AppCompat">

    <EditText
        android:id="@+id/password"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="@string/prompt_password"/>
</android.support.design.widget.TextInputLayout>

Reading specific XML elements from XML file

XDocument xdoc = XDocument.Load(path_to_xml);
var word = xdoc.Elements("word")
               .SingleOrDefault(w => (string)w.Element("category") == "verb");

This query will return whole word XElement. If there is more than one word element with category verb, than you will get an InvalidOperationException. If there is no elements with category verb, result will be null.

How do you post data with a link

I would just use a value in the querystring to pass the required information to the next page.

How to Deserialize XML document

See if this helps:

[Serializable()]
[System.Xml.Serialization.XmlRootAttribute("Cars", Namespace = "", IsNullable = false)]
public class Cars
{
    [XmlArrayItem(typeof(Car))]
    public Car[] Car { get; set; }
}

.

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement()]
    public string StockNumber{ get; set; }

    [System.Xml.Serialization.XmlElement()]
    public string Make{ get; set; }

    [System.Xml.Serialization.XmlElement()]
    public string Model{ get; set; }
}

And failing that use the xsd.exe program that comes with visual studio to create a schema document based on that xml file, and then use it again to create a class based on the schema document.

Error handling in getJSON calls

Why not

getJSON('get.php',{cmd:"1", typeID:$('#typesSelect')},function(data) {
    // ...
});

function getJSON(url,params,callback) {
    return $.getJSON(url,params,callback)
        .fail(function(jqXMLHttpRequest,textStatus,errorThrown) {
            console.dir(jqXMLHttpRequest);
            alert('Ajax data request failed: "'+textStatus+':'+errorThrown+'" - see javascript console for details.');
        })
}

??

For details on the used .fail() method (jQuery 1.5+), see http://api.jquery.com/jQuery.ajax/#jqXHR

Since the jqXHR is returned by the function, a chaining like

$.when(getJSON(...)).then(function() { ... });

is possible.

Styling twitter bootstrap buttons

In Twitter Bootstrap bootstrap 3.0.0, Twitter button is flat. You can customize it from http://getbootstrap.com/customize. Button color, border radious etc.

Also you can find the HTML code and others functionality http://twitterbootstrap.org/bootstrap-css-buttons.

Bootstrap 2.3.2 button is gradient but 3.0.0 ( new release ) flat and looks more cool.

and also you can find to customize the entire bootstrap looks and style form this resources: http://twitterbootstrap.org/top-5-customizing-bootstrap-resources/

How to connect Android app to MySQL database?

Android does not support MySQL out of the box. The "normal" way to access your database would be to put a Restful server in front of it and use the HTTPS protocol to connect to the Restful front end.

Have a look at ContentProvider. It is normally used to access a local database (SQLite) but it can be used to get data from any data store.

I do recommend that you look at having a local copy of all/some of your websites data locally, that way your app will still work when the Android device hasn't got a connection. If you go down this route then a service can be used to keep the two databases in sync.

How to disable Compatibility View in IE

The answer given by FelixFett worked for me. To reiterate:

<meta http-equiv="X-UA-Compatible" content="IE=11; IE=10; IE=9; IE=8; IE=7; IE=EDGE" />

I have it as the first 'meta' tag in my code. I added 10 and 11 as those are versions that are published now for Internet Explorer.

I would've just commented on his answer but I do not have a high enough reputation...

Environment.GetFolderPath(...CommonApplicationData) is still returning "C:\Documents and Settings\" on Vista

I was looking for a listing of macOS but found nothing, maybe this helps someone.

Output on macOS Catalina (10.15.7) using net5.0

# SpecialFolders (Only with value)
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.System: /System
SpecialFolder.UserProfile: /Users/$USER

# SpecialFolders (All)
SpecialFolder.AdminTools: 
SpecialFolder.ApplicationData: /Users/$USER/.config
SpecialFolder.CDBurning: 
SpecialFolder.CommonAdminTools: 
SpecialFolder.CommonApplicationData: /usr/share
SpecialFolder.CommonDesktopDirectory: 
SpecialFolder.CommonDocuments: 
SpecialFolder.CommonMusic: 
SpecialFolder.CommonOemLinks: 
SpecialFolder.CommonPictures: 
SpecialFolder.CommonProgramFiles: 
SpecialFolder.CommonProgramFilesX86: 
SpecialFolder.CommonPrograms: 
SpecialFolder.CommonStartMenu: 
SpecialFolder.CommonStartup: 
SpecialFolder.CommonTemplates: 
SpecialFolder.CommonVideos: 
SpecialFolder.Cookies: 
SpecialFolder.Desktop: /Users/$USER/Desktop
SpecialFolder.DesktopDirectory: /Users/$USER/Desktop
SpecialFolder.Favorites: /Users/$USER/Library/Favorites
SpecialFolder.Fonts: /Users/$USER/Library/Fonts
SpecialFolder.History: 
SpecialFolder.InternetCache: /Users/$USER/Library/Caches
SpecialFolder.LocalApplicationData: /Users/$USER/.local/share
SpecialFolder.LocalizedResources: 
SpecialFolder.MyComputer: 
SpecialFolder.MyDocuments: /Users/$USER
SpecialFolder.MyMusic: /Users/$USER/Music
SpecialFolder.MyPictures: /Users/$USER/Pictures
SpecialFolder.MyVideos: 
SpecialFolder.NetworkShortcuts: 
SpecialFolder.PrinterShortcuts: 
SpecialFolder.ProgramFiles: /Applications
SpecialFolder.ProgramFilesX86: 
SpecialFolder.Programs: 
SpecialFolder.Recent: 
SpecialFolder.Resources: 
SpecialFolder.SendTo: 
SpecialFolder.StartMenu: 
SpecialFolder.Startup: 
SpecialFolder.System: /System
SpecialFolder.SystemX86: 
SpecialFolder.Templates: 
SpecialFolder.UserProfile: /Users/$USER
SpecialFolder.Windows: 

I have replaced my username with $USER.

Code Snippet from pogosama.

foreach(Environment.SpecialFolder f in Enum.GetValues(typeof(Environment.SpecialFolder)))
{
    string commonAppData = Environment.GetFolderPath(f);
    Console.WriteLine("{0}: {1}", f, commonAppData);
}
Console.ReadLine();

ImportError: DLL load failed: %1 is not a valid Win32 application

This error can also appear when python versions are mixed:

For example if any of the DLL to be loaded has been compiled using python 2.7.16 and you try to import with python 2.7.15 this error ImportError: DLL load failed: %1 is not a valid Win32 application. is thrown.

This is at least what I've found to be the problem in my case.

How to use regex with find command?

Try to use single quotes (') to avoid shell escaping of your string. Remember that the expression needs to match the whole path, i.e. needs to look like:

 find . -regex '\./[a-f0-9-]*.jpg'

Apart from that, it seems that my find (GNU 4.4.2) only knows basic regular expressions, especially not the {36} syntax. I think you'll have to make do without it.

Limiting the number of characters per line with CSS

Depending on what font you're using you can set max-width on the paragraph with a calculated value. It will not be exact, but I've found that in most cases that does not matter.

p {
  max-width: calc(30em * 0.5);
}

The number you multiply with depends on what font it is, and how much a character takes up in a em square. More characters = less accurate.

Error related to only_full_group_by when executing a query in MySql

I will try to explain you what this error is about.
Starting from MySQL 5.7.5, option ONLY_FULL_GROUP_BY is enabled by default.
Thus, according to standart SQL92 and earlier:

does not permit queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on (uniquely determined by) GROUP BY columns

(read more in docs)

So, for example:

SELECT * FROM `users` GROUP BY `name`;

You will get error message after executing query above.

#1055 - Expression #1 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'testsite.user.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

Why?
Because MySQL dont exactly understand, what certain values from grouped records to retrieve, and this is the point.

I.E. lets say you have this records in your users table:
Yo

And you will execute invalid query showen above.
And you will get error shown above, because, there is 3 records with name John, and it is nice, but, all of them have different email field values.
So, MySQL simply don't understand which of them to return in resulting grouped record.

You can fix this issue, by simply changing your query like this:

SELECT `name` FROM `users` GROUP BY `name`

Also, you may want to add more fields to SELECT section, but you cant do that, if they are not aggregated, but there is crutch you could use (but highly not reccomended):

SELECT ANY_VALUE(`id`), ANY_VALUE(`email`), `name` FROM `users` GROUP BY `name`

enter image description here

Now, you may ask, why using ANY_VALUE is highly not recommended?
Because MySQL don't exactly know what value of grouped records to retrieve, and by using this function, you asking it to fetch any of them (in this case, email of first record with name = John was fetched).
Exactly I cant come up with any ideas on why you would want this behaviour to exist.

Please, if you dont understand me, read more about how grouping in MySQL works, it is very simple.

And by the end, here is one more simple, yet valid query.
If you want to query total users count according to available ages, you may want to write down this query

SELECT `age`, COUNT(`age`) FROM `users` GROUP BY `age`;

Which is fully valid, according to MySQL rules.
And so on.

It is important to understand what exactly the problem is and only then write down the solution.

Initialization of an ArrayList in one line

Collections.singletonList(messageBody)

If you'd need to have a list of one item!

Collections is from java.util package.

What is the best alternative IDE to Visual Studio

Zeus.

Here's an example showing code completion, taken from the Zeus homepage.

example.cs open in Zeus, showing code-completion

Assign one struct to another in C

Yes, assignment is supported for structs. However, there are problems:

struct S {
   char * p;
};

struct S s1, s2;
s1.p = malloc(100);
s2 = s1;

Now the pointers of both structs point to the same block of memory - the compiler does not copy the pointed to data. It is now difficult to know which struct instance owns the data. This is why C++ invented the concept of user-definable assignment operators - you can write specific code to handle this case.

Arrays with different datatypes i.e. strings and integers. (Objectorientend)

Notice the repetition of Book in Booknumber (int), Booktitle (string), Booklanguage (string), Bookprice (int)- it screams for a class type.

class Book {
  int number;
  String title;
  String language;
  int price;
}

Now you can simply have:

Book[] books = new Books[3];

If you want arrays, you can declare it as object array an insert Integer and String into it:

Object books[3][4]

Is Laravel really this slow?

Since nobody else has mentioned it, I found that the xdebug debugger dramatically increased the time. I served a basic "Hello World, the time is 2020-01-01T01:01:01.010101" dynamic page and used this in my httpd.conf to time the request:

LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" **%T/%D**" combined

%T is the serve time in seconds, %D is the time in microseconds. With this in my php.ini:

[XDebug]
xdebug.remote_autostart = 1
xdebug.remote_enable = 1

I was getting around 770ms response times, but with both of those set to 0 to disable them, it jumped to 160ms instantly. Running both of these brought it down to 120ms:

php artisan route:cache
php artisan config:cache

The downside being that if I made config or route changes, I would need to re-cache them, which is annoying.

As a sidenote, oddly, moving the site from my SSD to a spinning HDD provided no performance benefits, which is super odd to me, but I suppose it's maybe cached, I'm on Windows 10 with XAMPP.

How to play only the audio of a Youtube video using HTML 5?

I agree with Tom van der Woerdt. You could use CSS to hide the video (visibility:hidden or overflow:hidden in a div wrapper constrained by height), but that may violate Youtube's policies. Additionally, how could you control the audio (pause, stop, volume, etc.)?

You could instead turn to resources such as http://www.houndbite.com/ to manage audio.

How to wrap text using CSS?

With text-wrap, browser support is relatively weak (as you might expect from from a draft spec).

You are better off taking steps to ensure the data doesn't have long strings of non-white-space.

CSS to line break before/after a particular `inline-block` item

You are not interested in a lot of "solutions" to your problem. I do not think there really is a good way to do what you want to do. Anything you insert using :after and content has exactly the same syntactic and semantic validity it would have done if you had just written it in there yourself.

The tools CSS provide work. You should just float the lis and then clear: left when you want to start a new line, as you have mentioned:

See an example: http://jsfiddle.net/marcuswhybrow/YMN7U/5/

VB.net Need Text Box to Only Accept Numbers

This is what I did in order to handle both key entry and copy/paste.

Private Sub TextBox_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox.KeyPress
    If Not Char.IsNumber(e.KeyChar) AndAlso Not Char.IsControl(e.KeyChar) Then
        e.Handled = True
    End If
End Sub

Private Sub TextBox_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox.TextChanged
    Dim digitsOnly As Regex = New Regex("[^\d]")
    TextBox.Text = digitsOnly.Replace(TextBox.Text, "")
End Sub

If you want to allow decimals and negative amount, add

AndAlso Not e.KeyChar = "." AndAlso Not e.keyChar = "-"

to the if statement in the KeyPress section.

How do I tell if an object is a Promise?

const isPromise = (value) => {
  return !!(
    value &&
    value.then &&
    typeof value.then === 'function' &&
    value?.constructor?.name === 'Promise'
  )
}

As for me - this check is better, try it out

Angular2 - Radio Button Binding

Here is the best way to use radio buttons in Angular2. There is no need to use the (click) event or a RadioControlValueAccessor to change the binded property value, setting [checked] property does the trick.

<input name="options" type="radio" [(ngModel)]="model.options" [value]="1"
       [checked]="model.options==1" /><br/>
<input name="options" type="radio"  [(ngModel)]="model.options" [value]="2"
       [checked]="model.options==2" /><br/>

I published an example of using radio buttons: Angular 2: how to create radio buttons from enum and add two-way binding? It works from at least Angular 2 RC5.

Reading CSV files using C#

My experience is that there are many different csv formats. Specially how they handle escaping of quotes and delimiters within a field.

These are the variants I have ran into:

  • quotes are quoted and doubled (excel) i.e. 15" -> field1,"15""",field3
  • quotes are not changed unless the field is quoted for some other reason. i.e. 15" -> field1,15",fields3
  • quotes are escaped with \. i.e. 15" -> field1,"15\"",field3
  • quotes are not changed at all (this is not always possible to parse correctly)
  • delimiter is quoted (excel). i.e. a,b -> field1,"a,b",field3
  • delimiter is escaped with \. i.e. a,b -> field1,a\,b,field3

I have tried many of the existing csv parsers but there is not a single one that can handle the variants I have ran into. It is also difficult to find out from the documentation which escaping variants the parsers support.

In my projects I now use either the VB TextFieldParser or a custom splitter.

NullPointerException in Java with no StackTrace

When you are using AspectJ in your project, it may happen that some aspect hides its portion of the stack trace. For example, today I had:

java.lang.NullPointerException:
  at com.company.product.MyTest.test(MyTest.java:37)

This stack trace was printed when running the test via Maven's surefire.

On the other hand, when running the test in IntelliJ, a different stack trace was printed:

java.lang.NullPointerException
  at com.company.product.library.ArgumentChecker.nonNull(ArgumentChecker.java:67)
  at ...
  at com.company.product.aspects.CheckArgumentsAspect.wrap(CheckArgumentsAspect.java:82)
  at ...
  at com.company.product.MyTest.test(MyTest.java:37)

What is the regex pattern for datetime (2008-09-01 12:35:45 )?

Here is my solution:

[12]\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01]) ([01][0-9]|2[0-3]):[0-5]\d

Regular expression visualization

Debuggex Demo

https://regex101.com/r/lbthaT/4

Can you force Visual Studio to always run as an Administrator in Windows 8?

After looking on Super User I found this question which explains how to do this with the shortcut on the start screen. Similarly you can do the same when Visual Studio is pinned to the task bar. In either location:

  1. Right click the Visual Studio icon
  2. Go to Properties
  3. Under the Shortcut tab select Advanced
  4. Check Run as administrator

setting default operation in admin mode

Unlike in Windows 7 this only works if you launch the application from the shortcut you changed. After updating both Visual Studio shortcuts it seems to also work when you open a solution file from Explorer.

Update Warning: It looks like one of the major flaws in running Visual Studio with elevated permissions is since Explorer isn't running with them as well you can't drag and drop files into Visual Studio for editing. You need to open them through the file open dialog. Nor can you double click any file associated to Visual Studio and have it open in Visual Studio (aside from solutions it seems) because you'll get an error message saying There was a problem sending the command to the program. Once I uncheck to always start with elevated permissions (using VSCommands) then I'm able to open files directly and drop them into an open instance of Visual Studio.

Update For The Daring: Despite there being no UI to turn off UAC like in the past, that I saw at least, you can still do so through the registry. The key to edit is:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
EnableLUA - DWORD 1-Enabled, 0-Disabled

After changing this Windows will prompt you to restart. Once restarted you'll be back to everything running with admin permissions if you're an admin. The issues I reported above are now gone as well.

Change bundle identifier in Xcode when submitting my first app in IOS

View this picture to see how you can change the bundle identifier

Explanation:

  1. Select your project form the leftmost project navigator
  2. Under the General Tab, there is a section called Targets inside where you will see the name of your project. Click on the name.
  3. Then you will be able to see the bundle identifier which you can change as below:

As you can see in the picture, the name of my App is PracticeApp. And my bundle identifier is: com.hello500.PracticeApp

In this case, You can change hello500 to change the bundle identifier of the app.

Excel VBA to Export Selected Sheets to PDF

I'm pretty mixed up on this. I am also running Excel 2010. I tried saving two sheets as a single PDF using:

    ThisWorkbook.Sheets(Array(1,2)).Select
    **Selection**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False

but I got nothing but blank pages. It saved both sheets, but nothing on them. It wasn't until I used:

    ThisWorkbook.Sheets(Array(1,2)).Select
    **ActiveSheet**.ExportAsFixedFormat xlTypePDF, FileName & ".pdf", , , False

that I got a single PDF file with both sheets.

I tried manually saving these two pages using Selection in the Options dialog to save the two sheets I had selected, but got blank pages. When I tried the Active Sheet(s) option, I got what I wanted. When I recorded this as a macro, Excel used ActiveSheet when it successfully published the PDF. What gives?

Fixed position but relative to container

I had to do this with an advertisement that my client wanted to sit outside of the content area. I simply did the following and it worked like a charm!

<div id="content" style="position:relative; width:750px; margin:0 auto;">
  <div id="leftOutsideAd" style="position:absolute; top:0; left:-150px;">
    <a href="#" style="position:fixed;"><img src="###" /></a>
  </div>
</div>

Convert Unix timestamp into human readable date using MySQL

What's missing from the other answers (as of this writing) and not directly obvious is that from_unixtime can take a second parameter to specify the format like so:

SELECT
  from_unixtime(timestamp, '%Y %D %M %H:%i:%s')
FROM 
  your_table

How to extract text from the PDF document?

I know that this topic is quite old, but this need is still alive. I read many documents, forum and script and build a new advanced one which supports compressed and uncompressed pdf :

https://gist.github.com/smalot/6183152

Hope it helps everone

How to call multiple JavaScript functions in onclick event?

This is the code required if you're using only JavaScript and not jQuery

var el = document.getElementById("id");
el.addEventListener("click", function(){alert("click1 triggered")}, false);
el.addEventListener("click", function(){alert("click2 triggered")}, false);

Batch script to find and replace a string in text file without creating an extra output file for storing the modified file

@echo off 
    setlocal enableextensions disabledelayedexpansion

    set "search=%1"
    set "replace=%2"

    set "textFile=Input.txt"

    for /f "delims=" %%i in ('type "%textFile%" ^& break ^> "%textFile%" ') do (
        set "line=%%i"
        setlocal enabledelayedexpansion
        >>"%textFile%" echo(!line:%search%=%replace%!
        endlocal
    )

for /f will read all the data (generated by the type comamnd) before starting to process it. In the subprocess started to execute the type, we include a redirection overwritting the file (so it is emptied). Once the do clause starts to execute (the content of the file is in memory to be processed) the output is appended to the file.

What are advantages of Artificial Neural Networks over Support Vector Machines?

Judging from the examples you provide, I'm assuming that by ANNs, you mean multilayer feed-forward networks (FF nets for short), such as multilayer perceptrons, because those are in direct competition with SVMs.

One specific benefit that these models have over SVMs is that their size is fixed: they are parametric models, while SVMs are non-parametric. That is, in an ANN you have a bunch of hidden layers with sizes h1 through hn depending on the number of features, plus bias parameters, and those make up your model. By contrast, an SVM (at least a kernelized one) consists of a set of support vectors, selected from the training set, with a weight for each. In the worst case, the number of support vectors is exactly the number of training samples (though that mainly occurs with small training sets or in degenerate cases) and in general its model size scales linearly. In natural language processing, SVM classifiers with tens of thousands of support vectors, each having hundreds of thousands of features, is not unheard of.

Also, online training of FF nets is very simple compared to online SVM fitting, and predicting can be quite a bit faster.

EDIT: all of the above pertains to the general case of kernelized SVMs. Linear SVM are a special case in that they are parametric and allow online learning with simple algorithms such as stochastic gradient descent.

Override back button to act like home button

try to override void onBackPressed() defined in android.app.Activity class.

Limiting Powershell Get-ChildItem by File Creation Date Range

Use Where-Object and test the $_.CreationTime:

Get-ChildItem 'PATH' -recurse -include @("*.tif*","*.jp2","*.pdf") | 
    Where-Object { $_.CreationTime -ge "03/01/2013" -and $_.CreationTime -le "03/31/2013" }

Undefined symbols for architecture i386

A bit late to the party but might be valuable to someone with this error..

I just straight copied a bunch of files into an Xcode project, if you forget to add them to your projects Build Phases you will get the error "Undefined symbols for architecture i386". So add your implementation files to Compile Sources, and Xib files to Copy Bundle Resources.

The error was telling me that there was no link to my classes simply because they weren't included in the Compile Sources, quite obvious really but may save someone a headache.

Which encoding opens CSV files correctly with Excel on both Mac and Windows?

instead of csv, trying outputting html with an XLS extension and "application/excel" mime-type. I know this will work in Windows, but can't speak for MacOS

Convert list of dictionaries to a pandas DataFrame

You can also use pd.DataFrame.from_dict(d) as :

In [8]: d = [{'points': 50, 'time': '5:00', 'year': 2010}, 
   ...: {'points': 25, 'time': '6:00', 'month': "february"}, 
   ...: {'points':90, 'time': '9:00', 'month': 'january'}, 
   ...: {'points_h1':20, 'month': 'june'}]

In [12]: pd.DataFrame.from_dict(d)
Out[12]: 
      month  points  points_h1  time    year
0       NaN    50.0        NaN  5:00  2010.0
1  february    25.0        NaN  6:00     NaN
2   january    90.0        NaN  9:00     NaN
3      june     NaN       20.0   NaN     NaN

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

Why do abstract classes in Java have constructors?

I guess root of this question is that people believe that a call to a constructor creates the object. That is not the case. Java nowhere claims that a constructor call creates an object. It just does what we want constructor to do, like initialising some fields..that's all. So an abstract class's constructor being called doesn't mean that its object is created.

Proper way to catch exception from JSON.parse

We can check error & 404 statusCode, and use try {} catch (err) {}.

You can try this :

_x000D_
_x000D_
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
    if (req.status == 404) {_x000D_
        console.log("404");_x000D_
        return false;_x000D_
    }_x000D_
_x000D_
    if (!(req.readyState == 4 && req.status == 200))_x000D_
        return false;_x000D_
_x000D_
    const json = (function(raw) {_x000D_
        try {_x000D_
            return JSON.parse(raw);_x000D_
        } catch (err) {_x000D_
            return false;_x000D_
        }_x000D_
    })(req.responseText);_x000D_
_x000D_
    if (!json)_x000D_
        return false;_x000D_
_x000D_
    document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
_x000D_
_x000D_

Read more :

Why does ASP.NET webforms need the Runat="Server" attribute?

If you use it on normal html tags, it means that you can programatically manipulate them in event handlers etc, eg change the href or class of an anchor tag on page load... only do that if you have to, because vanilla html tags go faster.

As far as user controls and server controls, no, they just wont work without them, without having delved into the innards of the aspx preprocessor, couldn't say exactly why, but would take a guess that for probably good reasons, they just wrote the parser that way, looking for things explicitly marked as "do something".

If @JonSkeet is around anywhere, he will probably be able to provide a much better answer.

C multi-line macro: do/while(0) vs scope block

Andrey Tarasevich provides the following explanation:

  1. On Google Groups
  2. On bytes.com

[Minor changes to formatting made. Parenthetical annotations added in square brackets []].

The whole idea of using 'do/while' version is to make a macro which will expand into a regular statement, not into a compound statement. This is done in order to make the use of function-style macros uniform with the use of ordinary functions in all contexts.

Consider the following code sketch:

if (<condition>)
  foo(a);
else
  bar(a);

where foo and bar are ordinary functions. Now imagine that you'd like to replace function foo with a macro of the above nature [named CALL_FUNCS]:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

Now, if your macro is defined in accordance with the second approach (just { and }) the code will no longer compile, because the 'true' branch of if is now represented by a compound statement. And when you put a ; after this compound statement, you finished the whole if statement, thus orphaning the else branch (hence the compilation error).

One way to correct this problem is to remember not to put ; after macro "invocations":

if (<condition>)
  CALL_FUNCS(a)
else
  bar(a);

This will compile and work as expected, but this is not uniform. The more elegant solution is to make sure that macro expand into a regular statement, not into a compound one. One way to achieve that is to define the macro as follows:

#define CALL_FUNCS(x) \
do { \
  func1(x); \
  func2(x); \
  func3(x); \
} while (0)

Now this code:

if (<condition>)
  CALL_FUNCS(a);
else
  bar(a);

will compile without any problems.

However, note the small but important difference between my definition of CALL_FUNCS and the first version in your message. I didn't put a ; after } while (0). Putting a ; at the end of that definition would immediately defeat the entire point of using 'do/while' and make that macro pretty much equivalent to the compound-statement version.

I don't know why the author of the code you quoted in your original message put this ; after while (0). In this form both variants are equivalent. The whole idea behind using 'do/while' version is not to include this final ; into the macro (for the reasons that I explained above).

Rounding a number to the nearest 5 or 10 or X

To mimic in Visual Basic the way the round function works in Excel, you just have to use: WorksheetFunction.Round(number, decimals)

This way the banking or accounting rounding don't do the rounding.

Notepad++: Multiple words search in a file (may be in different lines)?

You need a new version of notepad++. Looks like old versions don't support |.

Note: egrep "CAT|TOWN" will search for lines containing CATOWN. (CAT)|(TOWN) is the proper or extension (matching 1,3,4). Strangely you wrote and which is btw (CAT.*TOWN)|(TOWN.*CAT)

Python: TypeError: object of type 'NoneType' has no len()

You don't need to assign names to list or [] or anything else until you wish to use it.

It's neater to use a list comprehension to make the list of names.

shuffle modifies the list you pass to it. It always returns None

If you are using a context manager (with ...) you don't need to close the file explicitly

from random import shuffle

with open('names') as f:
    names = [name.rstrip() for name in f if not name.isspace()]
    shuffle(names)

assert len(names) > 100

Can the Unix list command 'ls' output numerical chmod permissions?

Closest I can think of (keeping it simple enough) is stat, assuming you know which files you're looking for. If you don't, * can find most of them:

/usr/bin$ stat -c '%a %n' *
755 [
755 a2p
755 a2ps
755 aclocal
...

It handles sticky, suid and company out of the box:

$ stat -c '%a %n' /tmp /usr/bin/sudo
1777 /tmp
4755 /usr/bin/sudo

How to check if BigDecimal variable == 0 in java?

You would want to use equals() since they are objects, and utilize the built in ZERO instance:

if (selectPrice.equals(BigDecimal.ZERO))

Note that .equals() takes scale into account, so unless selectPrice is the same scale (0) as .ZERO then this will return false.

To take scale out of the equation as it were:

if (selectPrice.compareTo(BigDecimal.ZERO) == 0)

I should note that for certain mathematical situations, 0.00 != 0, which is why I imagine .equals() takes the scale into account. 0.00 gives precision to the hundredths place, whereas 0 is not that precise. Depending on the situation you may want to stick with .equals().

Combine hover and click functions (jQuery)?

You could also use bind:

$('#myelement').bind('click hover', function yourCommonHandler (e) {
   // Your handler here
});

Resolve build errors due to circular dependency amongst classes

Here is the solution for templates: How to handle circular dependencies with templates

The clue to solving this problem is to declare both classes before providing the definitions (implementations). It’s not possible to split the declaration and definition into separate files, but you can structure them as if they were in separate files.

Java getting the Enum name given the Enum Value

You should replace your getEnumNameForValue by a call to the name() method.

Check if a input box is empty

Quite simple:

<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>

You could also use ng-hide="somefield.length" instead of ng-show="!somefield.length" if that reads more naturally for you.


A better alternative might be to really take advantage of the form abilities of Angular:

<form name="myform">
  <input name="myfield" ng-model="somefield" ng-minlength="5" required>
  <span ng-show="myform.myfield.$error.required">Please enter something!</span>
  <span ng-show="!myform.myfield.$error.required">Good boy!</span>
</form> 

Updated Plnkr here.

File size exceeds configured limit (2560000), code insight features not available

Edit config file for IDEA: IDEA_HOME/bin/idea.properties

# Maximum file size (kilobytes) IDE should provide code assistance for.
idea.max.intellisense.filesize=60000

# Maximum file size (kilobytes) IDE is able to open.
idea.max.content.load.filesize=60000

Save and restart IDEA

How to `wget` a list of URLs in a text file?

If you're on OpenWrt or using some old version of wget which doesn't gives you -i option:

#!/bin/bash
input="text_file.txt"
while IFS= read -r line
do
  wget $line
done < "$input"

Furthermore, if you don't have wget, you can use curl or whatever you use for downloading individual files.

Evenly distributing n points on a sphere

This works and it's deadly simple. As many points as you want:

    private function moveTweets():void {


        var newScale:Number=Scale(meshes.length,50,500,6,2);
        trace("new scale:"+newScale);


        var l:Number=this.meshes.length;
        var tweetMeshInstance:TweetMesh;
        var destx:Number;
        var desty:Number;
        var destz:Number;
        for (var i:Number=0;i<this.meshes.length;i++){

            tweetMeshInstance=meshes[i];

            var phi:Number = Math.acos( -1 + ( 2 * i ) / l );
            var theta:Number = Math.sqrt( l * Math.PI ) * phi;

            tweetMeshInstance.origX = (sphereRadius+5) * Math.cos( theta ) * Math.sin( phi );
            tweetMeshInstance.origY= (sphereRadius+5) * Math.sin( theta ) * Math.sin( phi );
            tweetMeshInstance.origZ = (sphereRadius+5) * Math.cos( phi );

            destx=sphereRadius * Math.cos( theta ) * Math.sin( phi );
            desty=sphereRadius * Math.sin( theta ) * Math.sin( phi );
            destz=sphereRadius * Math.cos( phi );

            tweetMeshInstance.lookAt(new Vector3D());


            TweenMax.to(tweetMeshInstance, 1, {scaleX:newScale,scaleY:newScale,x:destx,y:desty,z:destz,onUpdate:onLookAtTween, onUpdateParams:[tweetMeshInstance]});

        }

    }
    private function onLookAtTween(theMesh:TweetMesh):void {
        theMesh.lookAt(new Vector3D());
    }

React Native: Possible unhandled promise rejection

delete build folder projectfile\android\app\build and run project

How to check object is nil or not in swift?

Swift-5 Very Simple Way

//MARK:- In my case i have an array so i am checking the object in this
    for object in yourArray {
        if object is NSNull {
            print("Hey, it's null!")

        }else if object is String {
            print("Hey, it's String!")

        }else if object is Int {
            print("Hey, it's Int!")

        }else if object is yourChoice {
            print("Hey, it's yourChoice!")

        }
        else {
            print("It's not null, not String, not yourChoice it's \(object)")
        }
    }

How to get df linux command output always in GB

You can use the -B option.

Man page of df:

-B, --block-size=SIZE use SIZE-byte blocks

All together,

df -BG

Can an Option in a Select tag carry multiple values?

Duplicate tag parameters are not allowed in HTML. What you could do, is VALUE="1,2010". But you would have to parse the value on the server.

Pandas DataFrame column to list

I'd like to clarify a few things:

  1. As other answers have pointed out, the simplest thing to do is use pandas.Series.tolist(). I'm not sure why the top voted answer leads off with using pandas.Series.values.tolist() since as far as I can tell, it adds syntax/confusion with no added benefit.
  2. tst[lookupValue][['SomeCol']] is a dataframe (as stated in the question), not a series (as stated in a comment to the question). This is because tst[lookupValue] is a dataframe, and slicing it with [['SomeCol']] asks for a list of columns (that list that happens to have a length of 1), resulting in a dataframe being returned. If you remove the extra set of brackets, as in tst[lookupValue]['SomeCol'], then you are asking for just that one column rather than a list of columns, and thus you get a series back.
  3. You need a series to use pandas.Series.tolist(), so you should definitely skip the second set of brackets in this case. FYI, if you ever end up with a one-column dataframe that isn't easily avoidable like this, you can use pandas.DataFrame.squeeze() to convert it to a series.
  4. tst[lookupValue]['SomeCol'] is getting a subset of a particular column via chained slicing. It slices once to get a dataframe with only certain rows left, and then it slices again to get a certain column. You can get away with it here since you are just reading, not writing, but the proper way to do it is tst.loc[lookupValue, 'SomeCol'] (which returns a series).
  5. Using the syntax from #4, you could reasonably do everything in one line: ID = tst.loc[tst['SomeCol'] == 'SomeValue', 'SomeCol'].tolist()

Demo Code:

import pandas as pd
df = pd.DataFrame({'colA':[1,2,1],
                   'colB':[4,5,6]})
filter_value = 1

print "df"
print df
print type(df)

rows_to_keep = df['colA'] == filter_value
print "\ndf['colA'] == filter_value"
print rows_to_keep
print type(rows_to_keep)

result = df[rows_to_keep]['colB']
print "\ndf[rows_to_keep]['colB']"
print result
print type(result)

result = df[rows_to_keep][['colB']]
print "\ndf[rows_to_keep][['colB']]"
print result
print type(result)

result = df[rows_to_keep][['colB']].squeeze()
print "\ndf[rows_to_keep][['colB']].squeeze()"
print result
print type(result)

result = df.loc[rows_to_keep, 'colB']
print "\ndf.loc[rows_to_keep, 'colB']"
print result
print type(result)

result = df.loc[df['colA'] == filter_value, 'colB']
print "\ndf.loc[df['colA'] == filter_value, 'colB']"
print result
print type(result)

ID = df.loc[rows_to_keep, 'colB'].tolist()
print "\ndf.loc[rows_to_keep, 'colB'].tolist()"
print ID
print type(ID)

ID = df.loc[df['colA'] == filter_value, 'colB'].tolist()
print "\ndf.loc[df['colA'] == filter_value, 'colB'].tolist()"
print ID
print type(ID)

Result:

df
   colA  colB
0     1     4
1     2     5
2     1     6
<class 'pandas.core.frame.DataFrame'>

df['colA'] == filter_value
0     True
1    False
2     True
Name: colA, dtype: bool
<class 'pandas.core.series.Series'>

df[rows_to_keep]['colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df[rows_to_keep][['colB']]
   colB
0     4
2     6
<class 'pandas.core.frame.DataFrame'>

df[rows_to_keep][['colB']].squeeze()
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[rows_to_keep, 'colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[df['colA'] == filter_value, 'colB']
0    4
2    6
Name: colB, dtype: int64
<class 'pandas.core.series.Series'>

df.loc[rows_to_keep, 'colB'].tolist()
[4, 6]
<type 'list'>

df.loc[df['colA'] == filter_value, 'colB'].tolist()
[4, 6]
<type 'list'>

Multiple aggregations of the same column using pandas GroupBy.agg()

Would something like this work:

In [7]: df.groupby('dummy').returns.agg({'func1' : lambda x: x.sum(), 'func2' : lambda x: x.prod()})
Out[7]: 
              func2     func1
dummy                        
1     -4.263768e-16 -0.188565

Make an existing Git branch track a remote branch?

For git version 2.25.1, use the command:

git push --set-upstream origin <local_branch_name>

How to configure CORS in a Spring Boot + Spring Security application?

Spring Security can now leverage Spring MVC CORS support described in this blog post I wrote.

To make it work, you need to explicitly enable CORS support at Spring Security level as following, otherwise CORS enabled requests may be blocked by Spring Security before reaching Spring MVC.

If you are using controller level @CrossOrigin annotations, you just have to enable Spring Security CORS support and it will leverage Spring MVC configuration:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }
}

If you prefer using CORS global configuration, you can declare a CorsConfigurationSource bean as following:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and()...
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", new CorsConfiguration().applyPermitDefaultValues());
        return source;
    }
}

This approach supersedes the filter-based approach previously recommended.

You can find more details in the dedicated CORS section of Spring Security documentation.

Serializing an object as UTF-8 XML in .NET

I found this blog post which explains the problem very well, and defines a few different solutions:

(dead link removed)

I've settled for the idea that the best way to do it is to completely omit the XML declaration when in memory. It actually is UTF-16 at that point anyway, but the XML declaration doesn't seem meaningful until it has been written to a file with a particular encoding; and even then the declaration is not required. It doesn't seem to break deserialization, at least.

As @Jon Hanna mentions, this can be done with an XmlWriter created like this:

XmlWriter writer = XmlWriter.Create (output, new XmlWriterSettings() { OmitXmlDeclaration = true });

Installing jQuery?

There is no installation required. Just add jQuery to your application folder and give a reference to the js file.

<script type="text/javascript" src="jQuery.js"></script>

if jQuery is in the same folder of your referenced file.

How to sort List of objects by some property

Since Java8 this can be done even cleaner using a combination of Comparator and Lambda expressions

For Example:

class Student{

    private String name;
    private List<Score> scores;

    // +accessor methods
}

class Score {

    private int grade;
    // +accessor methods
}

    Collections.sort(student.getScores(), Comparator.comparing(Score::getGrade);

Create Log File in Powershell

You might just want to use the new TUN.Logging PowerShell module, this can also send a log mail. Just use the Start-Log and/or Start-MailLog cmdlets to start logging and then just use Write-HostLog, Write-WarningLog, Write-VerboseLog, Write-ErrorLog etc. to write to console and log file/mail. Then call Send-Log and/or Stop-Log at the end and voila, you got your logging. Just install it from the PowerShell Gallery via

Install-Module -Name TUN.Logging

Or just follow the link: https://www.powershellgallery.com/packages/TUN.Logging

Documentation of the module can be found here: https://github.com/echalone/TUN/blob/master/PowerShell/Modules/TUN.Logging/TUN.Logging.md

How do I print the content of a .txt file in Python?

Opening a file in python for reading is easy:

f = open('example.txt', 'r')

To get everything in the file, just use read()

file_contents = f.read()

And to print the contents, just do:

print (file_contents)

Don't forget to close the file when you're done.

f.close()

How does Java handle integer underflows and overflows and how would you check for it?

It wraps around.

e.g:

public class Test {

    public static void main(String[] args) {
        int i = Integer.MAX_VALUE;
        int j = Integer.MIN_VALUE;

        System.out.println(i+1);
        System.out.println(j-1);
    }
}

prints

-2147483648
2147483647

Using wget to recursively fetch a directory with arbitrary files in it

Recursive wget ignoring robots (for websites)

wget -e robots=off -r -np --page-requisites --convert-links 'http://example.com/folder/'

-e robots=off causes it to ignore robots.txt for that domain

-r makes it recursive

-np = no parents, so it doesn't follow links up to the parent folder

Get index of selected option with jQuery

You can use the .prop(propertyName) function to get a property from the first element in the jQuery object.

var savedIndex = $(selectElement).prop('selectedIndex');

This keeps your code within the jQuery realm and also avoids the other option of using a selector to find the selected option. You can then restore it using the overload:

$(selectElement).prop('selectedIndex', savedIndex);

Adding devices to team provisioning profile

After you've added the UDID to the devices in Provisioning Portal manually, you should trick Xcode into generating a new Team Provisioning Profile (with the newly added device included). Follow these steps:

  1. Open Organizer > Devices > Library > Provisioning Profiles. Find the existing (old) profile (that does not include the newly added device). Delete it.
  2. Connect one of your own devices. Right-click on it in Organizer > Devices > Devices. Choose 'Add Device to Provisioning Portal'.

This will trick Xcode into generating a new Team Provisioning Profile, which automatically includes devices you've added in Provisioning Portal.

ListView with OnItemClickListener

listPaired = (ListView) findViewById( R.id.listView1 );
listPairedData = new ArrayList < String >();
araPaired = new ArrayAdapter( this, android.R.layout.simple_list_item_1, listPairedData );
listPaired.setAdapter( araPaired );
listPaired.setOnItemClickListener( listPairedClickItem );

private OnItemClickListener listPairedClickItem = new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > arg0, View arg1, int arg2, long arg3) {

        String info = ( (TextView) arg1 ).getText().toString();
        Toast.makeText( getBaseContext(), "Item " + info, Toast.LENGTH_LONG ).show();
    }
};

Convert audio files to mp3 using ffmpeg

You could use this command:

ffmpeg -i input.wav -vn -ar 44100 -ac 2 -b:a 192k output.mp3

Explanation of the used arguments in this example:

  • -i - input file

  • -vn - Disable video, to make sure no video (including album cover image) is included if the source would be a video file

  • -ar - Set the audio sampling frequency. For output streams it is set by default to the frequency of the corresponding input stream. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options.

  • -ac - Set the number of audio channels. For output streams it is set by default to the number of input audio channels. For input streams this option only makes sense for audio grabbing devices and raw demuxers and is mapped to the corresponding demuxer options. So used here to make sure it is stereo (2 channels)

  • -b:a - Converts the audio bitrate to be exact 192kbit per second

How to mount host volumes into docker containers in Dockerfile during build

UPDATE: Somebody just won't take no as the answer, and I like it, very much, especially to this particular question.

GOOD NEWS, There is a way now --

The solution is Rocker: https://github.com/grammarly/rocker

John Yani said, "IMO, it solves all the weak points of Dockerfile, making it suitable for development."

Rocker

https://github.com/grammarly/rocker

By introducing new commands, Rocker aims to solve the following use cases, which are painful with plain Docker:

  1. Mount reusable volumes on build stage, so dependency management tools may use cache between builds.
  2. Share ssh keys with build (for pulling private repos, etc.), while not leaving them in the resulting image.
  3. Build and run application in different images, be able to easily pass an artifact from one image to another, ideally have this logic in a single Dockerfile.
  4. Tag/Push images right from Dockerfiles.
  5. Pass variables from shell build command so they can be substituted to a Dockerfile.

And more. These are the most critical issues that were blocking our adoption of Docker at Grammarly.

Update: Rocker has been discontinued, per the official project repo on Github

As of early 2018, the container ecosystem is much more mature than it was three years ago when this project was initiated. Now, some of the critical and outstanding features of rocker can be easily covered by docker build or other well-supported tools, though some features do remain unique to rocker. See https://github.com/grammarly/rocker/issues/199 for more details.

How to write inside a DIV box with javascript

If you are using jQuery and you want to add content to the existing contents of the div, you can use .html() within the brackets:

_x000D_
_x000D_
$("#log").html($('#log').html() + " <br>New content!");
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="log">Initial Content</div>
_x000D_
_x000D_
_x000D_

How do I move focus to next input with jQuery?

you cat use it

$(document).on("keypress","input,select",function (e) {
    e.preventDefault();
    if (e.keyCode==13) {
        $(':input:eq(' + ($(':input').index(this) + 1) +')').focus();
    }
});

How to get source code of a Windows executable?

I would (and have) used IDA Pro to decompile executables. It creates semi-complete code, you can decompile to assembly or C.

If you have a copy of the debug symbols around, load those into IDA before decompiling and it will be able to name many of the functions, parameters, etc.

Receiving "fatal: Not a git repository" when attempting to remote add a Git repo

Did you init a local Git repository, into which this remote is supposed to be added?

Does your local directory have a .git folder?

Try git init.

Open URL in Java to get the content

It works for me. Please check if you are using the right imports?

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

Default argument values in JavaScript functions

ES2015 onwards:

From ES6/ES2015, we have default parameters in the language specification. So we can just do something simple like,

function A(a, b = 4, c = 5) {
}

or combined with ES2015 destructuring,

function B({c} = {c: 2}, [d, e] = [3, 4]) {
}

For detailed explanation,

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/default_parameters

Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

Pre ES2015:

If you're going to handle values which are NOT Numbers, Strings, Boolean, NaN, or null you can simply use

(So, for Objects, Arrays and Functions that you plan never to send null, you can use)

param || DEFAULT_VALUE

for example,

function X(a) {
  a = a || function() {};
}

Though this looks simple and kinda works, this is restrictive and can be an anti-pattern because || operates on all falsy values ("", null, NaN, false, 0) too - which makes this method impossible to assign a param the falsy value passed as the argument.

So, in order to handle only undefined values explicitly, the preferred approach would be,

function C(a, b) {
  a = typeof a === 'undefined' ? DEFAULT_VALUE_A : a;
  b = typeof b === 'undefined' ? DEFAULT_VALUE_B : b;
}

Import txt file and having each line as a list

with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]