Programs & Examples On #Objectify

Objectify is a 3rd party Java data access API specifically designed for Google Cloud Datastore in the App Engine Standard runtime. It occupies a "middle ground"; easier to use and more transparent than JDO or JPA, but significantly more convenient than the Low-Level API provided for Cloud Datastore.

Error:Execution failed for task ':app:dexDebug'. com.android.ide.common.process.ProcessException

For me I had multiple versions of the same library included in /app/libs. I was using Parse and I had both ParseFacebookUtilsV3-1.9.0.jar and ParseFacebookUtilsV4-1.9.0.jar.

Deleting the V3 jar solves the problem.

How to convert an XML file to nice pandas dataframe?

You can also convert by creating a dictionary of elements and then directly converting to a data frame:

import xml.etree.ElementTree as ET
import pandas as pd

# Contents of test.xml
# <?xml version="1.0" encoding="utf-8"?> <tags>   <row Id="1" TagName="bayesian" Count="4699" ExcerptPostId="20258" WikiPostId="20257" />   <row Id="2" TagName="prior" Count="598" ExcerptPostId="62158" WikiPostId="62157" />   <row Id="3" TagName="elicitation" Count="10" />   <row Id="5" TagName="open-source" Count="16" /> </tags>

root = ET.parse('test.xml').getroot()

tags = {"tags":[]}
for elem in root:
    tag = {}
    tag["Id"] = elem.attrib['Id']
    tag["TagName"] = elem.attrib['TagName']
    tag["Count"] = elem.attrib['Count']
    tags["tags"]. append(tag)

df_users = pd.DataFrame(tags["tags"])
df_users.head()

pip is not able to install packages correctly: Permission denied error

It looks like you're having a permissions error, based on this message in your output: error: could not create '/lib/python2.7/site-packages/lxml': Permission denied.

One thing you can try is doing a user install of the package with pip install lxml --user. For more information on how that works, check out this StackOverflow answer. (Thanks to Ishaan Taylor for the suggestion)

You can also run pip install as a superuser with sudo pip install lxml but it is not generally a good idea because it can cause issues with your system-level packages.

SyntaxError of Non-ASCII character

You should define source code encoding, add this to the top of your script:

# -*- coding: utf-8 -*-

The reason why it works differently in console and in the IDE is, likely, because of different default encodings set. You can check it by running:

import sys
print sys.getdefaultencoding()

Also see:

How to check if a word is an English word with Python?

I find that there are 3 package-based solutions to solve the problem. They are pyenchant, wordnet and corpus(self-defined or from ntlk). Pyenchant couldn't installed easily in win64 with py3. Wordnet doesn't work very well because it's corpus isn't complete. So for me, I choose the solution answered by @Sadik, and use 'set(words.words())' to speed up.

First:

pip3 install nltk
python3

import nltk
nltk.download('words')

Then:

from nltk.corpus import words
setofwords = set(words.words())

print("hello" in setofwords)
>>True

Retrieving the output of subprocess.call()

If you have Python version >= 2.7, you can use subprocess.check_output which basically does exactly what you want (it returns standard output as string).

Simple example (linux version, see note):

import subprocess

print subprocess.check_output(["ping", "-c", "1", "8.8.8.8"])

Note that the ping command is using linux notation (-c for count). If you try this on Windows remember to change it to -n for same result.

As commented below you can find a more detailed explanation in this other answer.

What exactly is Python's file.flush() doing?

There's typically two levels of buffering involved:

  1. Internal buffers
  2. Operating system buffers

The internal buffers are buffers created by the runtime/library/language that you're programming against and is meant to speed things up by avoiding system calls for every write. Instead, when you write to a file object, you write into its buffer, and whenever the buffer fills up, the data is written to the actual file using system calls.

However, due to the operating system buffers, this might not mean that the data is written to disk. It may just mean that the data is copied from the buffers maintained by your runtime into the buffers maintained by the operating system.

If you write something, and it ends up in the buffer (only), and the power is cut to your machine, that data is not on disk when the machine turns off.

So, in order to help with that you have the flush and fsync methods, on their respective objects.

The first, flush, will simply write out any data that lingers in a program buffer to the actual file. Typically this means that the data will be copied from the program buffer to the operating system buffer.

Specifically what this means is that if another process has that same file open for reading, it will be able to access the data you just flushed to the file. However, it does not necessarily mean it has been "permanently" stored on disk.

To do that, you need to call the os.fsync method which ensures all operating system buffers are synchronized with the storage devices they're for, in other words, that method will copy data from the operating system buffers to the disk.

Typically you don't need to bother with either method, but if you're in a scenario where paranoia about what actually ends up on disk is a good thing, you should make both calls as instructed.


Addendum in 2018.

Note that disks with cache mechanisms is now much more common than back in 2013, so now there are even more levels of caching and buffers involved. I assume these buffers will be handled by the sync/flush calls as well, but I don't really know.

Is it possible to add dynamically named properties to JavaScript object?

I know that the question is answered perfectly, but I also found another way to add new properties and wanted to share it with you:

You can use the function Object.defineProperty()

Found on Mozilla Developer Network

Example:

var o = {}; // Creates a new object

// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(o, "a", {value : 37,
                               writable : true,
                               enumerable : true,
                               configurable : true});
// 'a' property exists in the o object and its value is 37

// Example of an object property added with defineProperty with an accessor property descriptor
var bValue;
Object.defineProperty(o, "b", {get : function(){ return bValue; },
                               set : function(newValue){ bValue = newValue; },
                               enumerable : true,
                               configurable : true});
o.b = 38;
// 'b' property exists in the o object and its value is 38
// The value of o.b is now always identical to bValue, unless o.b is redefined

// You cannot try to mix both :
Object.defineProperty(o, "conflict", { value: 0x9f91102, 
                                       get: function() { return 0xdeadbeef; } });
// throws a TypeError: value appears only in data descriptors, get appears only in accessor descriptors

How to find list intersection?

If order is not important and you don't need to worry about duplicates then you can use set intersection:

>>> a = [1,2,3,4,5]
>>> b = [1,3,5,6]
>>> list(set(a) & set(b))
[1, 3, 5]

Java Swing revalidate() vs repaint()

Any time you do a remove() or a removeAll(), you should call

  validate();
  repaint();

after you have completed add()'ing the new components.

Calling validate() or revalidate() is mandatory when you do a remove() - see the relevant javadocs.

My own testing indicates that repaint() is also necessary. I'm not sure exactly why.

Check whether an input string contains a number in javascript

You can also try lodash:

const isNumeric = number => 
  _.isFinite(_.parseInt(number)) && !_.isNaN(_.parseInt(number))

How to run a script as root on Mac OS X?

As in any unix-based environment, you can use the sudo command:

$ sudo script-name

It will ask for your password (your own, not a separate root password).

Tensorflow set CUDA_VISIBLE_DEVICES within jupyter

You can also enable multiple GPU cores, like so:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="0,2,3,4"

How to SFTP with PHP?

Install Flysystem:

composer require league/flysystem-sftp

Then:

use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;

$filesystem = new Filesystem(new SftpAdapter([
    'host' => 'example.com',
    'port' => 22,
    'username' => 'username',
    'password' => 'password',
    'privateKey' => 'path/to/or/contents/of/privatekey',
    'root' => '/path/to/root',
    'timeout' => 10,
]));
$filesystem->listFiles($path); // get file lists
$filesystem->read($path_to_file); // grab file
$filesystem->put($path); // upload file
....

Read:

https://flysystem.thephpleague.com/v1/docs/

c# replace \" characters

In .NET Framework 4 and MVC this is the only representation that worked:

