Programs & Examples On #Value type

In computer science, the term value type is commonly used to refer to one of two kinds of data types: Types of values or Types of objects with deep copy semantics.

What's the difference between struct and class in .NET?

Besides the basic difference of access specifier, and few mentioned above I would like to add some of the major differences including few of the mentioned above with a code sample with output, which will give a more clear idea of the reference and value

Structs:

  • Are value types and do not require heap allocation.
  • Memory allocation is different and is stored in stack
  • Useful for small data structures
  • Affect performance, when we pass value to method, we pass the entire data structure and all is passed to the stack.
  • Constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary
  • The variables each have their own copy of the data, and it is not possible for operations on one to affect the other.
  • Do not support user-specified inheritance, and they implicitly inherit from type object

Class:

  • Reference Type value
  • Stored in Heap
  • Store a reference to a dynamically allocated object
  • Constructors are invoked with the new operator, but that does not allocate memory on the heap
  • Multiple variables may have a reference to the same object
  • It is possible for operations on one variable to affect the object referenced by the other variable

Code Sample

    static void Main(string[] args)
    {
        //Struct
        myStruct objStruct = new myStruct();
        objStruct.x = 10;
        Console.WriteLine("Initial value of Struct Object is: " + objStruct.x);
        Console.WriteLine();
        methodStruct(objStruct);
        Console.WriteLine();
        Console.WriteLine("After Method call value of Struct Object is: " + objStruct.x);
        Console.WriteLine();

        //Class
        myClass objClass = new myClass(10);
        Console.WriteLine("Initial value of Class Object is: " + objClass.x);
        Console.WriteLine();
        methodClass(objClass);
        Console.WriteLine();
        Console.WriteLine("After Method call value of Class Object is: " + objClass.x);
        Console.Read();
    }
    static void methodStruct(myStruct newStruct)
    {
        newStruct.x = 20;
        Console.WriteLine("Inside Struct Method");
        Console.WriteLine("Inside Method value of Struct Object is: " + newStruct.x);
    }
    static void methodClass(myClass newClass)
    {
        newClass.x = 20;
        Console.WriteLine("Inside Class Method");
        Console.WriteLine("Inside Method value of Class Object is: " + newClass.x);
    }
    public struct myStruct
    {
        public int x;
        public myStruct(int xCons)
        {
            this.x = xCons;
        }
    }
    public class myClass
    {
        public int x;
        public myClass(int xCons)
        {
            this.x = xCons;
        }
    }

Output

Initial value of Struct Object is: 10

Inside Struct Method Inside Method value of Struct Object is: 20

After Method call value of Struct Object is: 10

Initial value of Class Object is: 10

Inside Class Method Inside Method value of Class Object is: 20

After Method call value of Class Object is: 20

Here you can clearly see the difference between call by value and call by reference.

In C#, why is String a reference type that behaves like a value type?

Actually strings have very few resemblances to value types. For starters, not all value types are immutable, you can change the value of an Int32 all you want and it it would still be the same address on the stack.

Strings are immutable for a very good reason, it has nothing to do with it being a reference type, but has a lot to do with memory management. It's just more efficient to create a new object when string size changes than to shift things around on the managed heap. I think you're mixing together value/reference types and immutable objects concepts.

As far as "==": Like you said "==" is an operator overload, and again it was implemented for a very good reason to make framework more useful when working with strings.

trim left characters in sql server?

To remove the left-most word, you'll need to use either RIGHT or SUBSTRING. Assuming you know how many characters are involved, that would look either of the following:

SELECT RIGHT('Hello World', 5)
SELECT SUBSTRING('Hello World', 6, 100)

If you don't know how many characters that first word has, you'll need to find out using CHARINDEX, then substitute that value back into SUBSTRING:

SELECT SUBSTRING('Hello World', CHARINDEX(' ', 'Hello World') + 1, 100)

This finds the position of the first space, then takes the remaining characters to the right.

Print array elements on separate lines in Bash?

Using for:

for each in "${alpha[@]}"
do
  echo "$each"
done

Using history; note this will fail if your values contain !:

history -p "${alpha[@]}"

Using basename; note this will fail if your values contain /:

basename -a "${alpha[@]}"

Using shuf; note that results might not come out in order:

shuf -e "${alpha[@]}"

How to modify a global variable within a function in bash?

I had a similar problem, when I wanted to automatically remove temp files I had created. The solution I came up with was not to use command substitution, but rather to pass the name of the variable, that should take the final result, into the function. E.g.

#! /bin/bash

remove_later=""
new_tmp_file() {
    file=$(mktemp)
    remove_later="$remove_later $file"
    eval $1=$file
}
remove_tmp_files() {
    rm $remove_later
}
trap remove_tmp_files EXIT

new_tmp_file tmpfile1
new_tmp_file tmpfile2

So, in your case that would be:

#!/bin/bash

e=2

function test1() {
  e=4
  eval $1="hello"
}

test1 ret

echo "$ret"
echo "$e"

Works and has no restrictions on the "return value".

Best JavaScript compressor

I recently released UglifyJS, a JavaScript compressor which is written in JavaScript (runs on the NodeJS Node.js platform, but it can be easily modified to run on any JavaScript engine, since it doesn't need any Node.js internals). It's a lot faster than both YUI Compressor and Google Closure, it compresses better than YUI on all scripts I tested it on, and it's safer than Closure (knows to deal with "eval" or "with").

Other than whitespace removal, UglifyJS also does the following:

  • changes local variable names (usually to single characters)
  • joins consecutive var declarations
  • avoids inserting any unneeded brackets, parens and semicolons
  • optimizes IFs (removes "else" when it detects that it's not needed, transforms IFs into the &&, || or ?/: operators when possible, etc.).
  • transforms foo["bar"] into foo.bar where possible
  • removes quotes from keys in object literals, where possible
  • resolves simple expressions when this leads to smaller code (1+3*4 ==> 13)

PS: Oh, it can "beautify" as well. ;-)

Getting Textbox value in Javascript

<script type="text/javascript" runat="server">
 public void Page_Load(object Sender, System.EventArgs e)
    {
        double rad=0.0;
        TextBox1.Attributes.Add("Visible", "False");
        if (TextBox1.Text != "") 
        rad = Convert.ToDouble(TextBox1.Text);    
        Button1.Attributes.Add("OnClick","alert("+ rad +")");
    }
</script>

<asp:Button ID="Button1" runat="server" Text="Diameter" 
            style="z-index: 1; left: 133px; top: 181px; position: absolute" />
<asp:TextBox ID="TextBox1" Visible="True" Text="" runat="server" 
            AutoPostBack="true" 
            style="z-index: 1; left: 134px; top: 133px; position: absolute" ></asp:TextBox>

use the help of this, hope it will be usefull

How to use select/option/NgFor on an array of objects in Angular2

I don't know what things were like in the alpha, but I'm using beta 12 right now and this works fine. If you have an array of objects, create a select like this:

<select [(ngModel)]="simpleValue"> // value is a string or number
    <option *ngFor="let obj of objArray" [value]="obj.value">{{obj.name}}</option>
</select>

If you want to match on the actual object, I'd do it like this:

<select [(ngModel)]="objValue"> // value is an object
    <option *ngFor="let obj of objArray" [ngValue]="obj">{{obj.name}}</option>
</select>

Import module from subfolder

There's no need to mess with your PYTHONPATH or sys.path here.

To properly use absolute imports in a package you should include the "root" packagename as well, e.g.:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

Or you can use relative imports:

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

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

std::string str(c_str, strnlen(c_str, max_length));

At Christian Rau's request:

strnlen is specified in POSIX.1-2008 and available in GNU's glibc and the Microsoft run-time library. It is not yet found in some other systems; you may fall back to Gnulib's substitute.

TypeError: $ is not a function when calling jQuery function

What worked for me. The first library to import is the query library and right then call the jQuery.noConflict() method.

<head>
 <script type="text/javascript" src="jquery.min.js"/>
 <script>
  var jq = jQuery.noConflict();
  jq(document).ready(function(){
  //.... your code here
    });
 </script>

Using Excel OleDb to get sheet names IN SHEET ORDER

As per MSDN, In a case of spreadsheets inside of Excel it might not work because Excel files are not real databases. So you will be not able to get the sheets name in order of their visualization in workbook.

Code to get sheets name as per their visual appearance using interop:

Add reference to Microsoft Excel 12.0 Object Library.

Following code will give the sheets name in the actual order stored in workbook, not the sorted name.

Sample Code:

using Microsoft.Office.Interop.Excel;

string filename = "C:\\romil.xlsx";

object missing = System.Reflection.Missing.Value;

Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();

Microsoft.Office.Interop.Excel.Workbook wb =excel.Workbooks.Open(filename,  missing,  missing,  missing,  missing,missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing,  missing);

ArrayList sheetname = new ArrayList();

foreach (Microsoft.Office.Interop.Excel.Worksheet  sheet in wb.Sheets)
{
    sheetname.Add(sheet.Name);
}

Pandas DataFrame concat vs append

One more thing you have to keep in mind that the APPEND() method in Pandas doesn't modify the original object. Instead it creates a new one with combined data. Because of involving creation and data buffer, its performance is not well. You'd better use CONCAT() function when doing multi-APPEND operations.

Carriage return in C?

Step-by-step:

[newline]ab

ab

[backspace]si

asi

[carriage-return]ha

hai

Carriage return, does not cause a newline. Under some circumstances a single CR or LF may be translated to a CR-LF pair. This is console and/or stream dependent.

Check if element found in array c++

C++ has NULL as well, often the same as 0 (pointer to address 0x00000000).

Do you use NULL or 0 (zero) for pointers in C++?

So in C++ that null check would be:

 if (!foo)
    cout << "not found";

Hibernate error - QuerySyntaxException: users is not mapped [from users]

org.hibernate.hql.internal.ast.QuerySyntaxException: users is not mapped [from users]

This indicates that hibernate does not know the User entity as "users".

@javax.persistence.Entity
@javax.persistence.Table(name = "Users")
public class User {

The @Table annotation sets the table name to be "Users" but the entity name is still referred to in HQL as "User".

To change both, you should set the name of the entity:

// this sets the name of the table and the name of the entity
@javax.persistence.Entity(name = "Users")
public class User implements Serializable{

See my answer here for more info: Hibernate table not mapped error

How do I update all my CPAN modules to their latest versions?

Try perl -MCPAN -e "upgrade /(.\*)/". It works fine for me.

How can I parse JSON with C#?

The following from the msdn site should I think help provide some native functionality for what you are looking for. Please note it is specified for Windows 8. One such example from the site is listed below.

JsonValue jsonValue = JsonValue.Parse("{\"Width\": 800, \"Height\": 600, \"Title\": \"View from 15th Floor\", \"IDs\": [116, 943, 234, 38793]}");
double width = jsonValue.GetObject().GetNamedNumber("Width");
double height = jsonValue.GetObject().GetNamedNumber("Height");
string title = jsonValue.GetObject().GetNamedString("Title");
JsonArray ids = jsonValue.GetObject().GetNamedArray("IDs");

It utilizes the Windows.Data.JSON namespace.

D3 transform scale and translate

The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

No Activity found to handle Intent : android.intent.action.VIEW

I have two ideas:

First: if you want to play 3gp file you should use mime types "audio/3gpp" or "audio/mpeg"

And second: you can try use method setData(data) for intent without any mime type.

Evaluate empty or null JSTL c tags

How can I validate if a String is null or empty using the c tags of JSTL?

You can use the empty keyword in a <c:if> for this:

<c:if test="${empty var1}">
    var1 is empty or null.
</c:if>
<c:if test="${not empty var1}">
    var1 is NOT empty or null.
</c:if>

Or the <c:choose>:

<c:choose>
    <c:when test="${empty var1}">
        var1 is empty or null.
    </c:when>
    <c:otherwise>
        var1 is NOT empty or null.
    </c:otherwise>
</c:choose>

Or if you don't need to conditionally render a bunch of tags and thus you could only check it inside a tag attribute, then you can use the EL conditional operator ${condition? valueIfTrue : valueIfFalse}:

<c:out value="${empty var1 ? 'var1 is empty or null' : 'var1 is NOT empty or null'}" />

To learn more about those ${} things (the Expression Language, which is a separate subject from JSTL), check here.

See also:

How do you subtract Dates in Java?

Here's the basic approach,

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");

Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);

Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);

There is simple way to implement it. We can use Calendar.add method with loop. The minus days between beginDate and endDate, and the implemented code as below,

int minusDays = 0;
while (true) {
  minusDays++;

  // Day increasing by 1
  beginCalendar.add(Calendar.DAY_OF_MONTH, 1);

  if (dateFormat.format(beginCalendar.getTime()).
            equals(dateFormat.format(endCalendar).getTime())) {
    break;
  }
}
System.out.println("The subtraction between two days is " + (minusDays + 1));**

Get and Set Screen Resolution

In C# this is how to get the resolution Screen:

button click or form load:

string screenWidth = Screen.PrimaryScreen.Bounds.Width.ToString();
string screenHeight = Screen.PrimaryScreen.Bounds.Height.ToString();
Label1.Text = ("Resolution: " + screenWidth + "x" + screenHeight);

How do I enumerate through a JObject?

JObjects can be enumerated via JProperty objects by casting it to a JToken:

foreach (JProperty x in (JToken)obj) { // if 'obj' is a JObject
    string name = x.Name;
    JToken value = x.Value;
}

If you have a nested JObject inside of another JObject, you don't need to cast because the accessor will return a JToken:

foreach (JProperty x in obj["otherObject"]) { // Where 'obj' and 'obj["otherObject"]' are both JObjects
    string name = x.Name;
    JToken value = x.Value;
}

Assign variable in if condition statement, good practice or not?

I see no proof that it is not good practice. Yes, it may look like a mistake but that is easily remedied by judicious commenting. Take for instance:

if (x = processorIntensiveFunction()) { // declaration inside if intended
    alert(x);
}

Why should that function be allowed to run a 2nd time with:

alert(processorIntensiveFunction());

Because the first version LOOKS bad? I cannot agree with that logic.

Transfer git repositories from GitLab to GitHub - can we, how to and pitfalls (if any)?

For anyone still looking for a simpler method to transfer repos from Gitlab to Github while preserving all history.

Step 1. Login to Github, create a private repo with the exact same name as the repo you would like to transfer.

Step 2. Under "push an existing repository from the command" copy the link of the new repo, it will look something like this:

[email protected]:your-name/name-of-repo.git

Step 3. Open up your local project and look for the folder .git typically this will be a hidden folder. Inside the .git folder open up config.

The config file will contain something like:

[remote "origin"]
url = [email protected]:your-name/name-of-repo.git
fetch = +refs/heads/:refs/remotes/origin/

Under [remote "origin"], change the URL to the one that you copied on Github.

Step 4. Open your project folder in the terminal and run: git push --all. This will push your code to Github as well as all the commit history.

Step 5. To make sure everything is working as expected, make changes, commit, push and new commits should appear on the newly created Github repo.

Step 6. As a last step, you can now archive your Gitlab repo or set it to read only.

Put a Delay in Javascript

This thread has a good discussion and a useful solution:

function pause( iMilliseconds )
{
    var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
    window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}

Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.

How can I extract a predetermined range of lines from a text file on Unix?

sed -n '16224,16482 p' orig-data-file > new-file

Where 16224,16482 are the start line number and end line number, inclusive. This is 1-indexed. -n suppresses echoing the input as output, which you clearly don't want; the numbers indicate the range of lines to make the following command operate on; the command p prints out the relevant lines.

Proper usage of .net MVC Html.CheckBoxFor

I was looking for the solution to show the label dynamically from database like this:

checkbox1 : Option 1 text from database
checkbox2 : Option 2 text from database
checkbox3 : Option 3 text from database
checkbox4 : Option 4 text from database

So none of the above solution worked for me so I used like this:

 @Html.CheckBoxFor(m => m.Option1, new { @class = "options" }) 
 <label for="Option1">@Model.Option1Text</label>

 @Html.CheckBoxFor(m => m.Option2, new { @class = "options" }) 
 <label for="Option2">@Mode2.Option1Text</label>

In this way when user will click on label, checkbox will be selected.

Might be it can help someone.

What do these three dots in React do?

The three dots (...) are called the spread operator, and this is conceptually similar to the ES6 array spread operator, JSX taking advantage of these supported and developing standards in order to provide a cleaner syntax in JSX

Spread properties in object initializers copies own enumerable properties from a provided object onto the newly created object.

let n = { x, y, ...z };
n; // { x: 1, y: 2, a: 3, b: 4 }

Reference:

1) https://github.com/sebmarkbage/ecmascript-rest-spread#spread-properties