Replace(@"""","")

Using a backslash in whatever combination did not work...

Global Events in Angular

You can use EventEmitter or observables to create an eventbus service that you register with DI. Every component that wants to participate just requests the service as constructor parameter and emits and/or subscribes to events.

See also

How can I retrieve Id of inserted entity using Entity framework?

It is pretty easy. If you are using DB generated Ids (like IDENTITY in MS SQL) you just need to add entity to ObjectSet and SaveChanges on related ObjectContext. Id will be automatically filled for you:

using (var context = new MyContext())
{
  context.MyEntities.Add(myNewObject);
  context.SaveChanges();

  int id = myNewObject.Id; // Yes it's here
}

Entity framework by default follows each INSERT with SELECT SCOPE_IDENTITY() when auto-generated Ids are used.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I had the same problem. mysql -u root -p worked for me. It later asks you for a password. You should then enter the password that you had set for mysql. The default password could be password, if you did not set one. More info here.

Using jQuery, Restricting File Size Before Uploading

I don't think it's possible unless you use a flash, activex or java uploader.

For security reasons ajax / javascript isn't allowed to access the file stream or file properties before or during upload.

Fatal error: unexpectedly found nil while unwrapping an Optional values

I searched around for a solution to this myself. only my problem was related to UITableViewCell Not UICollectionView as your mentioning here.

First off, im new to iOS development. like brand new, sitting here trying to get trough my first tutorial, so dont take my word for anything. (unless its working ;) )

I was getting a nil reference to cell.detailTextLabel.text - After rewatching the tutorial video i was following, it didnt look like i had missed anything. So i entered the header file for the UITableViewCell and found this.

var detailTextLabel: UILabel! { get } // default is nil. label will be created if necessary (and the current style supports a detail label).

So i noticed that it says (and the current style supports a detail label) - Well, Custom style does not have a detailLabel on there by default. so i just had to switch the style of the cell in the Storyboard, and all was fine.

Im guesssing your label should always be there?

So if your following connor`s advice, that basically means, IF that label is available, then use it. If your style is correctly setup and the reuse identifier matches the one set in the Storyboard you should not have to do this check unless your using more then one custom cell.

Call ASP.NET function from JavaScript?

Try this:

if(!ClientScript.IsStartupScriptRegistered("window"))
{
    Page.ClientScript.RegisterStartupScript(this.GetType(), "window", "pop();", true);
}

Or this

Response.Write("<script>alert('Hello World');</script>");

Use the OnClientClick property of the button to call JavaScript functions...

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

Is it possible to get a history of queries made in postgres

If you want to identify slow queries, than the method is to use log_min_duration_statement setting (in postgresql.conf or set per-database with ALTER DATABASE SET).

When you logged the data, you can then use grep or some specialized tools - like pgFouine or my own analyzer - which lacks proper docs, but despite this - runs quite well.

How to produce a range with step n in bash? (generate a sequence of numbers with increments)

$ seq 4
1
2
3
4

$ seq 2 5
2
3
4
5

$ seq 4 2 12
4
6
8
10
12

$ seq -w 4 2 12
04
06
08
10
12

$ seq -s, 4 2 12
4,6,8,10,12

How to access the contents of a vector from a pointer to the vector in C++?

vector<int> v;
v.push_back(906);
vector<int> * p = &v;
cout << (*p)[0] << endl;

Pythonic way to check if a list is sorted or not

Not very Pythonic at all, but we need at least one reduce() answer, right?

def is_sorted(iterable):
    prev_or_inf = lambda prev, i: i if prev <= i else float('inf')
    return reduce(prev_or_inf, iterable, float('-inf')) < float('inf')

The accumulator variable simply stores that last-checked value, and if any value is smaller than the previous value, the accumulator is set to infinity (and thus will still be infinity at the end, since the 'previous value' will always be bigger than the current one).

Double precision - decimal places

In most contexts where double values are used, calculations will have a certain amount of uncertainty. The difference between 1.33333333333333300 and 1.33333333333333399 may be less than the amount of uncertainty that exists in the calculations. Displaying the value of "2/3 + 2/3" as "1.33333333333333" is apt to be more meaningful than displaying it as "1.33333333333333319", since the latter display implies a level of precision that doesn't really exist.

In the debugger, however, it is important to uniquely indicate the value held by a variable, including essentially-meaningless bits of precision. It would be very confusing if a debugger displayed two variables as holding the value "1.333333333333333" when one of them actually held 1.33333333333333319 and the other held 1.33333333333333294 (meaning that, while they looked the same, they weren't equal). The extra precision shown by the debugger isn't apt to represent a numerically-correct calculation result, but indicates how the code will interpret the values held by the variables.

Concept of void pointer in C programming

You should be aware that in C, unlike Java or C#, there is absolutely no possibility to successfully "guess" the type of object a void* pointer points at. Something similar to getClass() simply doesn't exist, since this information is nowhere to be found. For that reason, the kind of "generic" you are looking for always comes with explicit metainformation, like the int b in your example or the format string in the printf family of functions.

How to run SQL script in MySQL?

mysql> source C:\Users\admin\Desktop\fn_Split.sql

Do not specify single quotes.

If the above command is not working, copy the file to c: drive and try again. as shown below,

mysql> source C:\fn_Split.sql

Subset of rows containing NA (missing) values in a chosen column of a data frame

Prints all the rows with NA data:

tmp <- data.frame(c(1,2,3),c(4,NA,5));
tmp[round(which(is.na(tmp))/ncol(tmp)),]

How can I initialize base class member variables in derived class constructor?

If you don't specify visibility for a class member, it defaults to "private". You should make your members private or protected if you want to access them in a subclass.

When should I write the keyword 'inline' for a function/method?

You still need to explicitly inline your function when doing template specialization (if specialization is in .h file)

Get IP address of visitors using Flask for Python

The user's IP address can be retrieved using the following snippet:

from flask import request
print(request.remote_addr)

Simplest way to throw an error/exception with a custom message in Swift 2?

The simplest approach is probably to define one custom enum with just one case that has a String attached to it:

enum MyError: ErrorType {
    case runtimeError(String)
}

Or, as of Swift 4:

enum MyError: Error {
    case runtimeError(String)
}

Example usage would be something like:

func someFunction() throws {
    throw MyError.runtimeError("some message")
}
do {
    try someFunction()
} catch MyError.runtimeError(let errorMessage) {
    print(errorMessage)
}

If you wish to use existing Error types, the most general one would be an NSError, and you could make a factory method to create and throw one with a custom message.

Pandas create empty DataFrame with only column names

You can create an empty DataFrame with either column names or an Index:

In [4]: import pandas as pd
In [5]: df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
In [6]: df
Out[6]:
Empty DataFrame
Columns: [A, B, C, D, E, F, G]
Index: []

Or

In [7]: df = pd.DataFrame(index=range(1,10))
In [8]: df
Out[8]:
Empty DataFrame
Columns: []
Index: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Edit: Even after your amendment with the .to_html, I can't reproduce. This:

df = pd.DataFrame(columns=['A','B','C','D','E','F','G'])
df.to_html('test.html')

Produces:

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>A</th>
      <th>B</th>
      <th>C</th>
      <th>D</th>
      <th>E</th>
      <th>F</th>
      <th>G</th>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Way to go from recursion to iteration

Generally the technique to avoid stack overflow is for recursive functions is called trampoline technique which is widely adopted by Java devs.

However, for C# there is a little helper method here that turns your recursive function to iterative without requiring to change logic or make the code in-comprehensible. C# is such a nice language that amazing stuff is possible with it.

It works by wrapping parts of the method by a helper method. For example the following recursive function:

int Sum(int index, int[] array)
{
 //This is the termination condition
 if (int >= array.Length)
 //This is the returning value when termination condition is true
 return 0;

//This is the recursive call
 var sumofrest = Sum(index+1, array);

//This is the work to do with the current item and the
 //result of recursive call
 return array[index]+sumofrest;
}

Turns into:

int Sum(int[] ar)
{
 return RecursionHelper<int>.CreateSingular(i => i >= ar.Length, i => 0)
 .RecursiveCall((i, rv) => i + 1)
 .Do((i, rv) => ar[i] + rv)
 .Execute(0);
}

Deprecated: mysql_connect()

Its just a warning that is telling you to start using newer methods of connecting to your db such as pdo objects

http://code.tutsplus.com/tutorials/php-database-access-are-you-doing-it-correctly--net-25338

The manual is here

http://www.php.net/manual/en/book.pdo.php

Test if registry value exists

One-liner:

$valueExists = (Get-Item $regKeyPath -EA Ignore).Property -contains $regValueName

How to show PIL images on the screen?

You can display an image in your own window using Tkinter, w/o depending on image viewers installed in your system:

import Tkinter as tk
from PIL import Image, ImageTk  # Place this at the end (to avoid any conflicts/errors)

window = tk.Tk()
#window.geometry("500x500") # (optional)    
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()

For Python 3, replace import Tkinter as tk with import tkinter as tk.

How to check postgres user and password?

You may change the pg_hba.conf and then reload the postgresql. something in the pg_hba.conf may be like below:

# "local" is for Unix domain socket connections only
local   all             all                                     trust
# IPv4 local connections:
host    all             all             127.0.0.1/32            trust

then you change your user to postgresql, you may login successfully.

su postgresql

Warning: implode() [function.implode]: Invalid arguments passed

You can try

echo implode(', ', (array)$ret);

Difference between JPanel, JFrame, JComponent, and JApplet

Those classes are common extension points for Java UI designs. First off, realize that they don't necessarily have much to do with each other directly, so trying to find a relationship between them might be counterproductive.

JApplet - A base class that let's you write code that will run within the context of a browser, like for an interactive web page. This is cool and all but it brings limitations which is the price for it playing nice in the real world. Normally JApplet is used when you want to have your own UI in a web page. I've always wondered why people don't take advantage of applets to store state for a session so no database or cookies are needed.

JComponent - A base class for objects which intend to interact with Swing.

JFrame - Used to represent the stuff a window should have. This includes borders (resizeable y/n?), titlebar (App name or other message), controls (minimize/maximize allowed?), and event handlers for various system events like 'window close' (permit app to exit yet?).

JPanel - Generic class used to gather other elements together. This is more important with working with the visual layout or one of the provided layout managers e.g. gridbaglayout, etc. For example, you have a textbox that is bigger then the area you have reserved. Put the textbox in a scrolling pane and put that pane into a JPanel. Then when you place the JPanel, it will be more manageable in terms of layout.

How to change line color in EditText

You can change the color of EditText programmatically just using this line of code:edittext.setBackgroundTintList(ColorStateList.valueOf(yourcolor));

What's alternative to angular.copy in Angular

I as well as you faced a problem of work angular.copy and angular.expect because they do not copy the object or create the object without adding some dependencies. My solution was this:

  copyFactory = (() ->
    resource = ->
      resource.__super__.constructor.apply this, arguments
      return
    this.extendTo resource
    resource
  ).call(factory)

SQL Server Operating system error 5: "5(Access is denied.)"

If you get this error on an .MDF file in the APP_DATA folder (or where ever you put it) for a Visual Studio project, the way I did it was to simply copy permissions from the existing DATA folder here (I'm using SQL Express 2014 to support an older app):

C:\Program Files\Microsoft SQL Server\MSSQL12.SQLEXPRESS2014\MSSQL\DATA

(note: your actual install path my vary - especially if your instance name is different)

Double click on theDATA folder first as administrator to make sure you have access, then open the properties on the folder and mimic the same for the APP_DATA folder. In my case the missing user was MSSQL$SQLEXPRESS2014 (because I named the instance SQLEXPRESS2014 - yours may be different). That also happens to be the SQL Server service username.

Service vs IntentService in the Android platform

An IntentService is an extension of a Service that is made to ease the execution of a task that needs to be executed in background and in a seperated thread.

IntentService starts, create a thread and runs its task in the thread. once done, it cleans everything. Only one instance of a IntentService can run at the same time, several calls are enqueued.

It is very simple to use and very convenient for a lot of uses, for instance downloading stuff. But it has limitations that can make you want to use instead the more basic (not simple) Service.

For example, a service connected to a xmpp server and bound by activities cannot be simply done using an IntentService. You'll end up ignoring or overriding IntentService stuffs.

How to get Python requests to trust a self signed SSL certificate?

try:

r = requests.post(url, data=data, verify='/path/to/public_key.pem')

Press enter in textbox to and execute button command

Since everybody covered the KeyDown answers, how about using the IsDefault on the button?

You can read this tip for a quick howto and what it does: http://www.codeproject.com/Tips/665886/Button-Tip-IsDefault-IsCancel-and-other-usability

Here's an example from the article linked:

<Button IsDefault = "true" 
        Click     = "SaveClicked"
        Content   = "Save"  ... />
'''

ADB No Devices Found

There's obviously a ton of different problems that could be causing this (and a ton of different solutions to go along with those problems). So think about all the solutions!

If you've gotten this phone and computer pair to work together before, but they aren't working any more, it might be a specific program on your computer rather than a problem on your phone. Some programs install/use their own adb, and only one of these can connect to your phone at a time. I think this makes a race condition, so sometimes it'll connect fine.

Some programs that run adb:

HTC Sync Manager - uninstall this.

chrome://inspect - lets you view localhost on your phone. Just close the window when you're done with it.

Launch Pycharm from command line (terminal)

You're right that the JetBrains help page isn't very clear. On OS X, you'll want to use the launcher at:

/Applications/PyCharm.app/Contents/MacOS/pycharm

Or, for community edition:

/Applications/PyCharm\ CE.app/Contents/MacOS/pycharm

Unfortunately, adding a symlink to this binary wouldn't work for me (the launcher would crash). Setting an alias worked, though. Add this in your .bash_profile (or whatever shell you use):

alias pycharm="/Applications/PyCharm CE.app/Contents/MacOS/pycharm"

Then, you can run commands with simply pycharm.

With this you can do things like open a project:

pycharm ~/repos/my-project

Or open a specific line of a file in a project:

pycharm ~/repos/my-project --line 42 ~/repos/my-project/script.py

Or view the diff of two files (they don't need to be part of a project):

pycharm ~/some_file.txt ~/Downloads/some_other_file.txt

Note that I needed to pass absolute paths to those files or PyCharm couldn't find them..

check if file exists in php

for me also the file_exists() function is not working properly. So I got this alternative solution. Hope this one help someone

$path = 'http://localhost/admin/public/upload/video_thumbnail/thumbnail_1564385519_0.png';

    if (@GetImageSize($path)) {
        echo 'File exits';
    } else {
        echo "File doesn't exits";
    }

Fastest way to serialize and deserialize .NET objects

The binary serializer included with .net should be faster that the XmlSerializer. Or another serializer for protobuf, json, ...

But for some of them you need to add Attributes, or some other way to add metadata. For example ProtoBuf uses numeric property IDs internally, and the mapping needs to be somehow conserved by a different mechanism. Versioning isn't trivial with any serializer.

CSS selector for disabled input type="submit"

Does that work in IE6?

No, IE6 does not support attribute selectors at all, cf. CSS Compatibility and Internet Explorer.

You might find How to workaround: IE6 does not support CSS “attribute” selectors worth the read.


EDIT
If you are to ignore IE6, you could do (CSS2.1):

input[type=submit][disabled=disabled],
button[disabled=disabled] {
    ...
}

CSS3 (IE9+):

input[type=submit]:disabled,
button:disabled {
    ...
}

You can substitute [disabled=disabled] (attribute value) with [disabled] (attribute presence).

Typescript empty object for a typed variable

Caveats

Here are two worthy caveats from the comments.

Either you want user to be of type User | {} or Partial<User>, or you need to redefine the User type to allow an empty object. Right now, the compiler is correctly telling you that user is not a User. – jcalz

I don't think this should be considered a proper answer because it creates an inconsistent instance of the type, undermining the whole purpose of TypeScript. In this example, the property Username is left undefined, while the type annotation is saying it can't be undefined. – Ian Liu Rodrigues

Answer

One of the design goals of TypeScript is to "strike a balance between correctness and productivity." If it will be productive for you to do this, use Type Assertions to create empty objects for typed variables.

type User = {
    Username: string;
    Email: string;
}

const user01 = {} as User;
const user02 = <User>{};

user01.Email = "[email protected]";

Here is a working example for you.

Here are type assertions working with suggestion.

PHP 7 simpleXML

For Ubuntu 18.04 and php7.3, install php7.3-xml sudo apt-get install php7.3-xml

this will installl the required simplexml

Omitting one Setter/Getter in Lombok

According to @Data description you can use:

All generated getters and setters will be public. To override the access level, annotate the field or class with an explicit @Setter and/or @Getter annotation. You can also use this annotation (by combining it with AccessLevel.NONE) to suppress generating a getter and/or setter altogether.

C++ Remove new line from multiline string

 std::string some_str = SOME_VAL;
 if ( some_str.size() > 0 && some_str[some_str.length()-1] == '\n' ) 
  some_str.resize( some_str.length()-1 );

or (removes several newlines at the end)

some_str.resize( some_str.find_last_not_of(L"\n")+1 );

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

How to group subarrays by a column value?

I think this works better in PHP 5.5+

$IdVar = array_column($data, 'id');

How to check the extension of a filename in a bash script?

The correct answer on how to take the extension available in a filename in linux is:

${filename##*\.} 

Example of printing all file extensions in a directory

for fname in $(find . -maxdepth 1 -type f) # only regular file in the current dir
    do  echo ${fname##*\.} #print extensions 
done

Adding CSRFToken to Ajax request

How about this,

$("body").bind("ajaxSend", function(elm, xhr, s){
   if (s.type == "POST") {
      xhr.setRequestHeader('X-CSRF-Token', getCSRFTokenValue());
   }
});

Ref: http://erlend.oftedal.no/blog/?blogid=118

To pass CSRF as parameter,

        $.ajax({
            type: "POST",
            url: "file",
            data: { CSRF: getCSRFTokenValue()}
        })
        .done(function( msg ) {
            alert( "Data: " + msg );
        });

CURL and HTTPS, "Cannot resolve host"

Maybe a DNS issue?

Try your URL against this code:

$_h = curl_init();
curl_setopt($_h, CURLOPT_HEADER, 1);
curl_setopt($_h, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($_h, CURLOPT_HTTPGET, 1);
curl_setopt($_h, CURLOPT_URL, 'YOUR_URL' );
curl_setopt($_h, CURLOPT_DNS_USE_GLOBAL_CACHE, false );
curl_setopt($_h, CURLOPT_DNS_CACHE_TIMEOUT, 2 );

var_dump(curl_exec($_h));
var_dump(curl_getinfo($_h));
var_dump(curl_error($_h)); 

Is quitting an application frowned upon?

As an Application in an Android context is just a bunch of vaguely related Activities, quitting an Application doesn't really make much sense. You can finish() an Activity, and the view of the previous Activity in the Activity stack will be drawn.

error CS0234: The type or namespace name 'Script' does not exist in the namespace 'System.Web'

I had the same. Script been underlined. I added a reference to System.Web.Extensions. Thereafter the Script was no longer underlined. Hope this helps someone.

How to add a new audio (not mixing) into a video using ffmpeg?

mp3 music to wav

ffmpeg -i music.mp3 music.wav

truncate to fit video

ffmpeg -i music.wav -ss 0 -t 37 musicshort.wav

mix music and video

ffmpeg -i musicshort.wav -i movie.avi final_video.avi

Routing with multiple Get methods in ASP.NET Web API

  // this piece of code in the WebApiConfig.cs file or your custom bootstrap application class
  // define two types of routes 1. DefaultActionApi  and 2. DefaultApi as below

   config.Routes.MapHttpRoute("DefaultActionApi", "api/{controller}/{action}/{id}", new { id = RouteParameter.Optional });
   config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { action = "Default", id = RouteParameter.Optional });

  // decorate the controller action method with [ActionName("Default")] which need to invoked with below url
  // http://localhost:XXXXX/api/Demo/ -- will invoke the Get method of Demo controller
  // http://localhost:XXXXX/api/Demo/GetAll -- will invoke the GetAll method of Demo controller
  // http://localhost:XXXXX/api/Demo/GetById -- will invoke the GetById method of Demo controller
  // http://localhost:57870/api/Demo/CustomGetDetails -- will invoke the CustomGetDetails method of Demo controller
  // http://localhost:57870/api/Demo/DemoGet -- will invoke the DemoGet method of Demo controller


 public class DemoController : ApiController
 {
    // Mark the method with ActionName  attribute (defined in MapRoutes) 
    [ActionName("Default")]
    public HttpResponseMessage Get()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Get Method");
    }

    public HttpResponseMessage GetAll()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "GetAll Method");
    }

    public HttpResponseMessage GetById()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "Getby Id Method");
    }

    //Custom Method name
    [HttpGet]
    public HttpResponseMessage DemoGet()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "DemoGet Method");
    }

    //Custom Method name
    [HttpGet]
    public HttpResponseMessage CustomGetDetails()
    {
        return Request.CreateResponse(HttpStatusCode.OK, "CustomGetDetails Method");
    }
}

How to get Django and ReactJS to work together?

I know this is a couple of years late, but I'm putting it out there for the next person on this journey.

GraphQL has been helpful and way easier compared to DjangoRESTFramework. It is also more flexible in terms of the responses you get. You get what you ask for and don't have to filter through the response to get what you want.

You can use Graphene Django on the server side and React+Apollo/Relay... You can look into it as that is not your question.

AngularJS : The correct way of binding to a service properties

I think this question has a contextual component.

If you're simply pulling data from a service & radiating that information to it's view, I think binding directly to the service property is just fine. I don't want to write a lot of boilerplate code to simply map service properties to model properties to consume in my view.

Further, performance in angular is based on two things. The first is how many bindings are on a page. The second is how expensive getter functions are. Misko talks about this here

If you need to perform instance specific logic on the service data (as opposed to data massaging applied within the service itself), and the outcome of this impacts the data model exposed to the view, then I would say a $watcher is appropriate, as long as the function isn't terribly expensive. In the case of an expensive function, I would suggest caching the results in a local (to controller) variable, performing your complex operations outside of the $watcher function, and then binding your scope to the result of that.

As a caveat, you shouldn't be hanging any properties directly off your $scope. The $scope variable is NOT your model. It has references to your model.

In my mind, "best practice" for simply radiating information from service down to view:

function TimerCtrl1($scope, Timer) {
  $scope.model = {timerData: Timer.data};
};

And then your view would contain {{model.timerData.lastupdated}}.

Detect if a browser in a mobile device (iOS/Android phone/tablet) is used

Many mobile devices have resolutions so high that it's hard to distinguish between them and much larger screens. There are two ways to deal with this problem:

Use the following HTML code to scale the pixels (grouping smaller pixels into groups the size of the unit pixel - 96dpi, so px units will have the same physical size on all screens). Note that this will affect the scale of pretty much everything in your website, but this is generally the way to go when making sites mobile-friendly.

<meta name="viewport" content="width=device-width, initial-scale=1">

Alternatively, measuring the screen width in @media queries using cm instead of px units can tell you if you're dealing with a physically small screen regardless of resolution.

(413) Request Entity Too Large | uploadReadAheadSize

If you're running into this issue despite trying all of the solutions in this thread, and you're connecting to the service via SSL (e.g. https), this might help:

http://forums.newatlanta.com/messages.cfm?threadid=554611A2-E03F-43DB-92F996F4B6222BC0&#top

To summarize (in case the link dies in the future), if your requests are large enough the certificate negotiation between the client and the service will fail randomly. To keep this from happening, you'll need to enable a certain setting on your SSL bindings. From your IIS server, here are the steps you'll need to take:

  1. Via cmd or powershell, run netsh http show sslcert. This will give you your current configuration. You'll want to save this somehow so you can reference it again later.
  2. You should notice that "Negotiate Client Certificate" is disabled. This is the problem setting; the following steps will demonstrate how to enable it.
  3. Unfortunately there is no way to change existing bindings; you'll have to delete it and re-add it. Run netsh http delete sslcert <ipaddress>:<port> where <ipaddress>:<port> is the IP:port shown in the configuration you saved earlier.
  4. Now you can re-add the binding. You can view the valid parameters for netsh http add sslcert here (MSDN) but in most cases your command will look like this:

netsh http add sslcert ipport=<ipaddress>:<port> appid=<application ID from saved config including the {}> certhash=<certificate hash from saved config> certstorename=<certificate store name from saved config> clientcertnegotiation=enable

If you have multiple SSL bindings, you'll repeat the process for each of them. Hopefully this helps save someone else the hours and hours of headache this issue caused me.

EDIT: In my experience, you can't actually run the netsh http add sslcert command from the command line directly. You'll need to enter the netsh prompt first by typing netsh and then issue your command like http add sslcert ipport=... in order for it to work.

How do I run a spring boot executable jar in a Production environment?

By far the most easiest and reliable way to run Spring Boot applications in production is with Docker. Use Docker Compose, Docker Swarm or Kubernetes if you need to use multiple connected services.

Here's a simple Dockerfile from the official Spring Boot Docker guide to get you started:

FROM frolvlad/alpine-oraclejdk8:slim
VOLUME /tmp
ADD YOUR-APP-NAME.jar app.jar
RUN sh -c 'touch /app.jar'
ENV JAVA_OPTS=""
ENTRYPOINT [ "sh", "-c", "java $JAVA_OPTS -Djava.security.egd=file:/dev/./urandom -jar /app.jar" ]

Here's a sample command line to run the container as a daemon:

docker run \
  -d --restart=always \
  -e "SPRING_PROFILES_ACTIVE=prod" \
  -p 8080:8080 \
  prefix/imagename

How to open URL in Microsoft Edge from the command line?

All the other solutions work for Microsoft Edge (legacy) and on Windows 10 only. As of 2020, it will be discontinued and replaced by Microsoft Edge (Chromium based).

The solution that works with the new Edge on Windows 7, 8 and 10 is :

start msedge URL

Source :

How to initialize an array in one step using Ruby?

You can use an array literal:

array = [ '1', '2', '3' ]

You can also use a range:

array = ('1'..'3').to_a  # parentheses are required
# or
array = *('1'..'3')      # parentheses not required, but included for clarity

For arrays of whitespace-delimited strings, you can use Percent String syntax:

array = %w[ 1 2 3 ]

You can also pass a block to Array.new to determine what the value for each entry will be:

array = Array.new(3) { |i| (i+1).to_s }

Finally, although it doesn't produce the same array of three strings as the other answers above, note also that you can use enumerators in Ruby 1.8.7+ to create arrays; for example:

array = 1.step(17,3).to_a
#=> [1, 4, 7, 10, 13, 16]

How to increase image size of pandas.DataFrame.plot in jupyter notebook?

Try this:

import matplotlib as plt

after importing the file we can use matplotlib library but remember to use it as plt

df.plt(kind='line',figsize=(10,5))

after that the plot will be done and size increased. In figsize the 10 is for breadth and 5 is for height. Also other attributes can be added to the plot too.

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

How should I store GUID in MySQL tables?

if you have a char/varchar value formatted as the standard GUID, you can simply store it as BINARY(16) using the simple CAST(MyString AS BINARY16), without all those mind-boggling sequences of CONCAT + SUBSTR.

BINARY(16) fields are compared/sorted/indexed much faster than strings, and also take two times less space in the database

How to read file contents into a variable in a batch file?

You can read multiple variables from file like this:

for /f "delims== tokens=1,2" %%G in (param.txt) do set %%G=%%H

where param.txt:

PARAM1=value1
PARAM2=value2
...

How do I install Eclipse Marketplace in Eclipse Classic?

help=>install new software=>workwith choice Juno - http://download.eclipse.org/releases/juno and search in the below "type filter text" --------------market

you will see this plugs Marketplace Client

What is Scala's yield?

Unless you get a better answer from a Scala user (which I'm not), here's my understanding.

It only appears as part of an expression beginning with for, which states how to generate a new list from an existing list.

Something like:

var doubled = for (n <- original) yield n * 2

So there's one output item for each input (although I believe there's a way of dropping duplicates).

This is quite different from the "imperative continuations" enabled by yield in other languages, where it provides a way to generate a list of any length, from some imperative code with almost any structure.

(If you're familiar with C#, it's closer to LINQ's select operator than it is to yield return).

Add new row to excel Table (VBA)

I had the same error message and after lots of trial and error found out that it was caused by an advanced filter which was set on the ListObject. After clearing the advanced filter .listrows.add worked fine again. To clear the filter I use this - no idea how one could clear the filter only for the specific listobject instead of the complete worksheet.

Worksheets("mysheet").ShowAllData

How to hide Table Row Overflow?

If javascript is accepted as an answer, I made a jQuery plugin to address this issue (for more information about the issue see CSS: Truncate table cells, but fit as much as possible).

To use the plugin just type

$('selector').tableoverflow();

Plugin: https://github.com/marcogrcr/jquery-tableoverflow

Full example: http://jsfiddle.net/Cw7TD/3/embedded/result/

How can I position my jQuery dialog to center?

Because the dialog need a position, You need to include the js position

<script src="jquery.ui.position.js"></script>

Disabling same-origin policy in Safari

Most of these answers are old. The latest Safari 14.0.2 (in 2021), has the option to Disable Cross-Origin Restrictions, however, it doesn't work if the paths have ../../ kind of path names; even though Safari correctly resolves to a local file path, it still doesn't permit loading the file, even though it exists. This is a recent bug in Safari 14 that didn't happen in 13.

How do I determine k when using k-means clustering?

May be someone beginner like me looking for code example. information for silhouette_score is available here.

from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score

range_n_clusters = [2, 3, 4]            # clusters range you want to select
dataToFit = [[12,23],[112,46],[45,23]]  # sample data
best_clusters = 0                       # best cluster number which you will get
previous_silh_avg = 0.0

for n_clusters in range_n_clusters:
    clusterer = KMeans(n_clusters=n_clusters)
    cluster_labels = clusterer.fit_predict(dataToFit)
    silhouette_avg = silhouette_score(dataToFit, cluster_labels)
    if silhouette_avg > previous_silh_avg:
        previous_silh_avg = silhouette_avg
        best_clusters = n_clusters

# Final Kmeans for best_clusters
kmeans = KMeans(n_clusters=best_clusters, random_state=0).fit(dataToFit)

Java 8: Lambda-Streams, Filter by Method with Exception

You must catch the exception before it escapes the lambda:

s = s.filter(a -> {
    try {
        return a.isActive();
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    }
});

Consider the fact that the lambda isn't evaluated at the place you write it, but at some completely unrelated place, within a JDK class. So that would be the point where that checked exception would be thrown, and at that place it isn't declared.

You can deal with it by using a wrapper of your lambda that translates checked exceptions to unchecked ones:

public static <T> T uncheckCall(Callable<T> callable) {
    try {
        return callable.call();
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Your example would be written as

return s.filter(a -> uncheckCall(a::isActive))
        .map(Account::getNumber)
        .collect(toSet());

In my projects I deal with this issue without wrapping; instead I use a method which effectively defuses compiler's checking of exceptions. Needless to say, this should be handled with care and everybody on the project must be aware that a checked exception may appear where it is not declared. This is the plumbing code:

public static <T> T uncheckCall(Callable<T> callable) {
    try {
        return callable.call();
    } catch (Exception e) {
        return sneakyThrow(e);
    }
}

public static void uncheckRun(RunnableExc r) {
    try {
        r.run();
    } catch (Exception e) {
        sneakyThrow(e);
    }
}

public interface RunnableExc {
    void run() throws Exception;
}

@SuppressWarnings("unchecked")
private static <T extends Throwable> void sneakyThrow(Throwable t) throws T {
    throw (T) t;
}

and you can expect to get an IOException thrown in your face, even though collect does not declare it. In most, but not all real-life cases you would want to just rethrow the exception, anyway, and handle it as a generic failure. In all those cases, nothing is lost in clarity or correctness. Just beware of those other cases, where you would actually want to react to the exception on the spot. The developer will not be made aware by the compiler that there is an IOException to catch there and the compiler will in fact complain if you try to catch it because we have fooled it into believing that no such exception can be thrown.

adding child nodes in treeview

Guys use this code for adding nodes and childnodes for TreeView from C# code. *

KISS (Keep It Simple & Stupid :)*

protected void Button1_Click(object sender, EventArgs e)

{

        TreeNode a1 = new TreeNode("Apple");

        TreeNode b1 = new TreeNode("Banana");
        TreeNode a2 = new TreeNode("gree apple");
        TreeView2.Nodes.Add(a1);
        TreeView2.Nodes.Add(b1);
        a1.ChildNodes.Add(a2);

}

How to parse my json string in C#(4.0)using Newtonsoft.Json package?

You can use this tool to create appropriate c# classes:

http://jsonclassgenerator.codeplex.com/

and when you will have classes created you can simply convert string to object:

    public static T ParseJsonObject<T>(string json) where T : class, new()
    {
        JObject jobject = JObject.Parse(json);
        return JsonConvert.DeserializeObject<T>(jobject.ToString());
    }

Here that classes: http://ge.tt/2KGtbPT/v/0?c

Just fix namespaces.

When creating a service with sc.exe how to pass in context parameters?

It also important taking in account how you access the Arguments in the code of the application.

In my c# application I used the ServiceBase class:

 class MyService : ServiceBase
{

    protected override void OnStart(string[] args)
    {
       }
 }

I registered my service using

sc create myService binpath= "MeyService.exe arg1 arg2"

But I couldn't access the arguments through the args variable when I run it as a service.

The MSDN documentation suggests not using the Main method to retrieve the binPath or ImagePath arguments. Instead it suggests placing your logic in the OnStart method and then using (C#) Environment.GetCommandLineArgs();.

To access the first arguments arg1 I need to do like this:

class MyService : ServiceBase
 {

    protected override void OnStart(string[] args)
    {

                log.Info("arg1 == "+Environment.GetCommandLineArgs()[1]);

       }
 }

this would print

       arg1 == arg1

Connecting client to server using Socket.io

Have you tried loading the socket.io script not from a relative URL?

You're using:

<script src="socket.io/socket.io.js"></script>

And:

socket.connect('http://127.0.0.1:8080');

You should try:

<script src="http://localhost:8080/socket.io/socket.io.js"></script>

And:

socket.connect('http://localhost:8080');

Switch localhost:8080 with whatever fits your current setup.

Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

see NSURLError.h Define

NSURLErrorUnknown =             -1,
NSURLErrorCancelled =           -999,
NSURLErrorBadURL =              -1000,
NSURLErrorTimedOut =            -1001,
NSURLErrorUnsupportedURL =          -1002,
NSURLErrorCannotFindHost =          -1003,
NSURLErrorCannotConnectToHost =         -1004,
NSURLErrorNetworkConnectionLost =       -1005,
NSURLErrorDNSLookupFailed =         -1006,
NSURLErrorHTTPTooManyRedirects =        -1007,
NSURLErrorResourceUnavailable =         -1008,
NSURLErrorNotConnectedToInternet =      -1009,
NSURLErrorRedirectToNonExistentLocation =   -1010,
NSURLErrorBadServerResponse =       -1011,
NSURLErrorUserCancelledAuthentication =     -1012,
NSURLErrorUserAuthenticationRequired =  -1013,
NSURLErrorZeroByteResource =        -1014,
NSURLErrorCannotDecodeRawData =             -1015,
NSURLErrorCannotDecodeContentData =         -1016,
NSURLErrorCannotParseResponse =             -1017,
NSURLErrorAppTransportSecurityRequiresSecureConnection NS_ENUM_AVAILABLE(10_11, 9_0) = -1022,
NSURLErrorFileDoesNotExist =        -1100,
NSURLErrorFileIsDirectory =         -1101,
NSURLErrorNoPermissionsToReadFile =     -1102,
NSURLErrorDataLengthExceedsMaximum NS_ENUM_AVAILABLE(10_5, 2_0) =   -1103,

// SSL errors
NSURLErrorSecureConnectionFailed =      -1200,
NSURLErrorServerCertificateHasBadDate =     -1201,
NSURLErrorServerCertificateUntrusted =  -1202,
NSURLErrorServerCertificateHasUnknownRoot = -1203,
NSURLErrorServerCertificateNotYetValid =    -1204,
NSURLErrorClientCertificateRejected =   -1205,
NSURLErrorClientCertificateRequired =   -1206,
NSURLErrorCannotLoadFromNetwork =       -2000,

// Download and file I/O errors
NSURLErrorCannotCreateFile =        -3000,
NSURLErrorCannotOpenFile =          -3001,
NSURLErrorCannotCloseFile =         -3002,
NSURLErrorCannotWriteToFile =       -3003,
NSURLErrorCannotRemoveFile =        -3004,
NSURLErrorCannotMoveFile =          -3005,
NSURLErrorDownloadDecodingFailedMidStream = -3006,
NSURLErrorDownloadDecodingFailedToComplete =-3007,

NSURLErrorInternationalRoamingOff NS_ENUM_AVAILABLE(10_7, 3_0) =         -1018,
NSURLErrorCallIsActive NS_ENUM_AVAILABLE(10_7, 3_0) =                    -1019,
NSURLErrorDataNotAllowed NS_ENUM_AVAILABLE(10_7, 3_0) =                  -1020,
NSURLErrorRequestBodyStreamExhausted NS_ENUM_AVAILABLE(10_7, 3_0) =      -1021,

NSURLErrorBackgroundSessionRequiresSharedContainer NS_ENUM_AVAILABLE(10_10, 8_0) = -995,
NSURLErrorBackgroundSessionInUseByAnotherProcess NS_ENUM_AVAILABLE(10_10, 8_0) = -996,
NSURLErrorBackgroundSessionWasDisconnected NS_ENUM_AVAILABLE(10_10, 8_0)= -997,

How to download a branch with git?

git checkout -b branch/name

git pull origin branch/name

Dictionary with list of strings as value

I'd wrap the dictionary in another class:

public class MyListDictionary
{

    private Dictionary<string, List<string>> internalDictionary = new Dictionary<string,List<string>>();

    public void Add(string key, string value)
    {
        if (this.internalDictionary.ContainsKey(key))
        {
            List<string> list = this.internalDictionary[key];
            if (list.Contains(value) == false)
            {
                list.Add(value);
            }
        }
        else
        {
            List<string> list = new List<string>();
            list.Add(value);
            this.internalDictionary.Add(key, list);
        }
    }

}

JSON Structure for List of Objects

The first one is invalid syntax. You cannot have object properties inside a plain array. The second one is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.

This tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.

CSS3 :unchecked pseudo-class

The way I handled this was switching the className of a label based on a condition. This way you only need one label and you can have different classes for different states... Hope that helps!

Print newline in PHP in single quotes

No, according to documentation, PHP recognize no special symbol in single quotes. And there is no single reason to use single quotes as much as possible

How to set user environment variables in Windows Server 2008 R2 as a normal user?

Under "Start" enter "environment" in the search field. That will list the option to change the system variables directly in the start menu.

Run Button is Disabled in Android Studio

I opened the wrong folder.... Verify is your root folder in Android studio has the build.gradle file.

How to downgrade to older version of Gradle

Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here: enter image description here

And check your build.gradle of project,change dependency of gradle,like this:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.1'
    }
}

SQL Server 2008- Get table constraints

I used the following query to retrieve the information of constraints in the SQL Server 2012, and works perfectly. I hope it would be useful for you.

SELECT 
    tab.name AS [Table]
    ,tab.id AS [Table Id]
    ,constr.name AS [Constraint Name]
    ,constr.xtype AS [Constraint Type]
    ,CASE constr.xtype WHEN 'PK' THEN 'Primary Key' WHEN 'UQ' THEN 'Unique' ELSE '' END AS [Constraint Name]
    ,i.index_id AS [Index ID]
    ,ic.column_id AS [Column ID]
    ,clmns.name AS [Column Name]
    ,clmns.max_length AS [Column Max Length]
    ,clmns.precision AS [Column Precision]
    ,CASE WHEN clmns.is_nullable = 0 THEN 'NO' ELSE 'YES' END AS [Column Nullable]
    ,CASE WHEN clmns.is_identity = 0 THEN 'NO' ELSE 'YES' END AS [Column IS IDENTITY]
FROM SysObjects AS tab
INNER JOIN SysObjects AS constr ON(constr.parent_obj = tab.id AND constr.type = 'K')
INNER JOIN sys.indexes AS i ON( (i.index_id > 0 and i.is_hypothetical = 0) AND (i.object_id=tab.id) AND i.name = constr.name )
INNER JOIN sys.index_columns AS ic ON (ic.column_id > 0 and (ic.key_ordinal > 0 or ic.partition_ordinal = 0 or ic.is_included_column != 0)) 
                                    AND (ic.index_id=CAST(i.index_id AS int) 
                                    AND ic.object_id=i.object_id)
INNER JOIN sys.columns AS clmns ON clmns.object_id = ic.object_id and clmns.column_id = ic.column_id
WHERE tab.xtype = 'U'
ORDER BY tab.name

Calculate the center point of multiple latitude/longitude coordinate pairs

Dart Implementation for Flutter to find Center point for Multiple Latitude, Longitude.

import math package

import 'dart:math' as math;

Latitude and Longitude List

List<LatLng> latLongList = [LatLng(12.9824, 80.0603),LatLng(13.0569,80.2425,)];

LatLng getCenterLatLong(List<LatLng> latLongList) {
    double pi = math.pi / 180;
    double xpi = 180 / math.pi;
    double x = 0, y = 0, z = 0;

    if(latLongList.length==1)
    {
        return latLongList[0];
    }
    for (int i = 0; i < latLongList.length; i++) {
      double latitude = latLongList[i].latitude * pi;
      double longitude = latLongList[i].longitude * pi;
      double c1 = math.cos(latitude);
      x = x + c1 * math.cos(longitude);
      y = y + c1 * math.sin(longitude);
      z = z + math.sin(latitude);
    }

    int total = latLongList.length;
    x = x / total;
    y = y / total;
    z = z / total;

    double centralLongitude = math.atan2(y, x);
    double centralSquareRoot = math.sqrt(x * x + y * y);
    double centralLatitude = math.atan2(z, centralSquareRoot);

    return LatLng(centralLatitude*xpi,centralLongitude*xpi);
}

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Use the Bootstrap Customizer to generate a version of Bootstrap that has a taller navbar. The value you want to change is @navbar-height in the Navbar section.

Inspect your current implementation to see how tall your navbar is with the 50px brand image, and use that calculated height in the Customizer.

How to call a parent class function from derived class function?

If your base class is called Base, and your function is called FooBar() you can call it directly using Base::FooBar()

void Base::FooBar()
{
   printf("in Base\n");
}

void ChildOfBase::FooBar()
{
  Base::FooBar();
}

How do I use TensorFlow GPU?

I tried following the above tutorial. Thing is tensorflow changes a lot and so do the NVIDIA versions needed for running on a GPU. The next issue is that your driver version determines your toolkit version etc. As of today this information about the software requirements should shed some light on how they interplay:

NVIDIA® GPU drivers —CUDA 9.0 requires 384.x or higher.
CUDA® Toolkit —TensorFlow supports CUDA 9.0.
CUPTI ships with the CUDA Toolkit.
cuDNN SDK (>= 7.2) Note: Make sure your GPU has compute compatibility >3.0
(Optional) NCCL 2.2 for multiple GPU support.
(Optional) TensorRT 4.0 to improve latency and throughput for inference on some models.

And here you'll find the up-to-date requirements stated by tensorflow (which will hopefully be updated by them on a regular basis).

foreach vs someList.ForEach(){}

Behind the scenes, the anonymous delegate gets turned into an actual method so you could have some overhead with the second choice if the compiler didn't choose to inline the function. Additionally, any local variables referenced by the body of the anonymous delegate example would change in nature because of compiler tricks to hide the fact that it gets compiled to a new method. More info here on how C# does this magic:

http://blogs.msdn.com/oldnewthing/archive/2006/08/04/688527.aspx

How to send email to multiple recipients using python smtplib?

The solution below worked for me. It successfully sends an email to multiple recipients, including "CC" and "BCC."

toaddr = ['mailid_1','mailid_2']
cc = ['mailid_3','mailid_4']
bcc = ['mailid_5','mailid_6']
subject = 'Email from Python Code'
fromaddr = 'sender_mailid'
message = "\n  !! Hello... !!"

msg['From'] = fromaddr
msg['To'] = ', '.join(toaddr)
msg['Cc'] = ', '.join(cc)
msg['Bcc'] = ', '.join(bcc)
msg['Subject'] = subject

s.sendmail(fromaddr, (toaddr+cc+bcc) , message)

How to SELECT based on value of another SELECT

SELECT x.name, x.summary, (x.summary / COUNT(*)) as percents_of_total
FROM tbl t
INNER JOIN 
(SELECT name, SUM(value) as summary
FROM tbl
WHERE year BETWEEN 2000 AND 2001
GROUP BY name) x ON x.name = t.name
GROUP BY x.name, x.summary

How to round a numpy array?

If you want the output to be

array([1.6e-01, 9.9e-01, 3.6e-04])

the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:

def my_round(value, N):
    exponent = np.ceil(np.log10(value))
    return 10**exponent*np.round(value*10**(-exponent), N)

For a general solution handling 0 and negative values as well, you can do something like this:

def my_round(value, N):
    value = np.asarray(value).copy()
    zero_mask = (value == 0)
    value[zero_mask] = 1.0
    sign_mask = (value < 0)
    value[sign_mask] *= -1
    exponent = np.ceil(np.log10(value))
    result = 10**exponent*np.round(value*10**(-exponent), N)
    result[sign_mask] *= -1
    result[zero_mask] = 0.0
    return result

Laravel redirect back to original destination after login

Use Redirect;

Then use this:

return Redirect::back();

jQuery remove selected option from this

this isn't a css selector. you can avoid spelling the id of this by passing it as a context:

$('option:selected', this).remove();

http://api.jquery.com/jQuery/

Sorting A ListView By Column

Forget about your custom sorter. Start over using the code at the following page. It will show you how to define a class that inherits from the IComparer interface. Each line is commented out, so you can actually see what is happening. The only potential complication is how you are retrieving your Listview Items from your Listview control. Get those squared away and all you need to do is copy and paste the IComparer interface class and the columnClick method.

http://support.microsoft.com/kb/319401

How to remove all .svn directories from my application directories

Alternatively, if you want to export a copy without modifying the working copy, you can use rsync:

rsync -a --exclude .svn path/to/working/copy path/to/export

Return multiple values to a method caller

Future version of C# is going to include named tuples. Have a look at this channel9 session for the demo https://channel9.msdn.com/Events/Build/2016/B889

Skip to 13:00 for the tuple stuff. This will allow stuff like:

(int sum, int count) Tally(IEnumerable<int> list)
{
// calculate stuff here
return (0,0)
}

int resultsum = Tally(numbers).sum

(incomplete example from video)

Should I put #! (shebang) in Python scripts, and what form should it take?

Absolute vs Logical Path:

This is really a question about whether the path to the Python interpreter should be absolute or Logical (/usr/bin/env) in respect to portability.

Encountering other answers on this and other Stack sites which talked about the issue in a general way without supporting proofs, I've performed some really, REALLY, granular testing & analysis on this very question on the unix.stackexchange.com. Rather than paste that answer here, I'll point those interested to the comparative analysis to that answer:

https://unix.stackexchange.com/a/566019/334294

Being a Linux Engineer, my goal is always to provide the most suitable, optimized hosts for my developer clients, so the issue of Python environments was something I really needed a solid answer to. My view after the testing was that the logical path in the she-bang was the better of the (2) options.

Egit rejected non-fast-forward

Configure After pushing the code when you get a rejected message, click on configure and click Add spec as shown in this picture

Source ref and Destination ref Drop down and click on the ref/heads/yourbranchname and click on Add Spec again

enter image description here Make sure you select the force update

enter image description here Finally save and push the code to the repo

Node.js EACCES error when listening on most ports

Try authbind:

http://manpages.ubuntu.com/manpages/hardy/man1/authbind.1.html

After installing, you can add a file with the name of the port number you want to use in the following folder: /etc/authbind/byport/

Give it 500 permissions using chmod and change the ownership to the user you want to run the program under.

After that, do "authbind node ..." as that user in your project.

Equal height rows in CSS Grid Layout

The short answer is that setting grid-auto-rows: 1fr; on the grid container solves what was asked.

https://codepen.io/Hlsg/pen/EXKJba

HTML5 phone number validation with pattern

This code will accept all country code with + sign

<input type="text" pattern="[0-9]{5}[-][0-9]{7}[-][0-9]{1}"/>

Some countries allow a single "0" character instead of "+" and others a double "0" character instead of the "+". Neither are standard.

Bootstrap 4 card-deck with number of columns based on viewport

@Zim provided a great solution above (well deserved up-vote from me), however, it didn't quite fit what I needed since I was implementing this in Jekyll and wanted my card deck to automatically update every time I added a post to my site. Growing a card deck such as this with each new post is straight forward in Jekyll, the challenge was to correctly place the breakpoints. My solution make use of additional liquid tags and modulo mathematics.

While this question is old, I came across it and found it useful, and maybe someday someone will come along wanting to do this with Jekyll.

<div class = "container">
  <div class = "card-deck">

    {% for post in site.posts %}
      <div class = "card border-0 mt-2">
        <a href = "{{ post.url }}"><img src = "{{ site.baseurl }}{{ post.image }}" class = "mx-auto" alt = "..."></a>
        <div class = "card-body">
          <h5 class = "card-title"><a href = "{{ post.url }}">{{ post.title }}</a></h5>
          <span>Published: {{ post.date | date_to_long_string }} </span>
          <p class = "text-muted">{{ post.excerpt }}</p>
        </div>
        <div class = "card-footer bg-white border-0"><a href = "{{ post.url }}" class = "btn btn-primary">Read more</a></div>
      </div>

      <!-- Use modulo to add divs to handle break points -->
      {% assign sm = forloop.index | modulo: 2 %}
      {% assign md = forloop.index | modulo: 3 %}
      {% assign lg = forloop.index | modulo: 4 %}
      {% assign xl = forloop.index | modulo: 5 %}

      {% if sm == 0 %}
        <div class="w-100 d-none d-sm-block d-md-none"><!-- wrap every 2 on sm--></div>
      {% endif %}

      {% if md == 0 %}
        <div class="w-100 d-none d-md-block d-lg-none"><!-- wrap every 3 on md--></div>
      {% endif %}

      {% if lg == 0 %}
        <div class="w-100 d-none d-lg-block d-xl-none"><!-- wrap every 4 on lg--></div>
      {% endif %}

      {% if xl == 0 %}
        <div class="w-100 d-none d-xl-block"><!-- wrap every 5 on xl--></div>
      {% endif %}

    {% endfor %}
  </div>
</div>

This whole code block can be used directly in a website or saved in your Jekyll project _includes folder.

What is the simplest way to get indented XML with line breaks from XmlDocument?

Based on the other answers, I looked into XmlTextWriter and came up with the following helper method:

static public string Beautify(this XmlDocument doc)
{
    StringBuilder sb = new StringBuilder();
    XmlWriterSettings settings = new XmlWriterSettings
    {
        Indent = true,
        IndentChars = "  ",
        NewLineChars = "\r\n",
        NewLineHandling = NewLineHandling.Replace
    };
    using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
        doc.Save(writer);
    }
    return sb.ToString();
}

It's a bit more code than I hoped for, but it works just peachy.

What is default list styling (CSS)?

You cannot. Whenever there is any style sheet being applied that assigns a property to an element, there is no way to get to the browser defaults, for any instance of the element.

The (disputable) idea of reset.css is to get rid of browser defaults, so that you can start your own styling from a clean desk. No version of reset.css does that completely, but to the extent they do, the author using reset.css is supposed to completely define the rendering.

IntelliJ: Working on multiple projects

As of release 2019.2, this is as easy as File->Attach Project.

File->Attach Project

See: https://youtrack.jetbrains.com/issue/WEB-7968

.NET 4.0 has a new GAC, why?

I also wanted to know why 2 GAC and found the following explanation by Mark Miller in the comments section of .NET 4.0 has 2 Global Assembly Cache (GAC):

Mark Miller said... June 28, 2010 12:13 PM

Thanks for the post. "Interference issues" was intentionally vague. At the time of writing, the issues were still being investigated, but it was clear there were several broken scenarios.

For instance, some applications use Assemby.LoadWithPartialName to load the highest version of an assembly. If the highest version was compiled with v4, then a v2 (3.0 or 3.5) app could not load it, and the app would crash, even if there were a version that would have worked. Originally, we partitioned the GAC under it's original location, but that caused some problems with windows upgrade scenarios. Both of these involved code that had already shipped, so we moved our (version-partitioned GAC to another place.

This shouldn't have any impact to most applications, and doesn't add any maintenance burden. Both locations should only be accessed or modified using the native GAC APIs, which deal with the partitioning as expected. The places where this does surface are through APIs that expose the paths of the GAC such as GetCachePath, or examining the path of mscorlib loaded into managed code.

It's worth noting that we modified GAC locations when we released v2 as well when we introduced architecture as part of the assembly identity. Those added GAC_MSIL, GAC_32, and GAC_64, although all still under %windir%\assembly. Unfortunately, that wasn't an option for this release.

Hope it helps future readers.

Java Object Null Check for method

If you are using Java 7 You can use Objects.requireNotNull(object[, optionalMessage]); - to check if the parameter is null. To check if each element is not null just use

if(null != books[i]){/*do stuff*/}

Example:

public static double calculateInventoryTotal(Book[] books){
    Objects.requireNotNull(books, "Books must not be null");

    double total = 0;

    for (int i = 0; i < books.length; i++){
        if(null != book[i]){
            total += books[i].getPrice();
        }
    }

    return total;
}

cat, grep and cut - translated to python

In Python, without external dependencies, it is something like this (untested):

with open("filename") as origin:
    for line in origin:
        if not "something" in line:
           continue
        try:
            print line.split('"')[1]
        except IndexError:
            print

How do I check if a string is a number (float)?

In case you are looking for parsing (positive, unsigned) integers instead of floats, you can use the isdigit() function for string objects.

>>> a = "03523"
>>> a.isdigit()
True
>>> b = "963spam"
>>> b.isdigit()
False

String Methods - isdigit(): Python2, Python3

There's also something on Unicode strings, which I'm not too familiar with Unicode - Is decimal/decimal

Is there a way I can capture my iPhone screen as a video?

Here's my solution in a nutshell:

In recent years, when needing to produce moving visual content from the interface of an iOS app, I would require the developer provide a compiling of the app designed for the Simulator, (must be separately compiled because the apps are, by default compiled to run on the iPhone's ARM processor, whereas the Simulator runs on the Mac's Intel processor). This would then be screen captured on the Mac with something like Snapz Pro, Screenflow or something similar.

Beyond that, typical solutions required jailbreaking the device and installing a screen capture application sourced from the Cydia Store.

With the introduction of the iPad 2, Apple enabled full interface mirrored video output via either an authorized dock connector to HDMI dongle, or a dock connector to VGA dongle. (Note: Apple's composite and component options do not port mirrored content.) While the typical intent for these output mechanisms are to display the interface content to an external projector or High Definition Television, it is possible to record this mirrored content with a device capable of recording or transcoding content from such an incoming source. This option was also made possible with the introduction of the iPhone 4S. Quite often, recording this video content is done with HDMI capture cards installed on the capturing computer, such as those produced by Black Magic or AJA, among others. This is, or course limited to using computers that are capable of having such a capture card installed. Other options may include some HDMI record-enabled DVR devices (though many detect and disable such options) or firewire-based transcoding devices (like the Grass Valley ADVC-HD50, which I use).

Since getting the iPad 2 earlier this year, I have been using the Grass Valley ADVC HD50 to capture iOS screen motion from dock connected HDMI to a HDV compatible video capture application on my Mac. It has thus far worked flawlessly.

Here is an example from a video I recorded showing such captured content from both the iPHone 4S and the iPad 2.

http://youtu.be/k7jlPx8NAmw

However, now that Apple has enabled wireless iOS mirroring via Airplay in iOS 5, I find it is now much more convenient to connect an Apple TV device to the Grass Vally ADVC HD50, and capture the iOS interface screen recording wirelessly.

Here is a recent short video example in which the iPhone 4S interface was captured wirelessly via Airplay mirroring.

http://youtu.be/UKsixjcCXdI

I hope this helps.

Open page in new window without popup blocking

PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:

I opened the popup directly on the users click, directed the url to about:blank and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made

var myWindow = window.open("about:blank",'name','height=500,width=550');

Then, when my request is successful, I open my callback url in the window

function showWindow(win, url) {
     win.open(url,'name','height=500,width=550');
}

Case insensitive 'in'

I needed this for a dictionary instead of list, Jochen solution was the most elegant for that case so I modded it a bit:

class CaseInsensitiveDict(dict):
    ''' requests special dicts are case insensitive when using the in operator,
     this implements a similar behaviour'''
    def __contains__(self, name): # implements `in`
        return name.casefold() in (n.casefold() for n in self.keys())

now you can convert a dictionary like so USERNAMESDICT = CaseInsensitiveDict(USERNAMESDICT) and use if 'MICHAEL89' in USERNAMESDICT:

Use dynamic variable names in `dplyr`

In the new release of dplyr (0.6.0 awaiting in April 2017), we can also do an assignment (:=) and pass variables as column names by unquoting (!!) to not evaluate it

 library(dplyr)
 multipetalN <- function(df, n){
      varname <- paste0("petal.", n)
      df %>%
         mutate(!!varname := Petal.Width * n)
 }

 data(iris)
 iris1 <- tbl_df(iris)
 iris2 <- tbl_df(iris)
 for(i in 2:5) {
     iris2 <- multipetalN(df=iris2, n=i)
 }   

Checking the output based on @MrFlick's multipetal applied on 'iris1'

identical(iris1, iris2)
#[1] TRUE

Merge/flatten an array of arrays

Generic procedures mean we don't have to rewrite complexity each time we need to utilize a specific behaviour.

concatMap (or flatMap) is exactly what we need in this situation.

_x000D_
_x000D_
// concat :: ([a],[a]) -> [a]_x000D_
const concat = (xs,ys) =>_x000D_
  xs.concat (ys)_x000D_
_x000D_
// concatMap :: (a -> [b]) -> [a] -> [b]_x000D_
const concatMap = f => xs =>_x000D_
  xs.map(f).reduce(concat, [])_x000D_
_x000D_
// id :: a -> a_x000D_
const id = x =>_x000D_
  x_x000D_
_x000D_
// flatten :: [[a]] -> [a]_x000D_
const flatten =_x000D_
  concatMap (id)_x000D_
_x000D_
// your sample data_x000D_
const data =_x000D_
  [["$6"], ["$12"], ["$25"], ["$25"], ["$18"], ["$22"], ["$10"]]_x000D_
_x000D_
console.log (flatten (data))
_x000D_
_x000D_
_x000D_

foresight

And yes, you guessed it correctly, it only flattens one level, which is exactly how it should work

Imagine some data set like this

_x000D_
_x000D_
// Player :: (String, Number) -> Player_x000D_
const Player = (name,number) =>_x000D_
  [ name, number ]_x000D_
_x000D_
// team :: ( . Player) -> Team_x000D_
const Team = (...players) =>_x000D_
  players_x000D_
_x000D_
// Game :: (Team, Team) -> Game_x000D_
const Game = (teamA, teamB) =>_x000D_
  [ teamA, teamB ]_x000D_
_x000D_
// sample data_x000D_
const teamA =_x000D_
  Team (Player ('bob', 5), Player ('alice', 6))_x000D_
_x000D_
const teamB =_x000D_
  Team (Player ('ricky', 4), Player ('julian', 2))_x000D_
_x000D_
const game =_x000D_
  Game (teamA, teamB)_x000D_
_x000D_
console.log (game)_x000D_
// [ [ [ 'bob', 5 ], [ 'alice', 6 ] ],_x000D_
//   [ [ 'ricky', 4 ], [ 'julian', 2 ] ] ]
_x000D_
_x000D_
_x000D_

Ok, now say we want to print a roster that shows all the players that will be participating in game

const gamePlayers = game =>
  flatten (game)

gamePlayers (game)
// => [ [ 'bob', 5 ], [ 'alice', 6 ], [ 'ricky', 4 ], [ 'julian', 2 ] ]

If our flatten procedure flattened nested arrays too, we'd end up with this garbage result …

const gamePlayers = game =>
  badGenericFlatten(game)

gamePlayers (game)
// => [ 'bob', 5, 'alice', 6, 'ricky', 4, 'julian', 2 ]

rollin' deep, baby

That's not to say sometimes you don't want to flatten nested arrays, too – only that shouldn't be the default behaviour.

We can make a deepFlatten procedure with ease …

_x000D_
_x000D_
// concat :: ([a],[a]) -> [a]_x000D_
const concat = (xs,ys) =>_x000D_
  xs.concat (ys)_x000D_
_x000D_
// concatMap :: (a -> [b]) -> [a] -> [b]_x000D_
const concatMap = f => xs =>_x000D_
  xs.map(f).reduce(concat, [])_x000D_
_x000D_
// id :: a -> a_x000D_
const id = x =>_x000D_
  x_x000D_
_x000D_
// flatten :: [[a]] -> [a]_x000D_
const flatten =_x000D_
  concatMap (id)_x000D_
_x000D_
// deepFlatten :: [[a]] -> [a]_x000D_
const deepFlatten =_x000D_
  concatMap (x =>_x000D_
    Array.isArray (x) ? deepFlatten (x) : x)_x000D_
_x000D_
// your sample data_x000D_
const data =_x000D_
  [0, [1, [2, [3, [4, 5], 6]]], [7, [8]], 9]_x000D_
_x000D_
console.log (flatten (data))_x000D_
// [ 0, 1, [ 2, [ 3, [ 4, 5 ], 6 ] ], 7, [ 8 ], 9 ]_x000D_
_x000D_
console.log (deepFlatten (data))_x000D_
// [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
_x000D_
_x000D_
_x000D_

There. Now you have a tool for each job – one for squashing one level of nesting, flatten, and one for obliterating all nesting deepFlatten.

Maybe you can call it obliterate or nuke if you don't like the name deepFlatten.


Don't iterate twice !

Of course the above implementations are clever and concise, but using a .map followed by a call to .reduce means we're actually doing more iterations than necessary

Using a trusty combinator I'm calling mapReduce helps keep the iterations to a minium; it takes a mapping function m :: a -> b, a reducing function r :: (b,a) ->b and returns a new reducing function - this combinator is at the heart of transducers; if you're interested, I've written other answers about them

_x000D_
_x000D_
// mapReduce = (a -> b, (b,a) -> b, (b,a) -> b)_x000D_
const mapReduce = (m,r) =>_x000D_
  (acc,x) => r (acc, m (x))_x000D_
_x000D_
// concatMap :: (a -> [b]) -> [a] -> [b]_x000D_
const concatMap = f => xs =>_x000D_
  xs.reduce (mapReduce (f, concat), [])_x000D_
_x000D_
// concat :: ([a],[a]) -> [a]_x000D_
const concat = (xs,ys) =>_x000D_
  xs.concat (ys)_x000D_
_x000D_
// id :: a -> a_x000D_
const id = x =>_x000D_
  x_x000D_
_x000D_
// flatten :: [[a]] -> [a]_x000D_
const flatten =_x000D_
  concatMap (id)_x000D_
  _x000D_
// deepFlatten :: [[a]] -> [a]_x000D_
const deepFlatten =_x000D_
  concatMap (x =>_x000D_
    Array.isArray (x) ? deepFlatten (x) : x)_x000D_
_x000D_
// your sample data_x000D_
const data =_x000D_
  [ [ [ 1, 2 ],_x000D_
      [ 3, 4 ] ],_x000D_
    [ [ 5, 6 ],_x000D_
      [ 7, 8 ] ] ]_x000D_
_x000D_
console.log (flatten (data))_x000D_
// [ [ 1. 2 ], [ 3, 4 ], [ 5, 6 ], [ 7, 8 ] ]_x000D_
_x000D_
console.log (deepFlatten (data))_x000D_
// [ 1, 2, 3, 4, 5, 6, 7, 8 ]
_x000D_
_x000D_
_x000D_

How to invoke the super constructor in Python?

In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:

Python-2.x

class A(object):
 def __init__(self):
   print "world"

class B(A):
 def __init__(self):
   print "hello"
   super(B, self).__init__()

Python-3.x

class A(object):
 def __init__(self):
   print("world")

class B(A):
 def __init__(self):
   print("hello")
   super().__init__()

super() is now equivalent to super(<containing classname>, self) as per the docs.

Make the console wait for a user input to close

You can just use nextLine(); as pause

import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);

void Read()
{
     System.out.print("Press any key to continue . . . ");
     scan.nextLine();
}

However any button you press except Enter means you will have to press Enter after that but I found it better than scan.next();

When should I use curly braces for ES6 import?

Dan Abramov's answer explains about the default exports and named exports.

Which to use?

Quoting David Herman: ECMAScript 6 favors the single/default export style, and gives the sweetest syntax to importing the default. Importing named exports can and even should be slightly less concise.

However, in TypeScript named export is favored because of refactoring. Example, if you default export a class and rename it, the class name will change only in that file and not in the other references, with named exports class name will be renamed in all the references. Named exports is also preferred for utilities.

Overall use whatever you prefer.

Additional

Default export is actually a named export with name default, so default export can be imported as:

import {default as Sample} from '../Sample.js';

Why do people write #!/usr/bin/env python on the first line of a Python script?

The exec system call of the Linux kernel understands shebangs (#!) natively

When you do on bash:

./something

on Linux, this calls the exec system call with the path ./something.

This line of the kernel gets called on the file passed to exec: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_script.c#L25

if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))

It reads the very first bytes of the file, and compares them to #!.

If the comparison is true, then the rest of the line is parsed by the Linux kernel, which makes another exec call with:

  • executable: /usr/bin/env
  • first argument: python
  • second argument: script path

therefore equivalent to:

/usr/bin/env python /path/to/script.py

env is an executable that searches PATH to e.g. find /usr/bin/python, and then finally calls:

/usr/bin/python /path/to/script.py

The Python interpreter does see the #! line in the file, but # is the comment character in Python, so that line just gets ignored as a regular comment.

And yes, you can make an infinite loop with:

printf '#!/a\n' | sudo tee /a
sudo chmod +x /a
/a

Bash recognizes the error:

-bash: /a: /a: bad interpreter: Too many levels of symbolic links

#! just happens to be human readable, but that is not required.

If the file started with different bytes, then the exec system call would use a different handler. The other most important built-in handler is for ELF executable files: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_elf.c#L1305 which checks for bytes 7f 45 4c 46 (which also happens to be human readable for .ELF). Let's confirm that by reading the 4 first bytes of /bin/ls, which is an ELF executable:

head -c 4 "$(which ls)" | hd 

output:

00000000  7f 45 4c 46                                       |.ELF|
00000004                                                                 

So when the kernel sees those bytes, it takes the ELF file, puts it into memory correctly, and starts a new process with it. See also: How does kernel get an executable binary file running under linux?

Finally, you can add your own shebang handlers with the binfmt_misc mechanism. For example, you can add a custom handler for .jar files. This mechanism even supports handlers by file extension. Another application is to transparently run executables of a different architecture with QEMU.

I don't think POSIX specifies shebangs however: https://unix.stackexchange.com/a/346214/32558 , although it does mention in on rationale sections, and in the form "if executable scripts are supported by the system something may happen". macOS and FreeBSD also seem to implement it however.

PATH search motivation

Likely, one big motivation for the existence of shebangs is the fact that in Linux, we often want to run commands from PATH just as:

basename-of-command

instead of:

/full/path/to/basename-of-command

But then, without the shebang mechanism, how would Linux know how to launch each type of file?

Hardcoding the extension in commands:

 basename-of-command.py

or implementing PATH search on every interpreter:

python basename-of-command

would be a possibility, but this has the major problem that everything breaks if we ever decide to refactor the command into another language.

Shebangs solve this problem beautifully.

How to handle click event in Button Column in Datagridview?

This solves my problem.

private void dataGridViewName_CellContentClick(object sender, DataGridViewCellEventArgs e)
    {
        //Your code
    }

SAP Crystal Reports runtime for .Net 4.0 (64-bit)

I have found a variety of runtimes including Visual Studio(VS) versions are available at http://scn.sap.com/docs/DOC-7824

How to paginate with Mongoose in Node.js?

you can use the following line of code as well

per_page = parseInt(req.query.per_page) || 10
page_no = parseInt(req.query.page_no) || 1
var pagination = {
  limit: per_page ,
  skip:per_page * (page_no - 1)
}
users = await User.find({<CONDITION>}).limit(pagination.limit).skip(pagination.skip).exec()

this code will work in latest version of mongo

How can I write these variables into one line of code in C#?

You should try this one:

Console.WriteLine("{0}.{1}.{2}", mon, da, yet);

See http://www.dotnetperls.com/console-writeline for more details.

Spring Data JPA findOne() change to Optional how to use this?

From at least, the 2.0 version, Spring-Data-Jpa modified findOne().
Now, findOne() has neither the same signature nor the same behavior.
Previously, it was defined in the CrudRepository interface as:

T findOne(ID primaryKey);

Now, the single findOne() method that you will find in CrudRepository is the one defined in the QueryByExampleExecutor interface as:

<S extends T> Optional<S> findOne(Example<S> example);

That is implemented finally by SimpleJpaRepository, the default implementation of the CrudRepository interface.
This method is a query by example search and you don't want that as a replacement.

In fact, the method with the same behavior is still there in the new API, but the method name has changed.
It was renamed from findOne() to findById() in the CrudRepository interface :

Optional<T> findById(ID id); 

Now it returns an Optional, which is not so bad to prevent NullPointerException.

So, the actual method to invoke is now Optional<T> findById(ID id).

How to use that?
Learning Optional usage. Here's important information about its specification:

A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (return a default value if value not present) and ifPresent() (execute a block of code if the value is present).


Some hints on how to use Optional with Optional<T> findById(ID id).

Generally, as you look for an entity by id, you want to return it or make a particular processing if that is not retrieved.

Here are three classical usage examples.

  1. Suppose that if the entity is found you want to get it otherwise you want to get a default value.

You could write :

Foo foo = repository.findById(id)
                    .orElse(new Foo());

or get a null default value if it makes sense (same behavior as before the API change) :

Foo foo = repository.findById(id)
                    .orElse(null);
  1. Suppose that if the entity is found you want to return it, else you want to throw an exception.

You could write :

return repository.findById(id)
        .orElseThrow(() -> new EntityNotFoundException(id));
  1. Suppose you want to apply a different processing according to if the entity is found or not (without necessarily throwing an exception).

You could write :

Optional<Foo> fooOptional = fooRepository.findById(id);
if (fooOptional.isPresent()) {
    Foo foo = fooOptional.get();
    // processing with foo ...
} else {
    // alternative processing....
}

Debugging in Maven?

If you don't want to be IDE dependent and want to work directly with the command line, you can use 'jdb' (Java Debugger)

As mentioned by Samuel with small modification (set suspend=y instead of suspend=n, y means yes which suspends the program and not run it so you that can set breakpoints to debug it, if suspend=n means it may run the program to completion before you can even debug it)

On the directory which contains your pom.xml, execute:

mvn exec:exec -Dexec.executable="java" -Dexec.args="-classpath %classpath -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=1044 com.mycompany.app.App"

Then, open up a new terminal and execute:

jdb -attach 1044

You can then use jdb to debug your program!=)

Sources: Java jdb remote debugging command line tool

What is the difference between state and props in React?

Props are values, objects or arrays passed into a component on render. These props are often values needed within the component to create the UI, set certain default functionality or used to populate fields. Props can also come in the form of functions passed down from the parent component that can be invoked by the child.

State is managed within the component (child or parent).

Here is a definition I found to support this:

enter image description here

Send an Array with an HTTP Get

I know this post is really old, but I have to reply because although BalusC's answer is marked as correct, it's not completely correct.

You have to write the query adding "[]" to foo like this:

foo[]=val1&foo[]=val2&foo[]=val3

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.innerHTML = 'Hello, World!';
newTH.onclick = function () {
    this.parentElement.removeChild(this);
};

var table = document.getElementById('content');
table.appendChild(newTH);

Working example: http://jsfiddle.net/23tBM/

You can also just hide with this.style.display = 'none'.

Cannot connect to MySQL Workbench on mac. Can't connect to MySQL server on '127.0.0.1' (61) Mac Macintosh

I am using those commands on MacOs after getting the same error

sudo /usr/local/mysql/support-files/mysql.server start

sudo /usr/local/mysql/support-files/mysql.server stop

sudo /usr/local/mysql/support-files/mysql.server restart

how to read a long multiline string line by line in python

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines() is the way to go. I will leave this answer nevertheless as reference.

Old (incorrect) answer:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)

Launch Minecraft from command line - username and password as prefix

This answer is going to briefly explain how the native files are handled on the latest launcher.

As of 4/29/2017 the Minecraft launcher for Windows extracts all native files and places them info %APPDATA%\Local\Temp{random folder}. That folder is temporary and is deleted once the javaw.exe process finishes (when Minecraft is closed). The location of that temporary folder must be provided in the launch arguments as the value of

-Djava.library.path=

Also, the latest launcher (2.0.847) does not show you the launch arguments so if you need to check them yourself you can do so under the Task Manager (simply enable the Command Line tab and expand it) or by using the WMIC utility as explained here.

Hope this helps some people who are still interested in doing this in 2017.

How to re-enable right click so that I can inspect HTML elements in Chrome?

Tested in Chrome 60.0.3112.78.

Some of the above methods work, but the easiest in my opinion is:

  1. Open dev tools (Shift+Control+i).

  2. Select the "Elements" tab, and then the "Event Listeners" tab.

  3. Hover over the elements/listener. A "Remove" button will show up.

  4. Click "Remove".

E.g. see photo.

Remove event listener

Jinja2 template not rendering if-elif-else statement properly

You are testing if the values of the variables error and Already are present in RepoOutput[RepoName.index(repo)]. If these variables don't exist then an undefined object is used.

Both of your if and elif tests therefore are false; there is no undefined object in the value of RepoOutput[RepoName.index(repo)].

I think you wanted to test if certain strings are in the value instead:

{% if "error" in RepoOutput[RepoName.index(repo)] %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% elif "Already" in RepoOutput[RepoName.index(repo) %}
    <td id="good"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% else %}
    <td id="error"> {{ RepoOutput[RepoName.index(repo)] }} </td>
{% endif %}
</tr>

Other corrections I made:

  • Used {% elif ... %} instead of {$ elif ... %}.
  • moved the </tr> tag out of the if conditional structure, it needs to be there always.
  • put quotes around the id attribute

Note that most likely you want to use a class attribute instead here, not an id, the latter must have a value that must be unique across your HTML document.

Personally, I'd set the class value here and reduce the duplication a little:

{% if "Already" in RepoOutput[RepoName.index(repo)] %}
    {% set row_class = "good" %}
{% else %}
    {% set row_class = "error" %}
{% endif %}
<td class="{{ row_class }}"> {{ RepoOutput[RepoName.index(repo)] }} </td>

Why doesn't java.util.Set have get(int index)?

The only reason I can think of for using a numerical index in a set would be for iteration. For that, use

for(A a : set) { 
   visit(a); 
}

AngularJs: How to set radio button checked based on model

Ended up just using the built-in angular attribute ng-checked="model"

How to avoid 'undefined index' errors?

You can use isset() without losing the concatenation:

//snip
$str = 'something'
 . ( isset($output['alternate_title']) ? $output['alternate_title'] : '' )
 . ( isset($output['access_info']) ? $output['access_info'] : '' )
 . //etc.

You could also write a function to return the string if it is set - this probably isn't very efficient:

function getIfSet(& $var) {
    if (isset($var)) {
        return $var;
    }
    return null;
}

$str = getIfSet($output['alternate_title']) . getIfSet($output['access_info']) //etc

You won't get a notice because the variable is passed by reference.

How does the bitwise complement operator (~ tilde) work?

Simply ...........

As 2's complement of any number we can calculate by inverting all 1s to 0's and vice-versa than we add 1 to it..

Here N= ~N produce results -(N+1) always. Because system store data in form of 2's complement which means it stores ~N like this.

  ~N = -(~(~N)+1) =-(N+1). 

For example::

  N = 10  = 1010
  Than ~N  = 0101
  so ~(~N) = 1010
  so ~(~N) +1 = 1011 

Now point is from where Minus comes. My opinion is suppose we have 32 bit register which means 2^31 -1 bit involved in operation and to rest one bit which change in earlier computation(complement) stored as sign bit which is 1 usually. And we get result as ~10 = -11.

~(-11) =10 ;

The above is true if printf("%d",~0); we get result: -1;

But printf("%u",~0) than result: 4294967295 on 32 bit machine.

Escape single quote character for use in an SQLite query

In bash scripts, I found that escaping double quotes around the value was necessary for values that could be null or contained characters that require escaping (like hyphens).

In this example, columnA's value could be null or contain hyphens.:

sqlite3 $db_name "insert into foo values (\"$columnA\", $columnB)";

Get characters after last / in url

You can use substr and strrchr:

$url = 'http://www.vimeo.com/1234567';
$str = substr(strrchr($url, '/'), 1);
echo $str;      // Output: 1234567

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.

Java 8 stream map on entry set

Simply translating the "old for loop way" into streams:

private Map<String, String> mapConfig(Map<String, Integer> input, String prefix) {
    int subLength = prefix.length();
    return input.entrySet().stream()
            .collect(Collectors.toMap(
                   entry -> entry.getKey().substring(subLength), 
                   entry -> AttributeType.GetByName(entry.getValue())));
}

java.net.BindException: Address already in use: JVM_Bind <null>:80

I came across same issue. I was getting error Unable to open debugger port (127.0.0.1:63936): java.net.BindException "Address already in use: JVM_Bind" I tried above all option but any how its not resolved. Solution which worked for me is, I started the server and then stopped and again started in debug mode. then the server got started in debug mode.

How do I make the method return type generic?

There are a lot of great answers here, but this is the approach I took for an Appium test where acting on a single element can result in going to different application states based on the user's settings. While it doesn't follow the conventions of OP's example, I hope it helps someone.

public <T extends MobilePage> T tapSignInButton(Class<T> type) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {
    //signInButton.click();
    return type.getConstructor(AppiumDriver.class).newInstance(appiumDriver);
}
  • MobilePage is the super class that the type extends meaning you can use any of its children (duh)
  • type.getConstructor(Param.class, etc) allows you to interact with the constructor of the type. This constructor should be the same between all expected classes.
  • newInstance takes a declared variable that you want to pass to the new objects constructor

If you don't want to throw the errors you can catch them like so:

public <T extends MobilePage> T tapSignInButton(Class<T> type) {
    // signInButton.click();
    T returnValue = null;
    try {
       returnValue = type.getConstructor(AppiumDriver.class).newInstance(appiumDriver);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return returnValue;
}

Return anonymous type results?

BreedId in the Dog table is obviously a foreign key to the corresponding row in the Breed table. If you've got your database set up properly, LINQ to SQL should automatically create an association between the two tables. The resulting Dog class will have a Breed property, and the Breed class should have a Dogs collection. Setting it up this way, you can still return IEnumerable<Dog>, which is an object that includes the breed property. The only caveat is that you need to preload the breed object along with dog objects in the query so they can be accessed after the data context has been disposed, and (as another poster has suggested) execute a method on the collection that will cause the query to be performed immediately (ToArray in this case):

public IEnumerable<Dog> GetDogs()
{
    using (var db = new DogDataContext(ConnectString))
    {
        db.LoadOptions.LoadWith<Dog>(i => i.Breed);
        return db.Dogs.ToArray();
    }

}

It is then trivial to access the breed for each dog:

foreach (var dog in GetDogs())
{
    Console.WriteLine("Dog's Name: {0}", dog.Name);
    Console.WriteLine("Dog's Breed: {0}", dog.Breed.Name);        
}

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

I've been struggling with this for 3 days now while attempting to connect to a local API running Laravel valet. I finally figured it out. In my case I had to drag and drop over the LaravelValetCASelfSigned.pem file from ~/.config/valet/CA/LaravelValetCASelfSigned.pem

After verifying the installing within the simulator I had to go to Settings > About > Certificate Trust Settings > and Enable the Laravel Valet VA Self Signed CN

Finally working!!!

LINQ to SQL Left Outer Join

You don't need the into statements:

var query = 
    from customer in dc.Customers
    from order in dc.Orders
         .Where(o => customer.CustomerId == o.CustomerId)
         .DefaultIfEmpty()
    select new { Customer = customer, Order = order } 
    //Order will be null if the left join is null

And yes, the query above does indeed create a LEFT OUTER join.

Link to a similar question that handles multiple left joins: Linq to Sql: Multiple left outer joins

Is it possible to specify a different ssh port when using rsync?

use the "rsh option" . e.g.:

rsync -avz --rsh='ssh -p3382' root@remote_server_name:/opt/backups

refer to: http://www.linuxquestions.org/questions/linux-software-2/rsync-ssh-on-different-port-448112/

Can we overload the main method in Java?

You can overload the main() method, but only public static void main(String[] args) will be used when your class is launched by the JVM. For example:

public class Test {
    public static void main(String[] args) {
        System.out.println("main(String[] args)");
    }

    public static void main(String arg1) {
        System.out.println("main(String arg1)");
    }

    public static void main(String arg1, String arg2) {
        System.out.println("main(String arg1, String arg2)");
    }
}

That will always print main(String[] args) when you run java Test ... from the command line, even if you specify one or two command-line arguments.

You can call the main() method yourself from code, of course - at which point the normal overloading rules will be applied.

EDIT: Note that you can use a varargs signature, as that's equivalent from a JVM standpoint:

public static void main(String... args)

JavaScript - Get minutes between two dates

A simple function to perform this calculation:

function getMinutesBetweenDates(startDate, endDate) {
    var diff = endDate.getTime() - startDate.getTime();
    return (diff / 60000);
}

What's the difference between :: (double colon) and -> (arrow) in PHP?

Actually by this symbol we can call a class method that is static and not be dependent on other initialization...

class Test {

    public $name;

    public function __construct() {
        $this->name = 'Mrinmoy Ghoshal';
    }

    public static function doWrite($name) {
        print 'Hello '.$name;
    }

    public function write() {
        print $this->name;
    }
}

Here the doWrite() function is not dependent on any other method or variable, and it is a static method. That's why we can call this method by this operator without initializing the object of this class.

Test::doWrite('Mrinmoy'); // Output: Hello Mrinmoy.

But if you want to call the write method in this way, it will generate an error because it is dependent on initialization.

SSRS 2008 R2 - SSRS 2012 - ReportViewer: Reports are blank in Safari and Chrome

The solution provided by Emanuele worked for me. I could see the report when I accessed it directly from the server but when I used a ReportViewer control on my aspx page, I was unable to see the report. Upon inspecting the rendered HTML, I found a div by the id "ReportViewerGeneral_ctl09" (ReportViewerGeneral is the server id of the report viewer control) which had it's overflow property set to auto.

<div id="ReportViewerGeneral_ctl09" style="height: 100%; width: 100%; overflow: auto; position: relative; ">...</div>

I used the procedure explained by Emanuele to change this to visible as follows:

function pageLoad() {
    var element = document.getElementById("ReportViewerGeneral_ctl09");

    if (element) {
        element.style.overflow = "visible";
    }
}

Notice: Array to string conversion in

Even simpler:

$get = @mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");

note the quotes around username in the $_SESSION reference.

How can I control Chromedriver open window size?

Use this for your custom size:

driver.manage().window().setSize(new Dimension(1024,768));

you can change your dimensions as per your requirements.

SQL Server IIF vs CASE

IIF is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.

CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.

Finish all previous activities

Before launching your new Activity, simply add the following code:

finishAffinity();

Or if you want it to work in previous versions of Android:

ActivityCompat.finishAffinity(this);

How to extract request http headers from a request using NodeJS connect

If you use Express 4.x, you can use the req.get(headerName) method as described in Express 4.x API Reference

How can I style even and odd elements?

The problem with your CSS lies with the syntax of your pseudo-classes.

The even and odd pseudo-classes should be:

li:nth-child(even) {
    color:green;
}

and

li:nth-child(odd) {
    color:red;
}

Demo: http://jsfiddle.net/q76qS/5/

replace NULL with Blank value or Zero in sql server

Try This

SELECT Title  from #Movies
    SELECT CASE WHEN Title = '' THEN 'No Title' ELSE Title END AS Titile from #Movies

OR

SELECT [Id], [CategoryId], ISNULL(nullif(Title,''),'No data') as Title, [Director], [DateReleased] FROM #Movies

What good are SQL Server schemas?

Here a good implementation example of using schemas with SQL Server. We had several ms-access applications. We wanted to convert those to a ASP.NET App portal. Every ms-access application is written as an App for that portal. Every ms-access application has its own database tables. Some of those are related, we put those in the common dbo schema of SQL Server. The rest gets its own schemas. That way if we want to know what tables belong to an App on the ASP.NET app portal that can easily be navigated, visualised and maintained.

How to redirect output of an entire shell script within the script itself?

For saving the original stdout and stderr you can use:

exec [fd number]<&1 
exec [fd number]<&2

For example, the following code will print "walla1" and "walla2" to the log file (a.txt), "walla3" to stdout, "walla4" to stderr.

#!/bin/bash

exec 5<&1
exec 6<&2

exec 1> ~/a.txt 2>&1

echo "walla1"
echo "walla2" >&2
echo "walla3" >&5
echo "walla4" >&6

You should not use <Link> outside a <Router>

If you don't want to change much, use below code inside onClick()method.

this.props.history.push('/');

HTML5 : Iframe No scrolling?

In HTML5 there is no scrolling attribute because "its function is better handled by CSS" see http://www.w3.org/TR/html5-diff/ for other changes. Well and the CSS solution:

CSS solution:

HTML4's scrolling="no" is kind of an alias of the CSS's overflow: hidden, to do so it is important to set size attributes width/height:

iframe.noScrolling{
  width: 250px; /*or any other size*/
  height: 300px; /*or any other size*/
  overflow: hidden;
}

Add this class to your iframe and you're done:

<iframe src="http://www.example.com/" class="noScrolling"></iframe>

! IMPORTANT NOTE ! : overflow: hidden for <iframe> is not fully supported by all modern browsers yet(even chrome doesn't support it yet) so for now (2013) it's still better to use Transitional version and use scrolling="no" and overflow:hidden at the same time :)

UPDATE 2020: the above is still true, oveflow for iframes is still not supported by all majors

"Parameter not valid" exception loading System.Drawing.Image

I had the same problem and apparently is solved now, despite this and some other gdi+ exceptions are very misleading, I found that actually the problem was that the parameter being sent to a Bitmap constructor was not valid. I have this code:

using (System.IO.FileStream fs = new System.IO.FileStream(inputImage, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
{
    try
    {
        using (Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false))
        {
            try
            {
                bitmap.Save(OutputImage + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                GC.Collect();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    catch (ArgumentException aex)
    {
        throw new Exception("The file received from the Map Server is not a valid jpeg image", aex);
    }
}

The following line was causing an error:

Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false)

The file stream was built from the file downloaded from the Map Server. My app was sending the request incorrectly to get the image, and the server was returning something with the jpg extension, but was actually a html telling me that an error ocurred. So I was taking that image and trying to build a Bitmap with it. The fix was to control/ validate the image for a valid jpeg image.

Hope it helps!

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

Just make regular link look like button :)

<a href="#" role="button" class="btn btn-success btn-large">Click here!</a>

"role" inside a href code makes it look like button, ofc you can add more variables such as class.

Generating Random Passwords

Here Is what i put together quickly.

    public string GeneratePassword(int len)
    {
        string res = "";
        Random rnd = new Random();
        while (res.Length < len) res += (new Func<Random, string>((r) => {
            char c = (char)((r.Next(123) * DateTime.Now.Millisecond % 123)); 
            return (Char.IsLetterOrDigit(c)) ? c.ToString() : ""; 
        }))(rnd);
        return res;
    }

Can I assume (bool)true == (int)1 for any C++ compiler?

Charles Bailey's answer is correct. The exact wording from the C++ standard is (§4.7/4): "If the source type is bool, the value false is converted to zero and the value true is converted to one."

Edit: I see he's added the reference as well -- I'll delete this shortly, if I don't get distracted and forget...

Edit2: Then again, it is probably worth noting that while the Boolean values themselves always convert to zero or one, a number of functions (especially from the C standard library) return values that are "basically Boolean", but represented as ints that are normally only required to be zero to indicate false or non-zero to indicate true. For example, the is* functions in <ctype.h> only require zero or non-zero, not necessarily zero or one.

If you cast that to bool, zero will convert to false, and non-zero to true (as you'd expect).

Mockito: Inject real objects into private @Autowired fields

Mockito is not a DI framework and even DI frameworks encourage constructor injections over field injections.
So you just declare a constructor to set dependencies of the class under test :

@Mock
private SomeService serviceMock;

private Demo demo;

/* ... */
@BeforeEach
public void beforeEach(){
   demo = new Demo(serviceMock);
}

Using Mockito spy for the general case is a terrible advise. It makes the test class brittle, not straight and error prone : What is really mocked ? What is really tested ?
@InjectMocks and @Spy also hurts the overall design since it encourages bloated classes and mixed responsibilities in the classes.
Please read the spy() javadoc before using that blindly (emphasis is not mine) :

Creates a spy of the real object. The spy calls real methods unless they are stubbed. Real spies should be used carefully and occasionally, for example when dealing with legacy code.

As usual you are going to read the partial mock warning: Object oriented programming tackles complexity by dividing the complexity into separate, specific, SRPy objects. How does partial mock fit into this paradigm? Well, it just doesn't... Partial mock usually means that the complexity has been moved to a different method on the same object. In most cases, this is not the way you want to design your application.

However, there are rare cases when partial mocks come handy: dealing with code you cannot change easily (3rd party interfaces, interim refactoring of legacy code etc.) However, I wouldn't use partial mocks for new, test-driven & well-designed code.

Mailx send html message

I had successfully used the following on Arch Linux (where the -a flag is used for attachments) for several years:

mailx -s "The Subject $( echo -e "\nContent-Type: text/html" [email protected] < email.html

This appended the Content-Type header to the subject header, which worked great until a recent update. Now the new line is filtered out of the -s subject. Presumably, this was done to improve security.

Instead of relying on hacking the subject line, I now use a bash subshell:

(
    echo -e "Content-Type: text/html\n"
    cat mail.html
 ) | mail -s "The Subject" -t [email protected]

And since we are really only using mailx's subject flag, it seems there is no reason not to switch to sendmail as suggested by @dogbane:

(
    echo "To: [email protected]"
    echo "Subject: The Subject"
    echo "Content-Type: text/html"
    echo
    cat mail.html
) | sendmail -t

The use of bash subshells avoids having to create a temporary file.

C++ string to double conversion

You can convert char to int and viceversa easily because for the machine an int and a char are the same, 8 bits, the only difference comes when they have to be shown in screen, if the number is 65 and is saved as a char, then it will show 'A', if it's saved as a int it will show 65.

With other types things change, because they are stored differently in memory. There's standard function in C that allows you to convert from string to double easily, it's atof. (You need to include stdlib.h)

#include <stdlib.h>

int main()
{
    string word;  
    openfile >> word;
    double lol = atof(word.c_str()); /*c_str is needed to convert string to const char*
                                     previously (the function requires it)*/
    return 0;
}

How to set initial value and auto increment in MySQL?

MySQL Workbench

If you want to avoid writing sql, you can also do it in MySQL Workbench by right clicking on the table, choose "Alter Table ..." in the menu.

When the table structure view opens, go to tab "Options" (on the lower bottom of the view), and set "Auto Increment" field to the value of the next autoincrement number.

Don't forget to hit "Apply" when you are done with all changes.

PhpMyAdmin:

If you are using phpMyAdmin, you can click on the table in the lefthand navigation, go to the tab "Operations" and under Table Options change the AUTO_INCREMENT value and click OK.

Validate email address textbox using JavaScript

This is quite an old question so I've updated this answer to take the HTML 5 email type into account.

You don't actually need JavaScript for this at all with HTML 5; just use the email input type:

<input type="email" />
  • If you want to make it mandatory, you can add the required parameter.

  • If you want to add additional RegEx validation (limit to @foo.com email addresses for example), you can use the pattern parameter, e.g.:

    <input type="email" pattern="[email protected]" />
    

There's more information available on MozDev.


Original answer follows


First off - I'd recommend the email validator RegEx from Hexillion: http://hexillion.com/samples/

It's pretty comprehensive - :

^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$

I think you want a function in your JavaScript like:

function validateEmail(sEmail) {
  var reEmail = /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/;

  if(!sEmail.match(reEmail)) {
    alert("Invalid email address");
    return false;
  }

  return true;

}

In the HTML input you need to trigger the event with an onblur - the easy way to do this is to simply add something like:

<input type="text" name="email" onblur="validateEmail(this.value);" />

Of course that's lacking some sanity checks and won't do domain verification (that has to be done server side) - but it should give you a pretty solid JS email format verifier.

Note: I tend to use the match() string method rather than the test() RegExp method but it shouldn't make any difference.

Java double comparison epsilon

Floating point numbers only have so many significant digits, but they can go much higher. If your app will ever handle large numbers, you will notice the epsilon value should be different.

0.001+0.001 = 0.002 BUT 12,345,678,900,000,000,000,000+1=12,345,678,900,000,000,000,000 if you are using floating point and double. It's not a good representation of money, unless you are damn sure you'll never handle more than a million dollars in this system.

Edit and replay XHR chrome/firefox etc?

For Firefox the problem solved itself. It has the "Edit and Resend" feature implemented.

For Chrome Tamper extension seems to do the trick.

Clear listview content?

Simple its works me:)

YourArrayList_Object.clear();

Replacing H1 text with a logo image: best method for SEO and accessibility?

You missed title in <a> element.

<h1 id="logo">
  <a href="#" title="..."><span>Stack Overflow</span></a>
</h1>

I suggest to put title in <a> element because client would want to know what is the meaning of that image. Because you have set text-indent for the test of <h1> so, that front end user could get information of main logo while they hover on logo.

Find number of decimal places in decimal value regardless of culture

I'd probably use the solution in @fixagon's answer.

However, while the Decimal struct doesn't have a method to get the number of decimals, you could call Decimal.GetBits to extract the binary representation, then use the integer value and scale to compute the number of decimals.

This would probably be faster than formatting as a string, though you'd have to be processing an awful lot of decimals to notice the difference.

I'll leave the implementation as an exercise.

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

You could use serialize

<input type="hidden" name="quotation[]" value="{{serialize($quotation)}}">

But best way in this case use the json_encode method in your blade and json_decode in controller.

"Fade" borders in CSS

How to fade borders with CSS:

<div style="border-style:solid;border-image:linear-gradient(red, transparent) 1;border-bottom:0;">Text</div>

Please excuse the inline styles for the sake of demonstration. The 1 property for the border-image is border-image-slice, and in this case defines the border as a single continuous region.

Source: Gradient Borders

How to add a new object (key-value pair) to an array in javascript?

New solution with ES6

Default object

object = [{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}];

Another object

object =  {'id': 5};

Object assign ES6

resultObject = {...obj, ...newobj};

Result

[{'id': 1}, {'id': 2}, {'id': 3}, {'id': 4}, {'id': 5}];

How to include file in a bash shell script

In my situation, in order to include color.sh from the same directory in init.sh, I had to do something as follows.

. ./color.sh

Not sure why the ./ and not color.sh directly. The content of color.sh is as follows.

RED=`tput setaf 1`
GREEN=`tput setaf 2`
BLUE=`tput setaf 4`
BOLD=`tput bold`
RESET=`tput sgr0`

Making use of File color.sh does not error but, the color do not display. I have tested this in Ubuntu 18.04 and the Bash version is:

GNU bash, version 4.4.19(1)-release (x86_64-pc-linux-gnu)

How do I disable a href link in JavaScript?

Try this when you dont want user to redirect on click

<a href="javascript: void(0)">I am a useless link</a>

Converting serial port data to TCP/IP in a Linux environment

You might find Perl or Python useful to get data from the serial port. To send data to the server, the solution could be easy if the server is (let's say) an HTTP application or even a popular database. The solution would be not so easy if it is some custom/proprietary TCP application.

How to enable file sharing for my app?

In Xcode 8.3.3 add new row in .plist with true value

Application supports iTunes file sharing

HTML5 input type range show range value

For people don't care about jquery use, here is a short way without using any id

<label> userAvatar :
  <input type="range" name="userAvatar" min="1" max="100" value="1"
         onchange="$('~ output', this).val(value)" 
         oninput="$('~ output', this).val(value)">
  <output>1</output>
</label>

How can I specify system properties in Tomcat configuration on startup?

An alternative to setting the system property on tomcat configuration is to use CATALINA_OPTS environment variable

GDB: break if variable equal value

First, you need to compile your code with appropriate flags, enabling debug into code.

$ gcc -Wall -g -ggdb -o ex1 ex1.c

then just run you code with your favourite debugger

$ gdb ./ex1

show me the code.

(gdb) list
1   #include <stdio.h>
2   int main(void)
3   { 
4     int i = 0;
5     for(i=0;i<7;++i)
6       printf("%d\n", i);
7   
8     return 0;
9   }

break on lines 5 and looks if i == 5.

(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i

checking breakpoints

(gdb) info b
Num     Type           Disp Enb Address            What
1       breakpoint     keep y   0x00000000004004fb in main at ex1.c:5
    breakpoint already hit 1 time
5       read watchpoint keep y                      i
    stop only if i==5

running the program

(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i

Value = 5
0x0000000000400523 in main () at ex1.c:5
5     for(i=0;i<7;++i)