2) https://facebook.github.io/react/docs/jsx-spread.html

What is the difference between String.slice and String.substring?

The difference between substring and slice - is how they work with negative and overlooking lines abroad arguments:

substring (start, end)

Negative arguments are interpreted as zero. Too large values ??are truncated to the length of the string:   alert ( "testme" .substring (-2)); // "testme", -2 becomes 0

Furthermore, if start > end, the arguments are interchanged, i.e. plot line returns between the start and end:

alert ( "testme" .substring (4, -1)); // "test"
// -1 Becomes 0 -> got substring (4, 0)
// 4> 0, so that the arguments are swapped -> substring (0, 4) = "test"

slice

Negative values ??are measured from the end of the line:

alert ( "testme" .slice (-2)); // "me", from the end position 2
alert ( "testme" .slice (1, -1)); // "estm", from the first position to the one at the end.

It is much more convenient than the strange logic substring.

A negative value of the first parameter to substr supported in all browsers except IE8-.

If the choice of one of these three methods, for use in most situations - it will be slice: negative arguments and it maintains and operates most obvious.

R ggplot2: stat_count() must not be used with a y aesthetic error in Bar graph

First off, your code is a bit off. aes() is an argument in ggplot(), you don't use ggplot(...) + aes(...) + layers

Second, from the help file ?geom_bar:

By default, geom_bar uses stat="count" which makes the height of the bar proportion to the number of cases in each group (or if the weight aethetic is supplied, the sum of the weights). If you want the heights of the bars to represent values in the data, use stat="identity" and map a variable to the y aesthetic.

You want the second case, where the height of the bar is equal to the conversion_rate So what you want is...

data_country <- data.frame(country = c("China", "Germany", "UK", "US"), 
            conversion_rate = c(0.001331558,0.062428188, 0.052612025, 0.037800687))
ggplot(data_country, aes(x=country,y = conversion_rate)) +geom_bar(stat = "identity")

Result:

enter image description here

How best to read a File into List<string>

//this is only good in .NET 4
//read your file:
List<string> ReadFile = File.ReadAllLines(@"C:\TEMP\FILE.TXT").ToList();

//manipulate data here
foreach(string line in ReadFile)
{
    //do something here
}

//write back to your file:
File.WriteAllLines(@"C:\TEMP\FILE2.TXT", ReadFile);

SQL-Server: The backup set holds a backup of a database other than the existing

I was just trying to solve this issue.

I'd tried everything from running as admin through to the suggestions found here and elsewhere; what solved it for me in the end was to check the "relocate files" option in the Files property tab.

Hopefully this helps somebody else.

comparing strings in vb

I think this String.Equals is what you need.

Dim aaa = "12/31"
            Dim a = String.Equals(aaa, "06/30")

a will return false.

Update cordova plugins in one command

ionic state is deprecated as on [email protected]

If you happen to be using ionic and the ionic cli you can run:

ionic state reset

As long as all your plugin information was saved in your package.json earlier, this will essentially perform an rm/add for all your plugins. Just note that this will also rm/add your platforms as well, but that shouldn't matter.

This is also nice for when you ignore your plugin folders from your repo, and want to setup the project on another machine.

Obviously this doesn't directly answer the question, but many people are currently using both, and will end up here.

Setting the value of checkbox to true or false with jQuery

Use $('#id-of-the-checkbox').prop('checked', true_or_false);

In case you are using an ancient jQuery version, you'll need to use .attr('checked', 'checked') to check and .removeAttr('checked') to uncheck.

Django: Get list of model fields?

This does the trick. I only test it in Django 1.7.

your_fields = YourModel._meta.local_fields
your_field_names = [f.name for f in your_fields]

Model._meta.local_fields does not contain many-to-many fields. You should get them using Model._meta.local_many_to_many.

Why is Visual Studio 2013 very slow?

Visual Studio Community Edition was slow switching between files or opening new files. Everything else (for example, menu items) was otherwise normal.

I tried all the suggestions in the previous answers first and none worked. I then noticed it was occurring only on an ASP.NET MVC 4 Web Application, so I added a new ASP.NET MVC 4 Web Application, and this was fast.

After much trial and error, I discovered the difference was packages.config - If I put the Microsoft references at the top of the file this made everything snappy again.

Enter image description here

Move the Microsoft* entries to the top.

Enter image description here

It appears you don’t need to move them all - moving say <package id="Microsoft.Web.Infrastructure" has an noticeable effect on my machine.

As an aside

  • Removing all contents of the file makes it another notch faster too*
  • Excluding packages.config from Visual Studio does not fix the issue
  • A friend using Visual Studio 2013 Premium noticed no difference in either of these cases (both were fast)

UPDATE

It appears missing or incomplete NuGet packages locally are the cause. I opened the Package manager and got a warning 'Some NuGet packages are missing from this solution' and choose to Restore them and this sped things up. However I don’t like this as in my repository I only add the actual items required for compilation as I don’t want to bloat my repository, so in the end I just removed the packages.config.

This solution may not suit your needs as I prefer to use NuGet to fetch the packages, not handle updates to packages, so this will break this if you use it for that purpose.

Pause in Python

Getting python to read a single character from the terminal in an unbuffered manner is a little bit tricky, but here's a recipe that'll do it:

Recipe 134892: getch()-like unbuffered character reading from stdin on both Windows and Unix (Python)

Can a foreign key be NULL and/or duplicate?

Can a Foreign key be NULL?

Existing answers focused on single column scenario. If we consider multi column foreign key we have more options using MATCH [SIMPLE | PARTIAL | FULL] clause defined in SQL Standard:

PostgreSQL-CREATE TABLE

A value inserted into the referencing column(s) is matched against the values of the referenced table and referenced columns using the given match type. There are three match types: MATCH FULL, MATCH PARTIAL, and MATCH SIMPLE (which is the default). MATCH FULL will not allow one column of a multicolumn foreign key to be null unless all foreign key columns are null; if they are all null, the row is not required to have a match in the referenced table. MATCH SIMPLE allows any of the foreign key columns to be null; if any of them are null, the row is not required to have a match in the referenced table. MATCH PARTIAL is not yet implemented.

(Of course, NOT NULL constraints can be applied to the referencing column(s) to prevent these cases from arising.)

Example:

CREATE TABLE A(a VARCHAR(10), b VARCHAR(10), d DATE , UNIQUE(a,b));
INSERT INTO A(a, b, d) 
VALUES (NULL, NULL, NOW()),('a', NULL, NOW()),(NULL, 'b', NOW()),('c', 'b', NOW());

CREATE TABLE B(id INT PRIMARY KEY, ref_a VARCHAR(10), ref_b VARCHAR(10));

-- MATCH SIMPLE - default behaviour nulls are allowed
ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) 
REFERENCES A(a,b) MATCH SIMPLE;

INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, 'b');  

-- (NULL/'x') 'x' value does not exists in A table, but insert is valid
INSERT INTO B(id, ref_a, ref_b) VALUES (2, NULL, 'x');  

ALTER TABLE B DROP CONSTRAINT IF EXISTS B_Fk; -- cleanup

-- MATCH PARTIAL - not implemented
ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) 
REFERENCES A(a,b) MATCH PARTIAL;
-- ERROR:  MATCH PARTIAL not yet implemented

DELETE FROM B; ALTER TABLE B DROP CONSTRAINT IF EXISTS B_Fk; -- cleanup

-- MATCH FULL nulls are not allowed
ALTER TABLE B ADD CONSTRAINT B_Fk FOREIGN KEY (ref_a, ref_b) 
REFERENCES A(a,b) MATCH FULL;

-- FK is defined, inserting NULL as part of FK
INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, 'b');
-- ERROR:  MATCH FULL does not allow mixing of null and nonnull key values.

-- FK is defined, inserting all NULLs - valid
INSERT INTO B(id, ref_a, ref_b) VALUES (1, NULL, NULL);

db<>fiddle demo

"git rebase origin" vs."git rebase origin/master"

Here's a better option:

git remote set-head -a origin

From the documentation:

With -a, the remote is queried to determine its HEAD, then $GIT_DIR/remotes//HEAD is set to the same branch. e.g., if the remote HEAD is pointed at next, "git remote set-head origin -a" will set $GIT_DIR/refs/remotes/origin/HEAD to refs/remotes/origin/next. This will only work if refs/remotes/origin/next already exists; if not it must be fetched first.

This has actually been around quite a while (since v1.6.3); not sure how I missed it!

Exception from HRESULT: 0x800A03EC Error

I was receiving the same error some time back. The issue was that my XLS file contained more than 65531 records(500 thousand to be precise). I was attempting to read a range of cells.

Excel.Range rng = (Excel.Range) myExcelWorkbookObj.UsedRange.Rows[i];

The exception was thrown while trying to read the range of cells when my counter, i.e. 'i', exceeded this limit of 65531 records.

Iterate through string array in Java

You have to maintain the serial how many times you are accessing the array.Use like this

int lookUpTime=0;

    for(int i=lookUpTime;i<lookUpTime+2 && i<elements.length();i++)
     {
    // do something with elements[i]
    }

lookUpTime++;

What is the largest Safe UDP Packet Size on the Internet

It is true that a typical IPv4 header is 20 bytes, and the UDP header is 8 bytes. However it is possible to include IP options which can increase the size of the IP header to as much as 60 bytes. In addition, sometimes it is necessary for intermediate nodes to encapsulate datagrams inside of another protocol such as IPsec (used for VPNs and the like) in order to route the packet to its destination. So if you do not know the MTU on your particular network path, it is best to leave a reasonable margin for other header information that you may not have anticipated. A 512-byte UDP payload is generally considered to do that, although even that does not leave quite enough space for a maximum size IP header.

Debugging with command-line parameters in Visual Studio

Even if you do start the executable outside Visual Studio, you can still use the "Attach" command to connect Visual Studio to your already-running executable. This can be useful e.g. when your application is run as a plug-in within another application.

ASP.NET postback with JavaScript

Using __doPostBack directly is sooooo the 2000s. Anybody coding WebForms in 2018 uses GetPostBackEventReference

(More seriously though, adding this as an answer for completeness. Using the __doPostBack directly is bad practice (single underscore prefix typically indicates a private member and double indicates a more universal private member), though it probably won't change or become obsolete at this point. We have a fully supported mechanism in ClientScriptManager.GetPostBackEventReference.)

Assuming your btnRefresh is inside our UpdatePanel and causes a postback, you can use GetPostBackEventReference like this (inspiration):

function RefreshGrid() {
    <%= ClientScript.GetPostBackEventReference(btnRefresh, String.Empty) %>;
}

Testing pointers for validity (C/C++)

On Unix you should be able to utilize a kernel syscall that does pointer checking and returns EFAULT, such as:

#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdbool.h>

bool isPointerBad( void * p )
{
   int fh = open( p, 0, 0 );
   int e = errno;

   if ( -1 == fh && e == EFAULT )
   {
      printf( "bad pointer: %p\n", p );
      return true;
   }
   else if ( fh != -1 )
   {
      close( fh );
   }

   printf( "good pointer: %p\n", p );
   return false;
}

int main()
{
   int good = 4;
   isPointerBad( (void *)3 );
   isPointerBad( &good );
   isPointerBad( "/tmp/blah" );

   return 0;
}

returning:

bad pointer: 0x3
good pointer: 0x7fff375fd49c
good pointer: 0x400793

There's probably a better syscall to use than open() [perhaps access], since there's a chance that this could lead to actual file creation codepath, and a subsequent close requirement.

Appending to list in Python dictionary

Is there a more elegant way to write this code?

Use collections.defaultdict:

from collections import defaultdict

dates_dict = defaultdict(list)
for key, date in cur:
    dates_dict[key].append(date)

What does <> mean?

Yes in SQl <> is the same as != which is not equal.....excepts for NULLS of course, in that case you need to use IS NULL or IS NOT NULL

How do you configure HttpOnly cookies in tomcat / java webapps?

httpOnly is supported as of Tomcat 6.0.19 and Tomcat 5.5.28.

See the changelog entry for bug 44382.

The last comment for bug 44382 states, "this has been applied to 5.5.x and will be included in 5.5.28 onwards." However, it does not appear that 5.5.28 has been released.

The httpOnly functionality can be enabled for all webapps in conf/context.xml:

<Context useHttpOnly="true">
...
</Context>

My interpretation is that it also works for an individual context by setting it on the desired Context entry in conf/server.xml (in the same manner as above).

C# password TextBox in a ASP.net website

I think this is what you are looking for

 <asp:TextBox ID="txbPass" runat="server" TextMode="Password"></asp:TextBox>

How can I recognize touch events using jQuery in Safari for iPad? Is it possible?

If you're using jQuery 1.7+ it's even simpler than all these other answers.

$('#whatever').on({ 'touchstart' : function(){ /* do something... */ } });

ReportViewer Client Print Control "Unable to load client print control"?

In my case when I get this message IE suggest me to install add-on from Microsoft. After install problem solved.

My software:
IE9 but work also on older
SQL SERVER 2008 R2

How to trigger event when a variable's value is changed?

Seems to me like you want to create a property.

public int MyProperty
{
    get { return _myProperty; }
    set
    {
        _myProperty = value;
        if (_myProperty == 1)
        {
            // DO SOMETHING HERE
        }
    }
}

private int _myProperty;

This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.

Converting String to Int with Swift

Because a string might contain non-numerical characters you should use a guard to protect the operation. Example:

guard let labelInt:Int = Int(labelString) else {
    return
}

useLabelInt()

Pushing to Git returning Error Code 403 fatal: HTTP request failed

I had this problem because I had proxy I couldn't access to my repository

C:\Users\YourUser\.gitconfig

remove bullshit proxy and it should work

enter image description here

then try again to clone by gitbash

 git clone http://********************

enter image description here

Windows command for file size only

If you don't want to do this in a batch script, you can do this from the command line like this:

for %I in (test.jpg) do @echo %~zI

Ugly, but it works. You can also pass in a file mask to get a listing for more than one file:

for %I in (*.doc) do @echo %~znI

Will display the size, file name of each .DOC file.

When to use Spring Security`s antMatcher()?

Basically http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

GROUP BY and COUNT in PostgreSQL

WITH uniq AS (
        SELECT DISTINCT posts.id as post_id
        FROM posts
        JOIN votes ON votes.post_id = posts.id
        -- GROUP BY not needed anymore
        -- GROUP BY posts.id
        )
SELECT COUNT(*)
FROM uniq;

How do I add a Fragment to an Activity with a programmatically created content view

After read all Answers I came up with elegant way:

public class MyActivity extends ActionBarActivity {

 Fragment fragment ;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    FragmentManager fm = getSupportFragmentManager();
    fragment = fm.findFragmentByTag("myFragmentTag");
    if (fragment == null) {
        FragmentTransaction ft = fm.beginTransaction();
        fragment =new MyFragment();
        ft.add(android.R.id.content,fragment,"myFragmentTag");
        ft.commit();
    }

}

basically you don't need to add a frameLayout as container of your fragment instead you can add straight the fragment into the android root View container

IMPORTANT: don't use replace fragment as most of the approach shown here, unless you don't mind to lose fragment variable instance state during onrecreation process.

Array initialization in Perl

What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);

my @array = (); should work just fine -- it allocates a new array called @array, and then assigns it the empty list, (). Note that this is identical to simply saying my @array;, since the initial value of a new array is the empty list anyway.

Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings; in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)

Remove the last line from a file in Bash

Here's how you can do it manually (I personally use this method a lot when I need to quickly remove the last line in a file):

vim + [FILE]

That + sign there means that when the file is opened in the vim text editor, the cursor will be positioned on the last line of the file.

Now just press d twice on your keyboard. This will do exactly what you want—remove the last line. After that, press : followed by x and then press Enter. This will save the changes and bring you back to the shell. Now, the last line has been successfully removed.

FromBody string parameter is giving null

Finally got it working after 1 hour struggle.

This will remove null issue, also gets the JSON key1's value of value1, in a generic way (no model binding), .

For a new WebApi 2 application example:

Postman (looks exactly, like below):

POST    http://localhost:61402/api/values   [Send]
Body
     (*) raw             JSON (application/json) v
         "{  \"key1\": \"value1\" }"

The port 61402 or url /api/values above, may be different for you.

ValuesController.cs

using Newtonsoft.Json;
// ..

// POST api/values
[HttpPost]
public object Post([FromBody]string jsonString)
{
    // add reference to Newtonsoft.Json
    //  using Newtonsoft.Json;

    // jsonString to myJsonObj
    var myJsonObj = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(jsonString);

    // value1 is myJsonObj[key1]
    var valueOfkey1 = myJsonObj["key1"];

    return myJsonObj;
}

All good for now, not sure if model binding to a class is required if I have sub keys, or, may be DeserializeObject on sub key will work.

Adding a color background and border radius to a Layout

background.xml in drawable folder.

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#FFFFFF"/>    
    <stroke
        android:width="3dp"
        android:color="#0FECFF" />

    //specify gradient
    <gradient
        android:startColor="#ffffffff" 
        android:endColor="#110000FF" 
        android:angle="90"/> 

    <padding
        android:left="5dp"
        android:top="5dp"
        android:right="5dp"
        android:bottom="5dp"/> 
    <corners
        android:bottomRightRadius="7dp"
        android:bottomLeftRadius="7dp" 
        android:topLeftRadius="7dp"
        android:topRightRadius="7dp"/> 
</shape>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="210dp"
    android:orientation="vertical"
    android:layout_marginBottom="10dp"        
    android:background="@drawable/background">

Android WebView style background-color:transparent ignored on android 2.2

below code works fine Android 3.0+ but when you try this code below android 3.0 then your app forcefully closed.

webView.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);

You try below code on your less then API 11.

webview.setBackgroundColor(Color.parseColor("#919191"));

Or

you can also try below code which works on all API fine.

    webview.setBackgroundColor(Color.parseColor("#919191"));
    if (Build.VERSION.SDK_INT >= 11) {
        webview.setLayerType(WebView.LAYER_TYPE_SOFTWARE, null);
    }

above code use full for me.

Can an interface extend multiple interfaces in Java?

I think your confusion lies with multiple inheritance, in which it is bad practise to do so and in Java this is also not possible. However, implementing multiple interfaces is allowed in Java and it is also safe.

Exact difference between CharSequence and String in java

General differences

There are several classes which implement the CharSequence interface besides String. Among these are

  • StringBuilder for variable-length character sequences which can be modified
  • CharBuffer for fixed-length low-level character sequences which can be modified

Any method which accepts a CharSequence can operate on all of these equally well. Any method which only accepts a String will require conversion. So using CharSequence as an argument type in all the places where you don't care about the internals is prudent. However you should use String as a return type if you actually return a String, because that avoids possible conversions of returned values if the calling method actually does require a String.

Also note that maps should use String as key type, not CharSequence, as map keys must not change. In other words, sometimes the immutable nature of String is essential.

Specific code snippet

As for the code you pasted: simply compile that, and have a look at the JVM bytecode using javap -v. There you will notice that both obj and str are references to the same constant object. As a String is immutable, this kind of sharing is all right.

The + operator of String is compiled as invocations of various StringBuilder.append calls. So it is equivalent to

System.out.println(
  (new StringBuilder())
  .append("output is : ")
  .append((Object)obj)
  .append(" ")
  .append(str)
  .toString()
)

I must confess I'm a bit surprised that my compiler javac 1.6.0_33 compiles the + obj using StringBuilder.append(Object) instead of StringBuilder.append(CharSequence). The former probably involves a call to the toString() method of the object, whereas the latter should be possible in a more efficient way. On the other hand, String.toString() simply returns the String itself, so there is little penalty there. So StringBuilder.append(String) might be more efficient by about one method invocation.

OSError [Errno 22] invalid argument when use open() in Python

for folder, subs, files in os.walk(unicode(docs_dir, 'utf-8')):
    for filename in files:
        if not filename.startswith('.'):
            file_path = os.path.join(folder, filename)

Android and setting alpha for (image) view alpha

use android:alpha=0.5 to achieve the opacity of 50% and to turn Android Material icons from Black to Grey.

how to remove new lines and returns from php string?

To remove new lines from string, follow the below code

$newstring = preg_replace("/[\n\r]/","",$subject); 

How can I iterate over the elements in Hashmap?

Need Key & Value in Iteration

Use entrySet() to iterate through Map and need to access value and key:

Map<String, Person> hm = new HashMap<String, Person>();

hm.put("A", new Person("p1"));
hm.put("B", new Person("p2"));
hm.put("C", new Person("p3"));
hm.put("D", new Person("p4"));
hm.put("E", new Person("p5"));

Set<Map.Entry<String, Person>> set = hm.entrySet();

for (Map.Entry<String, Person> me : set) {
  System.out.println("Key :"+me.getKey() +" Name : "+ me.getValue().getName()+"Age :"+me.getValue().getAge());

}

Need Key in Iteration

If you want just to iterate over keys of map you can use keySet()

for(String key: map.keySet()) {
     Person value = map.get(key); 
}

Need Value in Iteration

If you just want to iterate over values of map you can use values()

for(Person person: map.values()) {

}

append multiple values for one key in a dictionary

If I can rephrase your question, what you want is a dictionary with the years as keys and an array for each year containing a list of values associated with that year, right? Here's how I'd do it:

years_dict = dict()

for line in list:
    if line[0] in years_dict:
        # append the new number to the existing array at this slot
        years_dict[line[0]].append(line[1])
    else:
        # create a new array in this slot
        years_dict[line[0]] = [line[1]]

What you should end up with in years_dict is a dictionary that looks like the following:

{
    "2010": [2],
    "2009": [4,7],
    "1989": [8]
}

In general, it's poor programming practice to create "parallel arrays", where items are implicitly associated with each other by having the same index rather than being proper children of a container that encompasses them both.

Access to ES6 array element index inside for-of loop

Use Array.prototype.keys:

_x000D_
_x000D_
for (const index of [1, 2, 3, 4, 5].keys()) {_x000D_
  console.log(index);_x000D_
}
_x000D_
_x000D_
_x000D_

If you want to access both the key and the value, you can use Array.prototype.entries() with destructuring:

_x000D_
_x000D_
for (const [index, value] of [1, 2, 3, 4, 5].entries()) {_x000D_
  console.log(index, value);_x000D_
}
_x000D_
_x000D_
_x000D_

Single TextView with multiple colored text

I don't know, since when this is possible, but you can simply add <font> </font> to your string.xml which will automatically change the color per text. No need to add any additional code such as spannable text etc.

Example

<string name="my_formatted_text">
    <font color="#FF0707">THIS IS RED</font>
    <font color="#0B132B">AND NOW BLUE</font>
</string>

What's "tools:context" in Android layout files?

<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    //more views

</androidx.constraintlayout.widget.ConstraintLayout>

In the above code, the basic need of tools:context is to tell which activity or fragment the layout file is associated with by default. So, you can specify the activity class name using the same dot prefix as used in Manifest file.

By doing so, the Android Studio will choose the necessary theme for the preview automatically and you don’t have to do the preview settings manually. As we all know that a layout file can be associated with several activities but the themes are defined in the Manifest file and these themes are associated with your activity. So, by adding tools:context in your layout file, the Android Studio preview will automatically choose the necessary theme for you.

How to change the spinner background in Android?

Android Studio has a pre-defined code, you can directly use it. android:popupBackground="HEX COLOR CODE"

Install apps silently, with granted INSTALL_PACKAGES permission

Try this LD_LIBRARY_PATH=/vendor/lib:/system/lib before pm install. It works well.

How to sort with a lambda?

Can the problem be with the "a.mProperty > b.mProperty" line? I've gotten the following code to work:

#include <algorithm>
#include <vector>
#include <iterator>
#include <iostream>
#include <sstream>

struct Foo
{
    Foo() : _i(0) {};

    int _i;

    friend std::ostream& operator<<(std::ostream& os, const Foo& f)
    {
        os << f._i;
        return os;
    };
};

typedef std::vector<Foo> VectorT;

std::string toString(const VectorT& v)
{
    std::stringstream ss;
    std::copy(v.begin(), v.end(), std::ostream_iterator<Foo>(ss, ", "));
    return ss.str();
};

int main()
{

    VectorT v(10);
    std::for_each(v.begin(), v.end(),
            [](Foo& f)
            {
                f._i = rand() % 100;
            });

    std::cout << "before sort: " << toString(v) << "\n";

    sort(v.begin(), v.end(),
            [](const Foo& a, const Foo& b)
            {
                return a._i > b._i;
            });

    std::cout << "after sort:  " << toString(v) << "\n";
    return 1;
};

The output is:

before sort: 83, 86, 77, 15, 93, 35, 86, 92, 49, 21,
after sort:  93, 92, 86, 86, 83, 77, 49, 35, 21, 15,

How can I grep for a string that begins with a dash/hyphen?

I dont have access to a Solaris machine, but grep "\-X" works for me on linux.

What is an opaque response, and what purpose does it serve?

Opaque responses can't be accessed by JavaScript, but you can still cache them with the Cache API and respond with them in the fetch event handler in a service worker. So they're useful for making your app offline, also for resources that you can't control (e.g. resources on a CDN that doesn't set the CORS headers).

How do I programmatically get the GUID of an application in .NET 2.0

To get the appID you could use the following line of code:

var applicationId = ((GuidAttribute)typeof(Program).Assembly.GetCustomAttributes(typeof(GuidAttribute), true)[0]).Value;

For this you need to include the System.Runtime.InteropServices;

How to use placeholder as default value in select2 framework

In the current version of select2 you just need to add the attribute data-placeholder="A NICE PLACEHOLDER". select2 will automatically assign the placeholder. Please note: adding an empty <option></option> inside the select is still mandatory.

LINQ equivalent of foreach for IEnumerable<T>

You could use the FirstOrDefault() extension, which is available for IEnumerable<T>. By returning false from the predicate, it will be run for each element but will not care that it doesn't actually find a match. This will avoid the ToList() overhead.

IEnumerable<Item> items = GetItems();
items.FirstOrDefault(i => { i.DoStuff(); return false; });

Jquery, set value of td in a table?

use .html() along with selector to get/set HTML:

 $('#detailInfo').html('changed value');

Java division by zero doesnt throw an ArithmeticException - why?

Why can't you just check it yourself and throw an exception if that is what you want.

    try {
        for (int i = 0; i < tab.length; i++) {
            tab[i] = 1.0 / tab[i];

            if (tab[i] == Double.POSITIVE_INFINITY ||
                    tab[i] == Double.NEGATIVE_INFINITY)
                throw new ArithmeticException();
        }
    } catch (ArithmeticException ae) {
        System.out.println("ArithmeticException occured!");
    }

Ctrl+click doesn't work in Eclipse Juno

You need to rebuild your workspace using CTRL+B. I a problem where I'd be able to go to the function declarations but for some I wouldn't. After a rebuild, I could do all. I hope that helps.

How to install node.js as windows service?

The process manager + task scheduler approach I posted a year ago works well with some one-off service installations. But recently I started to design system in a micro-service fashion, with many small services talking to each other via IPC. So manually configuring each service has become unbearable.

Towards the goal of installing services without manual configuration, I created serman, a command line tool (install with npm i -g serman) to install an executable as a service. All you need to write (and only write once) is a simple service configuration file along with your executable. Run

serman install <path_to_config_file>

will install the service. stdout and stderr are all logged. For more info, take a look at the project website.

A working configuration file is very simple, as demonstrated below. But it also has many useful features such as <env> and <persistent_env> below.

<service>
  <id>hello</id>
  <name>hello</name>
  <description>This service runs the hello application</description>

  <executable>node.exe</executable>

  <!-- 
       {{dir}} will be expanded to the containing directory of your 
       config file, which is normally where your executable locates 
   -->
  <arguments>"{{dir}}\hello.js"</arguments>

  <logmode>rotate</logmode>

  <!-- OPTIONAL FEATURE:
       NODE_ENV=production will be an environment variable 
       available to your application, but not visible outside 
       of your application
   -->
  <env name="NODE_ENV" value="production"/>

  <!-- OPTIONAL FEATURE:
       FOO_SERVICE_PORT=8989 will be persisted as an environment
       variable machine-wide.
   -->
  <persistent_env name="FOO_SERVICE_PORT" value="8989" />
</service>

Android: Pass data(extras) to a fragment

great answer by @Rarw. Try using a bundle to pass information from one fragment to another

Convert an NSURL to an NSString

If you're interested in the pure string:

[myUrl absoluteString];

If you're interested in the path represented by the URL (and to be used with NSFileManager methods for example):

[myUrl path];

Check if process returns 0 with batch file

To check whether a process/command returned 0 or not, use the operators && == 0 or not == 0 ||:

Just add operator to your script:

execute_command && (

       echo\Return 0, with no execution error
) || (
        echo\Return non 0, something went wrong
     )

command && echo\Return 0 || echo\Return non 0

Allow multi-line in EditText view in Android?

This is how I applied the code snippet below and it's working fine. Hope, this would help somebody.

<EditText 
    android:id="@+id/EditText02"
    android:gravity="top|left" 
    android:inputType="textMultiLine"
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:lines="5" 
    android:scrollHorizontally="false" 
/>

Cheers! ...Thanks.

How should I read a file line-by-line in Python?

There is exactly one reason why the following is preferred:

with open('filename.txt') as fp:
    for line in fp:
        print line

We are all spoiled by CPython's relatively deterministic reference-counting scheme for garbage collection. Other, hypothetical implementations of Python will not necessarily close the file "quickly enough" without the with block if they use some other scheme to reclaim memory.

In such an implementation, you might get a "too many files open" error from the OS if your code opens files faster than the garbage collector calls finalizers on orphaned file handles. The usual workaround is to trigger the GC immediately, but this is a nasty hack and it has to be done by every function that could encounter the error, including those in libraries. What a nightmare.

Or you could just use the with block.

Bonus Question

(Stop reading now if are only interested in the objective aspects of the question.)

Why isn't that included in the iterator protocol for file objects?

This is a subjective question about API design, so I have a subjective answer in two parts.

On a gut level, this feels wrong, because it makes iterator protocol do two separate things—iterate over lines and close the file handle—and it's often a bad idea to make a simple-looking function do two actions. In this case, it feels especially bad because iterators relate in a quasi-functional, value-based way to the contents of a file, but managing file handles is a completely separate task. Squashing both, invisibly, into one action, is surprising to humans who read the code and makes it more difficult to reason about program behavior.

Other languages have essentially come to the same conclusion. Haskell briefly flirted with so-called "lazy IO" which allows you to iterate over a file and have it automatically closed when you get to the end of the stream, but it's almost universally discouraged to use lazy IO in Haskell these days, and Haskell users have mostly moved to more explicit resource management like Conduit which behaves more like the with block in Python.

On a technical level, there are some things you may want to do with a file handle in Python which would not work as well if iteration closed the file handle. For example, suppose I need to iterate over the file twice:

with open('filename.txt') as fp:
    for line in fp:
        ...
    fp.seek(0)
    for line in fp:
        ...

While this is a less common use case, consider the fact that I might have just added the three lines of code at the bottom to an existing code base which originally had the top three lines. If iteration closed the file, I wouldn't be able to do that. So keeping iteration and resource management separate makes it easier to compose chunks of code into a larger, working Python program.

Composability is one of the most important usability features of a language or API.

Scala vs. Groovy vs. Clojure

I'm reading the Pragmatic Programmers book "Groovy Recipes: Greasing the wheels of Java" by Scott Davis, Copyright 2008 and printed in April of the same year.

It's a bit out of date but the book makes it clear that Groovy is literally an extension of Java. I can write Java code that functions exactly like Java and rename the file *.groovy and it works fine. According to the book, the reverse is true if I include the requisite libraries. So far, experimentation seems to bear this out.

Java Initialize an int array in a constructor

The best way is not to write any initializing statements. This is because if you write int a[]=new int[3] then by default, in Java all the values of array i.e. a[0], a[1] and a[2] are initialized to 0! Regarding the local variable hiding a field, post your entire code for us to come to conclusion.

Execute PHP script in cron job

You may need to run the cron job as a user with permissions to execute the PHP script. Try executing the cron job as root, using the command runuser (man runuser). Or create a system crontable and run the PHP script as an authorized user, as @Philip described.

I provide a detailed answer how to use cron in this stackoverflow post.

How to write a cron that will run a script every day at midnight?

jQuery Remove string from string

Pretty sure nobody answer your question to your exact terms, you want it for dynamic text

var newString = myString.substring( myString.indexOf( "," ) +1, myString.length );

It takes a substring from the first comma, to the end

How to split a line into words separated by one or more spaces in bash?

s='foo bar baz'
a=( $s )
echo ${a[0]}
echo ${a[1]}
...

numpy.where() detailed, step-by-step explanation / examples

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

How to get `DOM Element` in Angular 2?

Angular 2.0.0 Final:

I have found that using a ViewChild setter is most reliable way to set the initial form control focus:

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => {
            this._renderer.invokeElementMethod(_input.nativeElement, "focus");
        }, 0);
    }
}

The setter is first called with an undefined value followed by a call with an initialized ElementRef.

Working example and full source here: http://plnkr.co/edit/u0sLLi?p=preview

Using TypeScript 2.0.3 Final/RTM, Angular 2.0.0 Final/RTM, and Chrome 53.0.2785.116 m (64-bit).

UPDATE for Angular 4+

Renderer has been deprecated in favor of Renderer2, but Renderer2 does not have the invokeElementMethod. You will need to access the DOM directly to set the focus as in input.nativeElement.focus().

I'm still finding that the ViewChild setter approach works best. When using AfterViewInit I sometimes get read property 'nativeElement' of undefined error.

@ViewChild("myInput")
set myInput(_input: ElementRef | undefined) {
    if (_input !== undefined) {
        setTimeout(() => { //This setTimeout call may not be necessary anymore.
            _input.nativeElement.focus();
        }, 0);
    }
}

Why is there no ForEach extension method on IEnumerable?

While I agree that it's better to use the built-in foreach construct in most cases, I find the use of this variation on the ForEach<> extension to be a little nicer than having to manage the index in a regular foreach myself:

public static int ForEach<T>(this IEnumerable<T> list, Action<int, T> action)
{
    if (action == null) throw new ArgumentNullException("action");

    var index = 0;

    foreach (var elem in list)
        action(index++, elem);

    return index;
}
Example
var people = new[] { "Moe", "Curly", "Larry" };
people.ForEach((i, p) => Console.WriteLine("Person #{0} is {1}", i, p));

Would give you:

Person #0 is Moe
Person #1 is Curly
Person #2 is Larry

How to create a MySQL hierarchical recursive query?

Based on the @trincot answer, very good explained, I use WITH RECURSIVE () statement to create a breadcrumb using id of the current page and go backwards in the hierarchy to find the every parent in my route table.

So, the @trincot solution is adapted here in the opposite direction to find parents instead of descendants.

I also added depth value which is usefull to invert result order (otherwise the breadcrumb would be upside down).

WITH RECURSIVE cte (
    `id`,
    `title`,
    `url`,
    `icon`,
    `class`,
    `parent_id`,
    `depth`
) AS (
    SELECT   
        `id`,
        `title`,
        `url`,
        `icon`,
        `class`,
        `parent_id`,
        1 AS `depth` 
    FROM     `route`
    WHERE    `id` = :id
      
    UNION ALL 
    SELECT 
        P.`id`,
        P.`title`,
        P.`url`,
        P.`icon`,
        P.`class`,
        P.`parent_id`,
        `depth` + 1
    FROM `route` P
        
    INNER JOIN cte
        ON P.`id` = cte.`parent_id`
)
SELECT * FROM cte ORDER BY `depth` DESC;

Before upgrade to mySQL 8+, I was using vars but it's deprecated and no more working on my 8.0.22 version !

EDIT 2021-02-19 : Example for hierarchical menu

After @david comment I decided to try to make a full hierarchical menu with all nodes and sorted as I want (with sorting column which sort items in each depth). Very usefull for my user/authorization matrix page.

This really simplifies my old version with one query on each depth (PHP loops).

ERP authroization Matrix

This example intergrates an INNER JOIN with url table to filter route by website (multi-websites CMS system).

You can see the essential path column that contains CONCAT() function to sort the menu in the right way.

SELECT R.* FROM (
    WITH RECURSIVE cte (
        `id`,
        `title`,
        `url`,
        `icon`,
        `class`,
        `parent`,
        `depth`,
        `sorting`,
        `path`
    ) AS (
        SELECT 
            `id`,
            `title`,
            `url`,
            `icon`,
            `class`,
            `parent`,
            1 AS `depth`,
            `sorting`,
            CONCAT(`sorting`, ' ' , `title`) AS `path`
        FROM `route`
        WHERE `parent` = 0
        UNION ALL SELECT 
            D.`id`,
            D.`title`,
            D.`url`,
            D.`icon`,
            D.`class`,
            D.`parent`,
            `depth` + 1,
            D.`sorting`,
            CONCAT(cte.`path`, ' > ', D.`sorting`, ' ' , D.`title`)
        FROM `route` D
        INNER JOIN cte
            ON cte.`id` = D.`parent`
    )
    SELECT * FROM cte
) R

INNER JOIN `url` U
    ON R.`id` = U.`route_id`
    AND U.`site_id` = 1

ORDER BY `path` ASC  

Issue pushing new code in Github

Issue a forced push with the command:

git push -f origin master

change Oracle user account status from EXPIRE(GRACE) to OPEN

Step-1 Need to find user details by using below query

SQL> select username, account_status from dba_users where username='BOB';

USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            EXPIRED

Step-2 Get users password by using below query.

SQL>SELECT 'ALTER USER '|| name ||' IDENTIFIED BY VALUES '''|| spare4 ||';'|| password ||''';' FROM sys.user$ WHERE name='BOB';

ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';

Step -3 Run Above alter query

SQL> ALTER USER BOB IDENTIFIED BY VALUES 'S:9BDD17811E21EFEDFB1403AAB1DD86AB481E;T:602E36430C0D8DF7E1E453;2F9933095143F432';
User altered.

Step-4 :Check users account status

SQL> select username, account_status from dba_users where username='BOB';
USERNAME                       ACCOUNT_STATUS
------------------------------ --------------------------------
BOB                            OPEN

How To change the column order of An Existing Table in SQL Server 2008

Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:

For Columns:

  • Try not to use SELECT *, but instead specify the order of columns in the select list as in: SELECT Member_ID, MemberName, MemberAddress from TableName. This will guarantee order and will ease maintenance if columns get added.

For Rows:

  • Row order in your result set is only guaranteed if you specify the ORDER BY clause.
  • If no ORDER BY clause is specified the result set may differ as the Query Plan might differ or the database pages might have changed.

Hope this helps...

RegEx for matching "A-Z, a-z, 0-9, _" and "."

Working from what you've given I'll assume you want to check that someone has NOT entered any letters other than the ones you've listed. For that to work you want to search for any characters other than those listed:

[^A-Za-z0-9_.]

And use that in a match in your code, something like:

if ( /[^A-Za-z0-9_.]/.match( your_input_string ) ) {
   alert( "you have entered invalid data" );
}

Hows that?

Any way to make plot points in scatterplot more transparent in R?

Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?

addTrans <- function(color,trans)
{
  # This function adds transparancy to a color.
  # Define transparancy with an integer between 0 and 255
  # 0 being fully transparant and 255 being fully visable
  # Works with either color and trans a vector of equal length,
  # or one of the two of length 1.

  if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
  if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
  if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))

  num2hex <- function(x)
  {
    hex <- unlist(strsplit("0123456789ABCDEF",split=""))
    return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
  }
  rgb <- rbind(col2rgb(color),trans)
  res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
  return(res)
}

Some examples:

cols <- sample(c("red","green","pink"),100,TRUE)

# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)

# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)

# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)

Direct casting vs 'as' operator?

string s = o as string; // 2

Is prefered, as it avoids the performance penalty of double casting.

Converting string to title case

String TitleCaseString(String s)
{
    if (s == null || s.Length == 0) return s;

    string[] splits = s.Split(' ');

    for (int i = 0; i < splits.Length; i++)
    {
        switch (splits[i].Length)
        {
            case 1:
                break;

            default:
                splits[i] = Char.ToUpper(splits[i][0]) + splits[i].Substring(1);
                break;
        }
    }

    return String.Join(" ", splits);
}

Convert List(of object) to List(of string)

This works for all types.

List<object> objects = new List<object>();
List<string> strings = objects.Select(s => (string)s).ToList();

Groovy - Convert object to JSON string

You can use JsonBuilder for that.

Example Code:

import groovy.json.JsonBuilder

class Person {
    String name
    String address
}

def o = new Person( name: 'John Doe', address: 'Texas' )

println new JsonBuilder( o ).toPrettyString()

Best way to log POST data in Apache?

You can use [ModSecurity][1] to view POST data.

Install on Debian/Ubuntu:

$ sudo apt install libapache2-mod-security2

Use the recommended configuration file:

$ sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf

Reload Apache:

$ sudo service apache2 reload

You will now find your data logged under /var/log/apache2/modsec_audit.log

$ tail -f /var/log/apache2/modsec_audit.log
--2222229-A--
[23/Nov/2017:11:36:35 +0000] 
--2222229-B--
POST / HTTP/1.1
Content-Type: application/json
User-Agent: curl
Host: example.com

--2222229-C--
{"test":"modsecurity"}

Django: TemplateSyntaxError: Could not parse the remainder

also happens when you use jinja templates (which have different syntax for calling object methods) and you forget to set it in settings.py

Convert String to Carbon

Try this

$date = Carbon::parse(date_format($youttimestring,'d/m/Y H:i:s'));
echo $date;

Maximum number of rows in an MS Access database engine table?

It all depends. Theoretically using a single column with 4 byte data type. You could store 300 000 rows. But there is probably alot of overhead in the database even before you do anything. I read some where that you could have 1.000.000 rows but again, it all depends..

You can also link databases together. Limiting yourself to only disk space.

PHP list of specific files in a directory

You should use glob.

glob('*.xml')

More about using glob and advanced filtering:

http://domexception.blogspot.fi/2013/08/php-using-functional-programming-for.html

How to calculate the median of an array?

The Arrays class in Java has a static sort function, which you can invoke with Arrays.sort(numArray).

Arrays.sort(numArray);
double median;
if (numArray.length % 2 == 0)
    median = ((double)numArray[numArray.length/2] + (double)numArray[numArray.length/2 - 1])/2;
else
    median = (double) numArray[numArray.length/2];

Tkinter example code for multiple windows, why won't buttons load correctly?

You need to specify the master for the second button. Otherwise it will get packed onto the first window. This is needed not only for Button, but also for other widgets and non-gui objects such as StringVar.

Quick fix: add the frame new as the first argument to your Button in Demo2.

Possibly better: Currently you have Demo2 inheriting from tk.Frame but I think this makes more sense if you change Demo2 to be something like this,

class Demo2(tk.Toplevel):     
    def __init__(self):
        tk.Toplevel.__init__(self)
        self.title("Demo 2")
        self.button = tk.Button(self, text="Button 2", # specified self as master
                                width=25, command=self.close_window)
        self.button.pack()

    def close_window(self):
        self.destroy()

Just as a suggestion, you should only import tkinter once. Pick one of your first two import statements.

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

Tensorflow: how to save/restore a model?

Here's my simple solution for the two basic cases differing on whether you want to load the graph from file or build it during runtime.

This answer holds for Tensorflow 0.12+ (including 1.0).

Rebuilding the graph in code

Saving

graph = ... # build the graph
saver = tf.train.Saver()  # create the saver after the graph
with ... as sess:  # your session object
    saver.save(sess, 'my-model')

Loading

graph = ... # build the graph
saver = tf.train.Saver()  # create the saver after the graph
with ... as sess:  # your session object
    saver.restore(sess, tf.train.latest_checkpoint('./'))
    # now you can use the graph, continue training or whatever

Loading also the graph from a file

When using this technique, make sure all your layers/variables have explicitly set unique names. Otherwise Tensorflow will make the names unique itself and they'll be thus different from the names stored in the file. It's not a problem in the previous technique, because the names are "mangled" the same way in both loading and saving.

Saving

graph = ... # build the graph

for op in [ ... ]:  # operators you want to use after restoring the model
    tf.add_to_collection('ops_to_restore', op)

saver = tf.train.Saver()  # create the saver after the graph
with ... as sess:  # your session object
    saver.save(sess, 'my-model')

Loading

with ... as sess:  # your session object
    saver = tf.train.import_meta_graph('my-model.meta')
    saver.restore(sess, tf.train.latest_checkpoint('./'))
    ops = tf.get_collection('ops_to_restore')  # here are your operators in the same order in which you saved them to the collection

Error importing Seaborn module in Python

If your python version is 2.+, you can type below code to the terminal :

pip install seaborn

if python version is 3+, type below:

pip3 install seaborn

Why can't I use a list as a dict key in python?

Your awnser can be found here:

Why Lists Can't Be Dictionary Keys

Newcomers to Python often wonder why, while the language includes both a tuple and a list type, tuples are usable as a dictionary keys, while lists are not. This was a deliberate design decision, and can best be explained by first understanding how Python dictionaries work.

Source & more info: http://wiki.python.org/moin/DictionaryKeys

WebRTC vs Websockets: If WebRTC can do Video, Audio, and Data, why do I need Websockets?

Security is one aspect you missed.

With Websockets the data has to go via a central webserver which typically sees all the traffic and can access it.

With WebRTC the data is end-to-end encrypted and does not pass through a server (except sometimes TURN servers are needed, but they have no access to the body of the messages they forward).

Depending on your application this may or may not matter.

If you are sending large amounts of data, the saving in cloud bandwidth costs due to webRTC's P2P architecture may be worth considering too.

What does Ruby have that Python doesn't, and vice versa?

Python has a "we're all adults here" mentality. Thus, you'll find that Ruby has things like constants while Python doesn't (although Ruby's constants only raise a warning). The Python way of thinking is that if you want to make something constant, you should put the variable names in all caps and not change it.

For example, Ruby:

>> PI = 3.14
=> 3.14
>> PI += 1
(irb):2: warning: already initialized constant PI
=> 4.14

Python:

>>> PI = 3.14
>>> PI += 1
>>> PI
4.1400000000000006

mysql-python install error: Cannot open include file 'config-win.h'

For me, it worked when I selected the correct bit of my Python version, NOT the one of my computer version.

Mine is 32bit, and my computer is 64bit. That was the problem and the 32bit version of fixed it.

to be exact, here is the one that worked for me: mysqlclient-1.3.13-cp37-cp37m-win32.whl

How do I use namespaces with TypeScript external modules?

Try to organize by folder:

baseTypes.ts

export class Animal {
    move() { /* ... */ }
}

export class Plant {
    photosynthesize() { /* ... */ }
}

dog.ts

import b = require('./baseTypes');

export class Dog extends b.Animal {
    woof() { }
}   

tree.ts

import b = require('./baseTypes');

class Tree extends b.Plant {
}

LivingThings.ts

import dog = require('./dog')
import tree = require('./tree')

export = {
    dog: dog,
    tree: tree
}

main.ts

import LivingThings = require('./LivingThings');
console.log(LivingThings.Tree)
console.log(LivingThings.Dog)

The idea is that your module themselves shouldn't care / know they are participating in a namespace, but this exposes your API to the consumer in a compact, sensible way which is agnostic to which type of module system you are using for the project.

What are naming conventions for MongoDB?

DATABASE

  • camelCase
  • append DB on the end of name
  • make singular (collections are plural)

MongoDB states a nice example:

To select a database to use, in the mongo shell, issue the use <db> statement, as in the following example:

use myDB
use myNewDB

Content from: https://docs.mongodb.com/manual/core/databases-and-collections/#databases

COLLECTIONS

  • Lowercase names: avoids case sensitivity issues, MongoDB collection names are case sensitive.

  • Plural: more obvious to label a collection of something as the plural, e.g. "files" rather than "file"

  • >No word separators: Avoids issues where different people (incorrectly) separate words (username <-> user_name, first_name <->
    firstname). This one is up for debate according to a few people
    around here but provided the argument is isolated to collection names I don't think it should be ;) If you find yourself improving the
    readability of your collection name by adding underscores or
    camelCasing your collection name is probably too long or should use
    periods as appropriate which is the standard for collection
    categorization.

  • Dot notation for higher detail collections: Gives some indication to how collections are related. For example you can be reasonably sure you could delete "users.pagevisits" if you deleted "users", provided the people that designed the schema did a good job.

Content from: http://www.tutespace.com/2016/03/schema-design-and-naming-conventions-in.html

For collections I'm following these suggested patterns until I find official MongoDB documentation.

C# cannot convert method to non delegate type

To execute a method you need to add parentheses, even if the method does not take arguments.

So it should be:

string t = obj.getTitle();

string encoding and decoding?

That's because your input string can’t be converted according to the encoding rules (strict by default).

I don't know, but I always encoded using directly unicode() constructor, at least that's the ways at the official documentation:

unicode(your_str, errors="ignore")

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

This might be helpful for whoever else faces this problem. I finally figured out a solution. Turns out, even if we use the inline for "content-disposition" and specify a file name, the browsers still do not use the file name. Instead browsers try and interpret the file name based on the Path/URL.

You can read further on this URL: Securly download file inside browser with correct filename

This gave me an idea, I just created my URL route that would convert the URL and end it with the name of the file I wanted to give the file. So for e.g. my original controller call just consisted of passing the Order Id of the Order being printed. I was expecting the file name to be of the format Order{0}.pdf where {0} is the Order Id. Similarly for quotes, I wanted Quote{0}.pdf.

In my controller, I just went ahead and added an additional parameter to accept the file name. I passed the filename as a parameter in the URL.Action method.

I then created a new route that would map that URL to the format: http://localhost/ShoppingCart/PrintQuote/1054/Quote1054.pdf


routes.MapRoute("", "{controller}/{action}/{orderId}/{fileName}",
                new { controller = "ShoppingCart", action = "PrintQuote" }
                , new string[] { "x.x.x.Controllers" }
            );

This pretty much solved my issue. Hoping this helps someone!

Cheerz, Anup

How to convert string to boolean in typescript Angular 4

Boolean("true") will do the work too

Jmeter - Run .jmx file through command line and get the summary report in a excel

You can run JMeter from the command line using the -n parameter for 'Non-GUI' and the -t parameter for the test plan file.

    jmeter -n -t "PATHTOJMXFILE"        

If you want to further customize the command line experience, I would direct you to the 'Getting Started' section of their documentation.

MessageBox with YesNoCancel - No & Cancel triggers same event

This is how you can do it without a Dim, using MessageBox.Show instead of MsgBox. This is in my opinion the cleanest way of writing it!

Select Case MessageBox.Show("Message", "Title", MessageBoxButtons.YesNo)
    Case vbYes
        ' Other Code goes here
    Case vbNo
        ' Other Code goes here
End Select

You can shorten it down even further by using If:

If MessageBox.Show("Message", "Title", MessageBoxButtons.YesNo) = vbYes Then
    ' Other Code goes here
End If

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

Perfectly described in pkozlowski's comment. I had working solution with AngularJS 1.2.6 and ASP.NET Web Api but when I had upgraded AngularJS to 1.3.3 then requests failed.

  • Solution for Web Api server was to add handling of the OPTIONS requests at the beginning of configuration method (more info in this blog post):

    app.Use(async (context, next) =>
    {
        IOwinRequest req = context.Request;
        IOwinResponse res = context.Response;
        if (req.Path.StartsWithSegments(new PathString("/Token")))
        {
            var origin = req.Headers.Get("Origin");
            if (!string.IsNullOrEmpty(origin))
            {
                res.Headers.Set("Access-Control-Allow-Origin", origin);
            }
            if (req.Method == "OPTIONS")
            {
                res.StatusCode = 200;
                res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Methods", "GET", "POST");
                res.Headers.AppendCommaSeparatedValues("Access-Control-Allow-Headers", "authorization", "content-type");
                return;
            }
        }
        await next();
    });
    

curl: (35) SSL connect error

If updating cURL doesn't fix it, updating NSS should do the trick.

Angular 2.0 router not working on reloading the browser

For those of us struggling through life in IIS: use the following PowerShell code to fix this issue based on the official Angular 2 docs (that someone posted in this thread? http://blog.angular-university.io/angular2-router/)

Import-WebAdministration
# Grab the 404 handler and update it to redirect to index.html.
$redirect = Get-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS 
$redirect.path = "/index.html"
$redirect.responseMode = 1
# shove the updated config back into IIS
Set-WebConfiguration -filter "/system.WebServer/httperrors/error[@statusCode='404']" -PSPath IIS:\Sites\LIS -value $redirect

This redirects the 404 to the /index.html file as per the suggestion in the Angular 2 docs (link above).

"Too many characters in character literal error"

I faced the same issue. String.Replace('\\.','') is not valid statement and throws the same error. Thanks to C# we can use double quotes instead of single quotes and following works String.Replace("\\.","")

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

Because the operating system may not do so. The flush operation forces the file data into the file cache in RAM, and from there it's the OS's job to actually send it to the disk.

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

What is the optimal algorithm for the game 2048?

My attempt uses expectimax like other solutions above, but without bitboards. Nneonneo's solution can check 10millions of moves which is approximately a depth of 4 with 6 tiles left and 4 moves possible (2*6*4)4. In my case, this depth takes too long to explore, I adjust the depth of expectimax search according to the number of free tiles left:

depth = free > 7 ? 1 : (free > 4 ? 2 : 3)

The scores of the boards are computed with the weighted sum of the square of the number of free tiles and the dot product of the 2D grid with this:

[[10,8,7,6.5],
 [.5,.7,1,3],
 [-.5,-1.5,-1.8,-2],
 [-3.8,-3.7,-3.5,-3]]

which forces to organize tiles descendingly in a sort of snake from the top left tile.

code below or on github:

_x000D_
_x000D_
var n = 4,_x000D_
 M = new MatrixTransform(n);_x000D_
_x000D_
var ai = {weights: [1, 1], depth: 1}; // depth=1 by default, but we adjust it on every prediction according to the number of free tiles_x000D_
_x000D_
var snake= [[10,8,7,6.5],_x000D_
            [.5,.7,1,3],_x000D_
            [-.5,-1.5,-1.8,-2],_x000D_
            [-3.8,-3.7,-3.5,-3]]_x000D_
snake=snake.map(function(a){return a.map(Math.exp)})_x000D_
_x000D_
initialize(ai)_x000D_
_x000D_
function run(ai) {_x000D_
 var p;_x000D_
 while ((p = predict(ai)) != null) {_x000D_
  move(p, ai);_x000D_
 }_x000D_
 //console.log(ai.grid , maxValue(ai.grid))_x000D_
 ai.maxValue = maxValue(ai.grid)_x000D_
 console.log(ai)_x000D_
}_x000D_
_x000D_
function initialize(ai) {_x000D_
 ai.grid = [];_x000D_
 for (var i = 0; i < n; i++) {_x000D_
  ai.grid[i] = []_x000D_
  for (var j = 0; j < n; j++) {_x000D_
   ai.grid[i][j] = 0;_x000D_
  }_x000D_
 }_x000D_
 rand(ai.grid)_x000D_
 rand(ai.grid)_x000D_
 ai.steps = 0;_x000D_
}_x000D_
_x000D_
function move(p, ai) { //0:up, 1:right, 2:down, 3:left_x000D_
 var newgrid = mv(p, ai.grid);_x000D_
 if (!equal(newgrid, ai.grid)) {_x000D_
  //console.log(stats(newgrid, ai.grid))_x000D_
  ai.grid = newgrid;_x000D_
  try {_x000D_
   rand(ai.grid)_x000D_
   ai.steps++;_x000D_
  } catch (e) {_x000D_
   console.log('no room', e)_x000D_
  }_x000D_
 }_x000D_
}_x000D_
_x000D_
function predict(ai) {_x000D_
 var free = freeCells(ai.grid);_x000D_
 ai.depth = free > 7 ? 1 : (free > 4 ? 2 : 3);_x000D_
 var root = {path: [],prob: 1,grid: ai.grid,children: []};_x000D_
 var x = expandMove(root, ai)_x000D_
 //console.log("number of leaves", x)_x000D_
 //console.log("number of leaves2", countLeaves(root))_x000D_
 if (!root.children.length) return null_x000D_
 var values = root.children.map(expectimax);_x000D_
 var mx = max(values);_x000D_
 return root.children[mx[1]].path[0]_x000D_
_x000D_
}_x000D_
_x000D_
function countLeaves(node) {_x000D_
 var x = 0;_x000D_
 if (!node.children.length) return 1;_x000D_
 for (var n of node.children)_x000D_
  x += countLeaves(n);_x000D_
 return x;_x000D_
}_x000D_
_x000D_
function expectimax(node) {_x000D_
 if (!node.children.length) {_x000D_
  return node.score_x000D_
 } else {_x000D_
  var values = node.children.map(expectimax);_x000D_
  if (node.prob) { //we are at a max node_x000D_
   return Math.max.apply(null, values)_x000D_
  } else { // we are at a random node_x000D_
   var avg = 0;_x000D_
   for (var i = 0; i < values.length; i++)_x000D_
    avg += node.children[i].prob * values[i]_x000D_
   return avg / (values.length / 2)_x000D_
  }_x000D_
 }_x000D_
}_x000D_
_x000D_
function expandRandom(node, ai) {_x000D_
 var x = 0;_x000D_
 for (var i = 0; i < node.grid.length; i++)_x000D_
  for (var j = 0; j < node.grid.length; j++)_x000D_
   if (!node.grid[i][j]) {_x000D_
    var grid2 = M.copy(node.grid),_x000D_
     grid4 = M.copy(node.grid);_x000D_
    grid2[i][j] = 2;_x000D_
    grid4[i][j] = 4;_x000D_
    var child2 = {grid: grid2,prob: .9,path: node.path,children: []};_x000D_
    var child4 = {grid: grid4,prob: .1,path: node.path,children: []}_x000D_
    node.children.push(child2)_x000D_
    node.children.push(child4)_x000D_
    x += expandMove(child2, ai)_x000D_
    x += expandMove(child4, ai)_x000D_
   }_x000D_
 return x;_x000D_
}_x000D_
_x000D_
function expandMove(node, ai) { // node={grid,path,score}_x000D_
 var isLeaf = true,_x000D_
  x = 0;_x000D_
 if (node.path.length < ai.depth) {_x000D_
  for (var move of[0, 1, 2, 3]) {_x000D_
   var grid = mv(move, node.grid);_x000D_
   if (!equal(grid, node.grid)) {_x000D_
    isLeaf = false;_x000D_
    var child = {grid: grid,path: node.path.concat([move]),children: []}_x000D_
    node.children.push(child)_x000D_
    x += expandRandom(child, ai)_x000D_
   }_x000D_
  }_x000D_
 }_x000D_
 if (isLeaf) node.score = dot(ai.weights, stats(node.grid))_x000D_
 return isLeaf ? 1 : x;_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
var cells = []_x000D_
var table = document.querySelector("table");_x000D_
for (var i = 0; i < n; i++) {_x000D_
 var tr = document.createElement("tr");_x000D_
 cells[i] = [];_x000D_
 for (var j = 0; j < n; j++) {_x000D_
  cells[i][j] = document.createElement("td");_x000D_
  tr.appendChild(cells[i][j])_x000D_
 }_x000D_
 table.appendChild(tr);_x000D_
}_x000D_
_x000D_
function updateUI(ai) {_x000D_
 cells.forEach(function(a, i) {_x000D_
  a.forEach(function(el, j) {_x000D_
   el.innerHTML = ai.grid[i][j] || ''_x000D_
  })_x000D_
 });_x000D_
}_x000D_
_x000D_
_x000D_
updateUI(ai);_x000D_
updateHint(predict(ai));_x000D_
_x000D_
function runAI() {_x000D_
 var p = predict(ai);_x000D_
 if (p != null && ai.running) {_x000D_
  move(p, ai);_x000D_
  updateUI(ai);_x000D_
  updateHint(p);_x000D_
  requestAnimationFrame(runAI);_x000D_
 }_x000D_
}_x000D_
runai.onclick = function() {_x000D_
 if (!ai.running) {_x000D_
  this.innerHTML = 'stop AI';_x000D_
  ai.running = true;_x000D_
  runAI();_x000D_
 } else {_x000D_
  this.innerHTML = 'run AI';_x000D_
  ai.running = false;_x000D_
  updateHint(predict(ai));_x000D_
 }_x000D_
}_x000D_
_x000D_
_x000D_
function updateHint(dir) {_x000D_
 hintvalue.innerHTML = ['?', '?', '?', '?'][dir] || '';_x000D_
}_x000D_
_x000D_
document.addEventListener("keydown", function(event) {_x000D_
 if (!event.target.matches('.r *')) return;_x000D_
 event.preventDefault(); // avoid scrolling_x000D_
 if (event.which in map) {_x000D_
  move(map[event.which], ai)_x000D_
  console.log(stats(ai.grid))_x000D_
  updateUI(ai);_x000D_
  updateHint(predict(ai));_x000D_
 }_x000D_
})_x000D_
var map = {_x000D_
 38: 0, // Up_x000D_
 39: 1, // Right_x000D_
 40: 2, // Down_x000D_
 37: 3, // Left_x000D_
};_x000D_
init.onclick = function() {_x000D_
 initialize(ai);_x000D_
 updateUI(ai);_x000D_
 updateHint(predict(ai));_x000D_
}_x000D_
_x000D_
_x000D_
function stats(grid, previousGrid) {_x000D_
_x000D_
 var free = freeCells(grid);_x000D_
_x000D_
 var c = dot2(grid, snake);_x000D_
_x000D_
 return [c, free * free];_x000D_
}_x000D_
_x000D_
function dist2(a, b) { //squared 2D distance_x000D_
 return Math.pow(a[0] - b[0], 2) + Math.pow(a[1] - b[1], 2)_x000D_
}_x000D_
_x000D_
function dot(a, b) {_x000D_
 var r = 0;_x000D_
 for (var i = 0; i < a.length; i++)_x000D_
  r += a[i] * b[i];_x000D_
 return r_x000D_
}_x000D_
_x000D_
function dot2(a, b) {_x000D_
 var r = 0;_x000D_
 for (var i = 0; i < a.length; i++)_x000D_
  for (var j = 0; j < a[0].length; j++)_x000D_
   r += a[i][j] * b[i][j]_x000D_
 return r;_x000D_
}_x000D_
_x000D_
function product(a) {_x000D_
 return a.reduce(function(v, x) {_x000D_
  return v * x_x000D_
 }, 1)_x000D_
}_x000D_
_x000D_
function maxValue(grid) {_x000D_
 return Math.max.apply(null, grid.map(function(a) {_x000D_
  return Math.max.apply(null, a)_x000D_
 }));_x000D_
}_x000D_
_x000D_
function freeCells(grid) {_x000D_
 return grid.reduce(function(v, a) {_x000D_
  return v + a.reduce(function(t, x) {_x000D_
   return t + (x == 0)_x000D_
  }, 0)_x000D_
 }, 0)_x000D_
}_x000D_
_x000D_
function max(arr) { // return [value, index] of the max_x000D_
 var m = [-Infinity, null];_x000D_
 for (var i = 0; i < arr.length; i++) {_x000D_
  if (arr[i] > m[0]) m = [arr[i], i];_x000D_
 }_x000D_
 return m_x000D_
}_x000D_
_x000D_
function min(arr) { // return [value, index] of the min_x000D_
 var m = [Infinity, null];_x000D_
 for (var i = 0; i < arr.length; i++) {_x000D_
  if (arr[i] < m[0]) m = [arr[i], i];_x000D_
 }_x000D_
 return m_x000D_
}_x000D_
_x000D_
function maxScore(nodes) {_x000D_
 var min = {_x000D_
  score: -Infinity,_x000D_
  path: []_x000D_
 };_x000D_
 for (var node of nodes) {_x000D_
  if (node.score > min.score) min = node;_x000D_
 }_x000D_
 return min;_x000D_
}_x000D_
_x000D_
_x000D_
function mv(k, grid) {_x000D_
 var tgrid = M.itransform(k, grid);_x000D_
 for (var i = 0; i < tgrid.length; i++) {_x000D_
  var a = tgrid[i];_x000D_
  for (var j = 0, jj = 0; j < a.length; j++)_x000D_
   if (a[j]) a[jj++] = (j < a.length - 1 && a[j] == a[j + 1]) ? 2 * a[j++] : a[j]_x000D_
  for (; jj < a.length; jj++)_x000D_
   a[jj] = 0;_x000D_
 }_x000D_
 return M.transform(k, tgrid);_x000D_
}_x000D_
_x000D_
function rand(grid) {_x000D_
 var r = Math.floor(Math.random() * freeCells(grid)),_x000D_
  _r = 0;_x000D_
 for (var i = 0; i < grid.length; i++) {_x000D_
  for (var j = 0; j < grid.length; j++) {_x000D_
   if (!grid[i][j]) {_x000D_
    if (_r == r) {_x000D_
     grid[i][j] = Math.random() < .9 ? 2 : 4_x000D_
    }_x000D_
    _r++;_x000D_
   }_x000D_
  }_x000D_
 }_x000D_
}_x000D_
_x000D_
function equal(grid1, grid2) {_x000D_
 for (var i = 0; i < grid1.length; i++)_x000D_
  for (var j = 0; j < grid1.length; j++)_x000D_
   if (grid1[i][j] != grid2[i][j]) return false;_x000D_
 return true;_x000D_
}_x000D_
_x000D_
function conv44valid(a, b) {_x000D_
 var r = 0;_x000D_
 for (var i = 0; i < 4; i++)_x000D_
  for (var j = 0; j < 4; j++)_x000D_
   r += a[i][j] * b[3 - i][3 - j]_x000D_
 return r_x000D_
}_x000D_
_x000D_
function MatrixTransform(n) {_x000D_
 var g = [],_x000D_
  ig = [];_x000D_
 for (var i = 0; i < n; i++) {_x000D_
  g[i] = [];_x000D_
  ig[i] = [];_x000D_
  for (var j = 0; j < n; j++) {_x000D_
   g[i][j] = [[j, i],[i, n-1-j],[j, n-1-i],[i, j]]; // transformation matrix in the 4 directions g[i][j] = [up, right, down, left]_x000D_
   ig[i][j] = [[j, i],[i, n-1-j],[n-1-j, i],[i, j]]; // the inverse tranformations_x000D_
  }_x000D_
 }_x000D_
 this.transform = function(k, grid) {_x000D_
  return this.transformer(k, grid, g)_x000D_
 }_x000D_
 this.itransform = function(k, grid) { // inverse transform_x000D_
  return this.transformer(k, grid, ig)_x000D_
 }_x000D_
 this.transformer = function(k, grid, mat) {_x000D_
  var newgrid = [];_x000D_
  for (var i = 0; i < grid.length; i++) {_x000D_
   newgrid[i] = [];_x000D_
   for (var j = 0; j < grid.length; j++)_x000D_
    newgrid[i][j] = grid[mat[i][j][k][0]][mat[i][j][k][1]];_x000D_
  }_x000D_
  return newgrid;_x000D_
 }_x000D_
 this.copy = function(grid) {_x000D_
  return this.transform(3, grid)_x000D_
 }_x000D_
}
_x000D_
body {_x000D_
 font-family: Arial;_x000D_
}_x000D_
table, th, td {_x000D_
 border: 1px solid black;_x000D_
 margin: 0 auto;_x000D_
 border-collapse: collapse;_x000D_
}_x000D_
td {_x000D_
 width: 35px;_x000D_
 height: 35px;_x000D_
 text-align: center;_x000D_
}_x000D_
button {_x000D_
 margin: 2px;_x000D_
 padding: 3px 15px;_x000D_
 color: rgba(0,0,0,.9);_x000D_
}_x000D_
.r {_x000D_
 display: flex;_x000D_
 align-items: center;_x000D_
 justify-content: center;_x000D_
 margin: .2em;_x000D_
 position: relative;_x000D_
}_x000D_
#hintvalue {_x000D_
 font-size: 1.4em;_x000D_
 padding: 2px 8px;_x000D_
 display: inline-flex;_x000D_
 justify-content: center;_x000D_
 width: 30px;_x000D_
}
_x000D_
<table title="press arrow keys"></table>_x000D_
<div class="r">_x000D_
    <button id=init>init</button>_x000D_
    <button id=runai>run AI</button>_x000D_
    <span id="hintvalue" title="Best predicted move to do, use your arrow keys" tabindex="-1"></span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

php execute a background process

If you are looking to execute a background process via PHP, pipe the command's output to /dev/null and add & to the end of the command.

exec("bg_process > /dev/null &");

Note that you can not utilize the $output parameter of exec() or else PHP will hang (probably until the process completes).

BarCode Image Generator in Java

ZXing is a free open source Java library to read and generate barcode images. You need to get the source code and build the jars yourself. Here's a simple tutorial that I wrote for building with ZXing jars and writing your first program with ZXing.

[http://www.vineetmanohar.com/2010/09/java-barcode-api/]

How to use regex with find command?

Judging from other answers, it seems this might be find's fault.

However you can do it this way instead:

find . * | grep -P "[a-f0-9\-]{36}\.jpg"

You might have to tweak the grep a bit and use different options depending on what you want but it works.

Is it possible for UIStackView to scroll?

Up to date for 2020.

100% storyboard OR 100% code.


Here's the simplest possible explanation:

  1. Have a blank full-screen scene

  2. Add a scroll view. Control-drag from the scroll view to the base view, add left-right-top-bottom, all zero.

  3. Add a stack view in the scroll view. Control-drag from the stack view to the scroll view, add left-right-top-bottom, all zero.

  4. Put two or three labels inside the stack view.

For clarity, make the background color of the label red. Set the label height to 100.

  1. Now set the width of each UILabel:

    Surprisingly, control-drag from the UILabel to the scroll view, not to the stack view, and select equal widths.

To repeat:

Don't control drag from the UILabel to the UILabel's parent - go to the grandparent. (In other words, go all the way to the scroll view, do not go to the stack view.)

It's that simple. That's the secret.

Secret tip - Apple bug:

It will not work with only one item! Add a few labels to make the demo work.

You're done.

Tip: You must add a height to every new item. Every item in any scrolling stack view must have either an intrinsic size (such as a label) or add an explicit height constraint.


The alternative approach:

In the above: surprisingly, set the widths of the UILabels to the width of the scroll view (not the stack view).

Alternately...

Drag from the stack view to the scroll view, and add a "width equal" constraint. This seems strange because you already pinned left-right, but that is how you do it. No matter how strange it seems that's the secret.

So you have two options:

  1. Surprisingly, set the width of each item in the stack view to the width of the scrollview grandparent (not the stackview parent).

or

  1. Surprisingly, set a "width equal" of the stackview to the scrollview - even though you do have the left and right edges of the stackview pinned to the scrollview anyway.

To be clear, do ONE of those methods, do NOT do both.

SSH Port forwarding in a ~/.ssh/config file?

You can use the LocalForward directive in your host yam section of ~/.ssh/config:

LocalForward 5901 computer.myHost.edu:5901

Emulator in Android Studio doesn't start

I had the same problem, but now I'm using it successfully. As you know, the minimum RAM required to run android studio is 4 GB, but if you only have 4 GB RAM, you probably won't be able to run many other applications at the same time.

It's also possible that some windows driver, e.g. graphics, is incompatible. You may want to experiment with software and hardware options for graphics: https://developer.android.com/studio/run/emulator-acceleration.html

It might also help to increase the connection timeout in settings/tasks.

How can I stage and commit all files, including newly added files, using a single command?

Not sure why these answers all dance around what I believe to be the right solution but for what it's worth here is what I use:

1. Create an alias:

git config --global alias.coa "!git add -A && git commit -m"

2. Add all files & commit with a message:

git coa "A bunch of horrible changes"

NOTE: coa is short for commit all and can be replaced with anything your heart desires

HTTP headers in Websockets client API

Technically, you will be sending these headers through the connect function before the protocol upgrade phase. This worked for me in a nodejs project:

var WebSocketClient = require('websocket').client;
var ws = new WebSocketClient();
ws.connect(url, '', headers);

What's the difference between HEAD^ and HEAD~ in Git?

TLDR

~ is what you want most of the time, it references past commits to the current branch

^ references parents (git-merge creates a 2nd parent or more)

A~ is always the same as A^
A~~ is always the same as A^^, and so on
A~2 is not the same as A^2 however,
because ~2 is shorthand for ~~
while ^2 is not shorthand for anything, it means the 2nd parent

How do I determine file encoding in OS X?

Just use:

file -I <filename>

That's it.

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

From here.

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

Exclude all transitive dependencies of a single dependency

if you need to exclude all transitive dependencies from a dependency artifact that you are going to include in an assembly, you can specify this in the descriptor for the assembly-plugin:

<assembly>
    <id>myApp</id>
    <formats>
        <format>zip</format>
    </formats>
    <dependencySets>
        <dependencySet>
            <useTransitiveDependencies>false</useTransitiveDependencies>
            <includes><include>*:struts2-spring-plugin:jar:2.1.6</include></includes>
        </dependencySet>
    </dependencySets>
</assembly>

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

How to increase heap size of an android application?

you can't increase the heap size dynamically.

you can request to use more by using android:largeHeap="true" in the manifest.

also, you can use native memory (NDK & JNI) , so you actually bypass the heap size limitation.

here are some posts i've made about it:

and here's a library i've made for it:

How to preview a part of a large pandas DataFrame, in iPython notebook?

This line will allow you to see all rows (up to the number that you set as 'max_rows') without any rows being hidden by the dots ('.....') that normally appear between head and tail in the print output.

pd.options.display.max_rows = 500

Is it possible to make input fields read-only through CSS?

This is not possible with css, but I have used one css trick in one of my website, please check if this works for you.

The trick is: wrap the input box with a div and make it relative, place a transparent image inside the div and make it absolute over the input text box, so that no one can edit it.

css

.txtBox{
    width:250px;
    height:25px;
    position:relative;
}
.txtBox input{
    width:250px;
    height:25px;
}
.txtBox img{
    position:absolute;
    top:0;
    left:0
}

html

<div class="txtBox">
<input name="" type="text" value="Text Box" />
<img src="http://dev.w3.org/2007/mobileok-ref/test/data/ROOT/GraphicsForSpacingTest/1/largeTransparent.gif" width="250" height="25" alt="" />
</div>

jsFiddle File

SQL User Defined Function Within Select

Yes, you can do almost that:

SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...

Is it possible to force Excel recognize UTF-8 CSV files automatically?

  1. Download & install LibreOffice Calc
  2. Open the csv file of your choice in LibreOffice Calc
  3. Thank the heavens that an import text wizard shows up...
  4. ...select your delimiter and character encoding options
  5. Select the resulting data in Calc and copy paste to Excel

get list of packages installed in Anaconda

For more conda list usage details:

usage: conda-script.py list [-h][-n ENVIRONMENT | -p PATH][--json] [-v] [-q]
[--show-channel-urls] [-c] [-f] [--explicit][--md5] [-e] [-r] [--no-pip][regex]

Can I create view with parameter in MySQL?

Actually if you create func:

create function p1() returns INTEGER DETERMINISTIC NO SQL return @p1;

and view:

create view h_parm as
select * from sw_hardware_big where unit_id = p1() ;

Then you can call a view with a parameter:

select s.* from (select @p1:=12 p) parm , h_parm s;

I hope it helps.

Timeout function if it takes too long to finish

The process for timing out an operations is described in the documentation for signal.

The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.

Note that this will only work on UNIX.

Here's an implementation that creates a decorator (save the following code as timeout.py).

from functools import wraps
import errno
import os
import signal

class TimeoutError(Exception):
    pass

def timeout(seconds=10, error_message=os.strerror(errno.ETIME)):
    def decorator(func):
        def _handle_timeout(signum, frame):
            raise TimeoutError(error_message)

        def wrapper(*args, **kwargs):
            signal.signal(signal.SIGALRM, _handle_timeout)
            signal.alarm(seconds)
            try:
                result = func(*args, **kwargs)
            finally:
                signal.alarm(0)
            return result

        return wraps(func)(wrapper)

    return decorator

This creates a decorator called @timeout that can be applied to any long running functions.

So, in your application code, you can use the decorator like so:

from timeout import timeout

# Timeout a long running function with the default expiry of 10 seconds.
@timeout
def long_running_function1():
    ...

# Timeout after 5 seconds
@timeout(5)
def long_running_function2():
    ...

# Timeout after 30 seconds, with the error "Connection timed out"
@timeout(30, os.strerror(errno.ETIMEDOUT))
def long_running_function3():
    ...

Is there any difference between a GUID and a UUID?

One difference between GUID in SQL Server and UUID in PostgreSQL is letter case; SQL Server outputs upper while PostgreSQL outputs lower.

The hexadecimal values "a" through "f" are output as lower case characters and are case insensitive on input. - rfc4122#section-3

ActionBarActivity: cannot be resolved to a type

For Eclipse, modify project.properties like this: (your path please)

android.library.reference.1=../../../../workspace/appcompat_v7_22

And remove android-support-v4.jar file in your project's libs folder.

Logo image and H1 heading on the same line

<head>
<style>
header{
    color: #f4f4f4;
    background-image: url("header-background.jpeg");    
}

header img{
    float: left;
    display: inline-block;
}

header h1{
    font-size: 40px; 
    color: #f4f4f4;
    display: inline-block;
    position: relative;
    padding: 20px 20px 0 0;
    display: inline-block;
}
</style></head>


<header>
<a href="index.html">
    <img src="./branding.png" alt="technocrat logo" height="100px" width="100px"></a>
    <a href="index.html">
    <h1><span> Technocrat</span> Blog</h1></a>
</div></header>

How to center div vertically inside of absolutely positioned parent div

You can do it by using display:table; in parent div and display: table-cell; vertical-align: middle; in child div

_x000D_
_x000D_
<div style="display:table;">_x000D_
      <div style="text-align: left;  height: 56px;  background-color: pink; display: table-cell; vertical-align: middle;">_x000D_
          <div style="background-color: lightblue; ">test</div>_x000D_
      </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How to convert date in to yyyy-MM-dd Format?

You can't format the Date itself. You can only get the formatted result in String. Use SimpleDateFormat as mentioned by others.

Moreover, most of the getter methods in Date are deprecated.

How to set border on jPanel?

JPanel jPanel = new JPanel();

jPanel.setBorder(BorderFactory.createLineBorder(Color.black));

Here not only jPanel, you can add border to any Jcomponent

What's a quick way to comment/uncomment lines in Vim?

For those tasks I use most of the time block selection.

Put your cursor on the first # character, press CtrlV (or CtrlQ for gVim), and go down until the last commented line and press x, that will delete all the # characters vertically.

For commenting a block of text is almost the same:

  1. First, go to the first line you want to comment, press CtrlV. This will put the editor in the VISUAL BLOCK mode.
  2. Then using the arrow key and select until the last line
  3. Now press ShiftI, which will put the editor in INSERT mode and then press #. This will add a hash to the first line.
  4. Then press Esc (give it a second), and it will insert a # character on all other selected lines.

For the stripped-down version of vim shipped with debian/ubuntu by default, type : s/^/# in the third step instead (any remaining highlighting of the first character of each line can be removed with :nohl).

Here are two small screen recordings for visual reference.

Comment: Comment

Uncomment: Uncomment

How do I create a multiline Python string with inline variables?

This is what you want:

>>> string1 = "go"
>>> string2 = "now"
>>> string3 = "great"
>>> mystring = """
... I will {string1} there
... I will go {string2}
... {string3}
... """
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>, 'string3': 'great', '__package__': None, 'mystring': "\nI will {string1} there\nI will go {string2}\n{string3}\n", '__name__': '__main__', 'string2': 'now', '__doc__': None, 'string1': 'go'}
>>> print(mystring.format(**locals()))

I will go there
I will go now
great

jQuery Mobile Page refresh mechanism

Please take a good look here: http://jquerymobile.com/test/docs/api/methods.html

$.mobile.changePage() is to change from one page to another, and the parameter can be a url or a page object. ( only #result will also work )

$.mobile.page() isn't recommended anymore, please use .trigger( "create"), see also: JQuery Mobile .page() function causes infinite loop?

Important: Create vs. refresh: An important distinction

Note that there is an important difference between the create event and refresh method that some widgets have. The create event is suited for enhancing raw markup that contains one or more widgets. The refresh method that some widgets have should be used on existing (already enhanced) widgets that have been manipulated programmatically and need the UI be updated to match.

For example, if you had a page where you dynamically appended a new unordered list with data-role=listview attribute after page creation, triggering create on a parent element of that list would transform it into a listview styled widget. If more list items were then programmatically added, calling the listview’s refresh method would update just those new list items to the enhanced state and leave the existing list items untouched.

$.mobile.refresh() doesn't exist i guess

So what are you using for your results? A listview? Then you can update it by doing:

$('ul').listview('refresh');

Example: http://operationmobile.com/dont-forget-to-call-refresh-when-adding-items-to-your-jquery-mobile-list/

Otherwise you can do:

$('#result').live("pageinit", function(){ // or pageshow
    // your dom manipulations here
});

Add primary key to existing table

If you add primary key constraint

ALTER TABLE <TABLE NAME> ADD CONSTRAINT <CONSTRAINT NAME> PRIMARY KEY <COLUMNNAME>  

for example:

ALTER TABLE DEPT ADD CONSTRAINT PK_DEPT PRIMARY KEY (DEPTNO)

how to remove untracked files in Git?

Well, I had the similar issue. I had taken latest but there were some changes in the local due to which the merge was not happening to a particular file. The file was untracked and I did not want them so What I did was -

$ git checkout filepath/filename

filepath - The location from where I did the git bash. then when I took the latest the changes were available

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

How do I convert csv file to rdd

As of Spark 2.0, CSV can be read directly into a DataFrame.

If the data file does not have a header row, then it would be:

val df = spark.read.csv("file://path/to/data.csv")

That will load the data, but give each column generic names like _c0, _c1, etc.

If there are headers then adding .option("header", "true") will use the first row to define the columns in the DataFrame:

val df = spark.read
  .option("header", "true")
  .csv("file://path/to/data.csv")

For a concrete example, let's say you have a file with the contents:

user,topic,hits
om,scala,120
daniel,spark,80
3754978,spark,1

Then the following will get the total hits grouped by topic:

import org.apache.spark.sql.functions._
import spark.implicits._

val rawData = spark.read
  .option("header", "true")
  .csv("file://path/to/data.csv")

// specifies the query, but does not execute it
val grouped = rawData.groupBy($"topic").agg(sum($"hits))

// runs the query, pulling the data to the master node
// can fail if the amount of data is too much to fit 
// into the master node's memory!
val collected = grouped.collect

// runs the query, writing the result back out
// in this case, changing format to Parquet since that can
//   be nicer to work with in Spark
grouped.write.parquet("hdfs://some/output/directory/")

// runs the query, writing the result back out
// in this case, in CSV format with a header and 
// coalesced to a single file.  This is easier for human 
// consumption but usually much slower.
grouped.coalesce(1)
  .write
  .option("header", "true")
  .csv("hdfs://some/output/directory/")

What is the proper way to format a multi-line dict in Python?

Generally, you would not include the comma after the final entry, but Python will correct that for you.

ArrayList: how does the size increase?

static int getCapacity(ArrayList<?> list) throws Exception {
            Field dataField = ArrayList.class.getDeclaredField("elementData");
            dataField.setAccessible(true);
            return ((Object[]) dataField.get(list)).length;
    }

use the above method to check the size when the arraylist is being modified.

How to write a foreach in SQL Server?

Here is the one of the better solutions.

DECLARE @i int
            DECLARE @curren_val int
            DECLARE @numrows int
            create table #Practitioner (idx int IDENTITY(1,1), PractitionerId int)
            INSERT INTO #Practitioner (PractitionerId) values (10),(20),(30)
            SET @i = 1
            SET @numrows = (SELECT COUNT(*) FROM #Practitioner)
            IF @numrows > 0
            WHILE (@i <= (SELECT MAX(idx) FROM #Practitioner))
            BEGIN

                SET @curren_val = (SELECT PractitionerId FROM #Practitioner WHERE idx = @i)

                --Do something with Id here
                PRINT @curren_val
                SET @i = @i + 1
            END

Here i've add some values in the table beacuse, initially it is empty.

We can access or we can do anything in the body of the loop and we can access the idx by defining it inside the table definition.

              BEGIN
                SET @curren_val = (SELECT PractitionerId FROM #Practitioner WHERE idx = @i)

                --Do something with Id here

                PRINT @curren_val
                SET @i = @i + 1
            END

How to link an input button to a file select window?

You could use JavaScript and trigger the hidden file input when the button input has been clicked.

http://jsfiddle.net/gregorypratt/dhyzV/ - simple

http://jsfiddle.net/gregorypratt/dhyzV/1/ - fancier with a little JQuery

Or, you could style a div directly over the file input and set pointer-events in CSS to none to allow the click events to pass through to the file input that is "behind" the fancy div. This only works in certain browsers though; http://caniuse.com/pointer-events

Python script header

From the manpage for env (GNU coreutils 6.10):

env - run a program in a modified environment

In theory you could use env to reset the environment (removing many of the existing environment variables) or add additional environment variables in the script header. Practically speaking, the two versions you mentioned are identical. (Though others have mentioned a good point: specifying python through env lets you abstractly specify python without knowing its path.)

How to validate date with format "mm/dd/yyyy" in JavaScript?

  1. Javascript

    function validateDate(date) {
        try {
            new Date(date).toISOString();
            return true;
        } catch (e) { 
            return false; 
        }
    }
    
  2. JQuery

    $.fn.validateDate = function() {
        try {
            new Date($(this[0]).val()).toISOString();
            return true;
        } catch (e) { 
            return false; 
        }
    }
    

returns true for a valid date string.

How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?

This can be accomplished in two steps:

1: select the element you want to change by either tagname, id, class etc.

var element = document.getElementsByTagName('h2')[0];

  1. remove the style attribute

element.removeAttribute('style');

Redirect Windows cmd stdout and stderr to a single file

In a batch file (Windows 7 and above) I found this method most reliable

Call :logging >"C:\Temp\NAME_Your_Log_File.txt" 2>&1
:logging
TITLE "Logging Commands"
ECHO "Read this output in your log file"
ECHO ..
Prompt $_
COLOR 0F

Obviously, use whatever commands you want and the output will be directed to the text file. Using this method is reliable HOWEVER there is NO output on the screen.

Python virtualenv questions

After creating virtual environment copy the activate.bat file from Script folder of python and paste to it your environment and open cmd from your virtual environment and run activate.bat file.enter image description here

Get the week start date and week end date from week number

Below query will give data between start and end of current week starting from sunday to saturday

SELECT DOB FROM PROFILE_INFO WHERE DAY(DOB) BETWEEN
DAY( CURRENT_DATE() - (SELECT DAYOFWEEK(CURRENT_DATE())-1))
AND
DAY((CURRENT_DATE()+(7 - (SELECT DAYOFWEEK(CURRENT_DATE())) ) ))
AND
MONTH(DOB)=MONTH(CURRENT_DATE())

jQuery AJAX submit form

This is a simple reference:

// this is the id of the form
$("#idForm").submit(function(e) {

    e.preventDefault(); // avoid to execute the actual submit of the form.

    var form = $(this);
    var url = form.attr('action');
    
    $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    
});

Running command line silently with VbScript and getting output?

I have taken this and various other comments and created a bit more advanced function for running an application and getting the output.

Example to Call Function: Will output the DIR list of C:\ for Directories only. The output will be returned to the variable CommandResults as well as remain in C:\OUTPUT.TXT.

CommandResults = vFn_Sys_Run_CommandOutput("CMD.EXE /C DIR C:\ /AD",1,1,"C:\OUTPUT.TXT",0,1)

Function

Function vFn_Sys_Run_CommandOutput (Command, Wait, Show, OutToFile, DeleteOutput, NoQuotes)
'Run Command similar to the command prompt, for Wait use 1 or 0. Output returned and
'stored in a file.
'Command = The command line instruction you wish to run.
'Wait = 1/0; 1 will wait for the command to finish before continuing.
'Show = 1/0; 1 will show for the command window.
'OutToFile = The file you wish to have the output recorded to.
'DeleteOutput = 1/0; 1 deletes the output file. Output is still returned to variable.
'NoQuotes = 1/0; 1 will skip wrapping the command with quotes, some commands wont work
'                if you wrap them in quotes.
'----------------------------------------------------------------------------------------
  On Error Resume Next
  'On Error Goto 0
    Set f_objShell = CreateObject("Wscript.Shell")
    Set f_objFso = CreateObject("Scripting.FileSystemObject")
    Const ForReading = 1, ForWriting = 2, ForAppending = 8
      'VARIABLES
        If OutToFile = "" Then OutToFile = "TEMP.TXT"
        tCommand = Command
        If Left(Command,1)<>"""" And NoQuotes <> 1 Then tCommand = """" & Command & """"
        tOutToFile = OutToFile
        If Left(OutToFile,1)<>"""" Then tOutToFile = """" & OutToFile & """"
        If Wait = 1 Then tWait = True
        If Wait <> 1 Then tWait = False
        If Show = 1 Then tShow = 1
        If Show <> 1 Then tShow = 0
      'RUN PROGRAM
        f_objShell.Run tCommand & ">" & tOutToFile, tShow, tWait
      'READ OUTPUT FOR RETURN
        Set f_objFile = f_objFso.OpenTextFile(OutToFile, 1)
          tMyOutput = f_objFile.ReadAll
          f_objFile.Close
          Set f_objFile = Nothing
      'DELETE FILE AND FINISH FUNCTION
        If DeleteOutput = 1 Then
          Set f_objFile = f_objFso.GetFile(OutToFile)
            f_objFile.Delete
            Set f_objFile = Nothing
          End If
        vFn_Sys_Run_CommandOutput = tMyOutput
        If Err.Number <> 0 Then vFn_Sys_Run_CommandOutput = "<0>"
        Err.Clear
        On Error Goto 0
      Set f_objFile = Nothing
      Set f_objShell = Nothing
  End Function

SQL Error: ORA-00933: SQL command not properly ended

Not exactly the case of actual context of this question, but this exception can be reproduced by the next query:

update users set dismissal_reason='he can't and don't want' where userid=123

Single quotes in words can't and don't broke the string. In case string have only one inside quote e.g. 'he don't want' oracle throws more relevant quoted string not properly terminated error, but in case of two SQL command not properly ended is thrown.

Summary: check your query for double single quotes.

Set proxy through windows command line including login parameters

If you are using Microsoft windows environment then you can set a variable named HTTP_PROXY, FTP_PROXY, or HTTPS_PROXY depending on the requirement.

I have used following settings for allowing my commands at windows command prompt to use the browser proxy to access internet.

set HTTP_PROXY=http://proxy_userid:proxy_password@proxy_ip:proxy_port

The parameters on right must be replaced with actual values.

Once the variable HTTP_PROXY is set, all our subsequent commands executed at windows command prompt will be able to access internet through the proxy along with the authentication provided.

Additionally if you want to use ftp and https as well to use the same proxy then you may like to the following environment variables as well.

set FTP_PROXY=%HTTP_PROXY%

set HTTPS_PROXY=%HTTP_PROXY%

Format a datetime into a string with milliseconds

datetime
t = datetime.datetime.now()
ms = '%s.%i' % (t.strftime('%H:%M:%S'), t.microsecond/1000)
print(ms)
14:44:37.134

How do I set headers using python's urllib?

For multiple headers do as follow:

import urllib2
req = urllib2.Request('http://www.example.com/')
req.add_header('param1', '212212')
req.add_header('param2', '12345678')
req.add_header('other_param1', 'sample')
req.add_header('other_param2', 'sample1111')
req.add_header('and_any_other_parame', 'testttt')
resp = urllib2.urlopen(req)
content = resp.read()

How to define several include path in Makefile

You need to use -I with each directory. But you can still delimit the directories with whitespace if you use (GNU) make's foreach:

INC=$(DIR1) $(DIR2) ...
INC_PARAMS=$(foreach d, $(INC), -I$d)

Use grep --exclude/--include syntax to not grep through certain files

To ignore all binary results from grep

grep -Ri "pattern" * | awk '{if($1 != "Binary") print $0}'

The awk part will filter out all the Binary file foo matches lines

How to install a specific JDK on Mac OS X?

Check this awesome tool sdkman to manage your jdk and other jdk related tools with great ease!

e.g.

$sdk list java
$sdk install java <VERSION>

Java array assignment (multiple values)

Yes:

float[] values = {0.1f, 0.2f, 0.3f};

This syntax is only permissible in an initializer. You cannot use it in an assignment, where the following is the best you can do:

values = new float[3];

or

values = new float[] {0.1f, 0.2f, 0.3f};

Trying to find a reference in the language spec for this, but it's as unreadable as ever. Anyone else find one?

How to redirect stderr and stdout to different files in the same line in script?

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

Finding the position of bottom of a div with jquery

use this script to calculate end of div

$('#bottom').offset().top +$('#bottom').height()

How to convert signed to unsigned integer in python

just use abs for converting unsigned to signed in python

 a=-12
b=abs(a)
print(b)

Output: 12

String Resource new line /n not possible?

I just faced this issue. didn't work on TextView with constraint parameters. Adding android:lines="2" seems to fix this.