Programs & Examples On #Compiler bug

For questions about (suspected) incorrect behavior of a compiler. Use with the appropriate language tag and, where applicable, with the tag for the compiler in question.

unresolved external symbol __imp__fprintf and __imp____iob_func, SDL2

Microsoft has a special note on this (https://msdn.microsoft.com/en-us/library/bb531344.aspx#BK_CRT):

The printf and scanf family of functions are now defined inline.

The definitions of all of the printf and scanf functions have been moved inline into stdio.h, conio.h, and other CRT headers. This is a breaking change that leads to a linker error (LNK2019, unresolved external symbol) for any programs that declared these functions locally without including the appropriate CRT headers. If possible, you should update the code to include the CRT headers (that is, add #include ) and the inline functions, but if you do not want to modify your code to include these header files, an alternative solution is to add an additional library to your linker input, legacy_stdio_definitions.lib.

To add this library to your linker input in the IDE, open the context menu for the project node, choose Properties, then in the Project Properties dialog box, choose Linker, and edit the Linker Input to add legacy_stdio_definitions.lib to the semi-colon-separated list.

If your project links with static libraries that were compiled with a release of Visual C++ earlier than 2015, the linker might report an unresolved external symbol. These errors might reference internal stdio definitions for _iob, _iob_func, or related imports for certain stdio functions in the form of __imp_*. Microsoft recommends that you recompile all static libraries with the latest version of the Visual C++ compiler and libraries when you upgrade a project. If the library is a third-party library for which source is not available, you should either request an updated binary from the third party or encapsulate your usage of that library into a separate DLL that you compile with the older version of the Visual C++ compiler and libraries.

Wildcards in a Windows hosts file

While you can't add a wildcard like that, you could add the full list of sites that you need, at least for testing, that works well enough for me, in your hosts file, you just add:

127.0.0.1 site1.local
127.0.0.1 site2.local
127.0.0.1 site3.local
...

How to add `style=display:"block"` to an element using jQuery?

Depending on the purpose of setting the display property, you might want to take a look at

$("#yourElementID").show()

and

$("#yourElementID").hide()

PHP with MySQL 8.0+ error: The server requested authentication method unknown to the client

In my.cnf file check below 2 steps.

  • check this value -

    old_passwords=0;

    it should be 0.

  • check this also-

    [mysqld] default_authentication_plugin= mysql_native_password Another value to check is to make sure

    [mysqld] section should be like this.

How can I solve Exception in thread "main" java.lang.NullPointerException error

This is the problem

double a[] = null;

Since a is null, NullPointerException will arise every time you use it until you initialize it. So this:

a[i] = var;

will fail.

A possible solution would be initialize it when declaring it:

double a[] = new double[PUT_A_LENGTH_HERE]; //seems like this constant should be 7

IMO more important than solving this exception, is the fact that you should learn to read the stacktrace and understand what it says, so you could detect the problems and solve it.

java.lang.NullPointerException

This exception means there's a variable with null value being used. How to solve? Just make sure the variable is not null before being used.

at twoten.TwoTenB.(TwoTenB.java:29)

This line has two parts:

  • First, shows the class and method where the error was thrown. In this case, it was at <init> method in class TwoTenB declared in package twoten. When you encounter an error message with SomeClassName.<init>, means the error was thrown while creating a new instance of the class e.g. executing the constructor (in this case that seems to be the problem).
  • Secondly, shows the file and line number location where the error is thrown, which is between parenthesis. This way is easier to spot where the error arose. So you have to look into file TwoTenB.java, line number 29. This seems to be a[i] = var;.

From this line, other lines will be similar to tell you where the error arose. So when reading this:

at javapractice.JavaPractice.main(JavaPractice.java:32)

It means that you were trying to instantiate a TwoTenB object reference inside the main method of your class JavaPractice declared in javapractice package.

Generating a PDF file from React Components

You can use ReactPDF

Lets you convert a div into PDF with ease. You will need to match your existing markup to use ReactPDF markup, but it is worth it.

Send data from activity to fragment in Android

You can make a setter method in the fragment. Then in the Activity, when you reference to the fragment, you call the setter method and pass it the data from you Activity

How do you divide each element in a list by an int?

The way you tried first is actually directly possible with numpy:

import numpy
myArray = numpy.array([10,20,30,40,50,60,70,80,90])
myInt = 10
newArray = myArray/myInt

If you do such operations with long lists and especially in any sort of scientific computing project, I would really advise using numpy.

Maven plugins can not be found in IntelliJ

If problem persist, you can add manually the missing plugins files.

For example if maven-site-plugins is missing, go to https://mvnrepository.com/artifact/org.apache.maven.plugins/maven-site-plugin

Choice your version, and download files associated directly into your .m2 folder, in this example : C:\Users\ {USERNAME} .m2\repository\org\apache\maven\plugins\maven-site-plugin\ {VERSION}

In IntelliJ IDEA, open Maven sidebar, and reload (tooltip : Reimport All Maven projects)

How can I split a text file using PowerShell?

A word of warning about some of the existing answers - they will run very slow for very big files. For a 1.6 GB log file I gave up after a couple of hours, realising it would not finish before I returned to work the next day.

Two issues: the call to Add-Content opens, seeks and then closes the current destination file for every line in the source file. Reading a little of the source file each time and looking for the new lines will also slows things down, but my guess is that Add-Content is the main culprit.

The following variant produces slightly less pleasant output: it will split files in the middle of lines, but it splits my 1.6 GB log in less than a minute:

$from = "C:\temp\large_log.txt"
$rootName = "C:\temp\large_log_chunk"
$ext = "txt"
$upperBound = 100MB


$fromFile = [io.file]::OpenRead($from)
$buff = new-object byte[] $upperBound
$count = $idx = 0
try {
    do {
        "Reading $upperBound"
        $count = $fromFile.Read($buff, 0, $buff.Length)
        if ($count -gt 0) {
            $to = "{0}.{1}.{2}" -f ($rootName, $idx, $ext)
            $toFile = [io.file]::OpenWrite($to)
            try {
                "Writing $count to $to"
                $tofile.Write($buff, 0, $count)
            } finally {
                $tofile.Close()
            }
        }
        $idx ++
    } while ($count -gt 0)
}
finally {
    $fromFile.Close()
}

Spark java.lang.OutOfMemoryError: Java heap space

I suffered from this issue a lot when using dynamic resource allocation. I had thought it would utilize my cluster resources to best fit the application.

But the truth is the dynamic resource allocation doesn't set the driver memory and keeps it to its default value, which is 1G.

I resolved this issue by setting spark.driver.memory to a number that suits my driver's memory (for 32GB ram I set it to 18G).

You can set it using spark submit command as follows:

spark-submit --conf spark.driver.memory=18g

Very important note, this property will not be taken into consideration if you set it from code, according to Spark Documentation - Dynamically Loading Spark Properties:

Spark properties mainly can be divided into two kinds: one is related to deploy, like “spark.driver.memory”, “spark.executor.instances”, this kind of properties may not be affected when setting programmatically through SparkConf in runtime, or the behavior is depending on which cluster manager and deploy mode you choose, so it would be suggested to set through configuration file or spark-submit command line options; another is mainly related to Spark runtime control, like “spark.task.maxFailures”, this kind of properties can be set in either way.

Android-java- How to sort a list of objects by a certain value within the object

It's very easy for Kotlin!

listToBeSorted.sortBy { it.distance }

How do I find the difference between two values without knowing which is larger?

abs function is definitely not what you need as it is not calculating the distance. Try abs (-25+15) to see that it's not working. A distance between the numbers is 40 but the output will be 10. Because it's doing the math and then removing "minus" in front. I am using this custom function:


def distance(a, b):
    if (a < 0) and (b < 0) or (a > 0) and (b > 0):
        return abs( abs(a) - abs(b) )
    if (a < 0) and (b > 0) or (a > 0) and (b < 0):
        return abs( abs(a) + abs(b) )

print distance(-25, -15) print distance(25, -15) print distance(-25, 15) print distance(25, 15)

HTML 5 Favicon - Support?

No, not all browsers support the sizes attribute:

Note that some platforms define specific sizes:

How do I import a .dmp file into Oracle?

imp system/system-password@SID file=directory-you-selected\FILE.dmp log=log-dir\oracle_load.log fromuser=infodba touser=infodba commit=Y

Set Focus After Last Character in Text Box

Chris Coyier has a mini jQuery plugin for this which works perfectly well: http://css-tricks.com/snippets/jquery/move-cursor-to-end-of-textarea-or-input/

It uses setSelectionRange if supported, else has a solid fallback.

jQuery.fn.putCursorAtEnd = function() {
  return this.each(function() {
    $(this).focus()
    // If this function exists...
    if (this.setSelectionRange) {
      // ... then use it (Doesn't work in IE)
      // Double the length because Opera is inconsistent about whether a carriage return is one character or two. Sigh.
      var len = $(this).val().length * 2;
      this.setSelectionRange(len, len);
    } else {
      // ... otherwise replace the contents with itself
      // (Doesn't work in Google Chrome)
      $(this).val($(this).val());
    }
    // Scroll to the bottom, in case we're in a tall textarea
    // (Necessary for Firefox and Google Chrome)
    this.scrollTop = 999999;
  });
};

Then you can just do:

input.putCursorAtEnd();

Select All distinct values in a column using LINQ

To have unique Categories:

var uniqueCategories =  repository.GetAllProducts()
                                  .Select(p=>p.Category)
                                  .Distinct();

Passing a variable to a powershell script via command line

Here's a good tutorial on Powershell params:

PowerShell ABC's - P is for Parameters

Basically, you should use a param statement on the first line of the script

param([type]$p1 = , [type]$p2 = , ...)

or use the $args built-in variable, which is auto-populated with all of the args.

Is a URL allowed to contain a space?

Urls should not have spaces in them. If you need to address one that does, use its encoded value of %20

Eclipse executable launcher error: Unable to locate companion shared library

I had this issue on Linux (CentOS 7 64 bit) with 32-bit Eclipse Neon and 32-bit JRE 8. Non of the answers here or in similar questions were helpful, so I thought it can help someone.

Equinox launcher (eclipse executable) is reading the plugins/ directory and then searches for eclipse_xxxx.so/dll in org.eclipse.equinox.launcher.<os>_<version>/. Typically, the problem is in eclipse.ini pointing to the wrong version of Equinox launcher plugin. But, if the file system uses 64-bit inodes, such as XFS and one of the files gets inode number above 4294967296, then the launcher fails reading the plugins/ directory and this error message pops up. Use ls -li <eclipse>/plugins/ to check the inode numbers.

In my case, moving to another mount with 32-bit inodes resolved the problem.

See: http://www.tcm.phy.cam.ac.uk/sw/inodes64.html

Is there a way to make Firefox ignore invalid ssl-certificates?

Instead of using invalid/outdated SSL certificates, why not use self-signed SSL certificates? Then you can add an exception in Firefox for just that site.

Create, read, and erase cookies with jQuery

Use jquery cookie plugin, the link as working today: https://github.com/js-cookie/js-cookie

Using SUMIFS with multiple AND OR conditions

You can use DSUM, which will be more flexible. Like if you want to change the name of Salesman or the Quote Month, you need not change the formula, but only some criteria cells. Please see the link below for details...Even the criteria can be formula to copied from other sheets

http://office.microsoft.com/en-us/excel-help/dsum-function-HP010342460.aspx?CTT=1

Inserting values to SQLite table in Android

Since you are new to Android development you may not know about Content Providers, which are database abstractions. They may not be the right thing for your project, but you should check them out: http://developer.android.com/guide/topics/providers/content-providers.html

How to cast int to enum in C++?

Your code

enum Test
{
    A, B
}

int a = 1;

Solution

Test castEnum = static_cast<Test>(a);

How to convert a pymongo.cursor.Cursor into a dict?

Easy

import pymongo
conn = pymongo.MongoClient()
db = conn.test #test is my database
col = db.spam #Here spam is my collection
array = list(col.find())

print array

There you go

How does Tomcat locate the webapps directory?

I'm using Tomcat through XAMPP which might have been the cause of this problem. When I changed appBase="C:/Java Project/", for example, I kept getting "This localhost page can't be found" in the browser.

I had to add a folder called ROOT inside the Java Project folder and then it worked. Any files you're working on have to be inside this ROOT folder but you need to leave appBase="C:/Java Project/" as changing it to appBase="C:/Java Project/ROOT" will cause "This localhost page can't be found" to be displayed again.

Maybe needing the ROOT folder is obvious to more experienced Java developers but it wasn't for me so hopefully this helps anyone else encountering the same problem.

URL encoding in Android

You don't encode the entire URL, only parts of it that come from "unreliable sources".

  • Java:

    String query = URLEncoder.encode("apples oranges", "utf-8");
    String url = "http://stackoverflow.com/search?q=" + query;
    
  • Kotlin:

    val query: String = URLEncoder.encode("apples oranges", "utf-8")
    val url = "http://stackoverflow.com/search?q=$query"
    

Alternatively, you can use Strings.urlEncode(String str) of DroidParts that doesn't throw checked exceptions.

Or use something like

String uri = Uri.parse("http://...")
                .buildUpon()
                .appendQueryParameter("key", "val")
                .build().toString();

<strong> vs. font-weight:bold & <em> vs. font-style:italic

The <em> element - from W3C (HTML5 reference)

YES! There is a clear difference.

The <em> element represents stress emphasis of its contents. The level of emphasis that a particular piece of content has is given by its number of ancestor <em> elements.

<strong>  =  important content
<em>      =  stress emphasis of its contents

The placement of emphasis changes the meaning of the sentence. The element thus forms an integral part of the content. The precise way in which emphasis is used in this way depends on the language.

Note!

  1. The <em> element also isnt intended to convey importance; for that purpose, the <strong> element is more appropriate.

  2. The <em> element isn't a generic "italics" element. Sometimes, text is intended to stand out from the rest of the paragraph, as if it was in a different mood or voice. For this, the i element is more appropriate.

Reference (examples): See W3C Reference

SQL Server 100% CPU Utilization - One database shows high CPU usage than others

According to this article on sqlserverstudymaterial;

Remember that "%Privileged time" is not based on 100%.It is based on number of processors.If you see 200 for sqlserver.exe and the system has 8 CPU then CPU consumed by sqlserver.exe is 200 out of 800 (only 25%).

If "% Privileged Time" value is more than 30% then it's generally caused by faulty drivers or anti-virus software. In such situations make sure the BIOS and filter drives are up to date and then try disabling the anti-virus software temporarily to see the change.

If "% User Time" is high then there is something consuming of SQL Server. There are several known patterns which can be caused high CPU for processes running in SQL Server including

How can I move a tag on a git branch to a different commit?

Alias to move one tag to a different commit.

In your sample, to move commit with hash e2ea1639 do: git tagm v0.1 e2ea1639.

For pushed tags, use git tagmp v0.1 e2ea1639.

Both alias keeps you original date and message. If you use git tag -d you lost your original message.

Save them on your .gitconfig file

# Return date of tag. (To use in another alias)
tag-date = "!git show $1 | awk '{ if ($1 == \"Date:\") { print substr($0, index($0,$3)) }}' | tail -2 | head -1 #"

# Show tag message
tag-message = "!git show $1 | awk -v capture=0 '{ if(capture) message=message\"\\n\"$0}; BEGIN {message=\"\"}; { if ($1 == \"Date:\" && length(message)==0 ) {capture=1}; if ($1 == \"commit\" ) {capture=0}  }; END { print message }' | sed '$ d' | cat -s #"

### Move tag. Use: git tagm <tagname> <newcommit> 
tagm = "!GIT_TAG_MESSAGE=$(git tag-message $1) && GIT_COMMITTER_DATE=$(git tag-date $1) && git tag-message $1 && git tag -d $1 && git tag -a $1 $2 -m \"$GIT_TAG_MESSAGE\" #"

### Move pushed tag. Use: git tagmp <tagname> <newcommit> 
tagmp = "!git tagm $1 $2 && git push --delete origin $1 && git push origin $1 #"

Check box size change with CSS

You might want to do this.

input[type=checkbox] {

 -ms-transform: scale(2); /* IE */
 -moz-transform: scale(2); /* FF */
 -webkit-transform: scale(2); /* Safari and Chrome */
 -o-transform: scale(2); /* Opera */
  padding: 10px;
}

How to add not null constraint to existing column in MySQL

Just use an ALTER TABLE... MODIFY... query and add NOT NULL into your existing column definition. For example:

ALTER TABLE Person MODIFY P_Id INT(11) NOT NULL;

A word of caution: you need to specify the full column definition again when using a MODIFY query. If your column has, for example, a DEFAULT value, or a column comment, you need to specify it in the MODIFY statement along with the data type and the NOT NULL, or it will be lost. The safest practice to guard against such mishaps is to copy the column definition from the output of a SHOW CREATE TABLE YourTable query, modify it to include the NOT NULL constraint, and paste it into your ALTER TABLE... MODIFY... query.

IO Error: The Network Adapter could not establish the connection

Another thing you might want to check that the listener.ora file matches the way you are trying to connect to the DB. If you were connecting via a localhost reference and your listener.ora file got changed from:

HOST = localhost

to

HOST = 192.168.XX.XX

then this can cause the error that you had unless you update your hosts file to accommodate for this. Someone might have made this change to allow for remote connections to the DB from other machines.

WPF: simple TextBox data binding

Just for future needs.

In Visual Studio 2013 with .NET Framework 4.5, for a window property, try adding ElementName=window to make it work.

<Grid Name="myGrid" Height="437.274">
  <TextBox Text="{Binding Path=Name2, ElementName=window}"/>
</Grid>

This IP, site or mobile application is not authorized to use this API key

I had the same issue and I found this.

On the url, it requires the server key in the end and not the api key for the app.

So Basically, you just add the server key in the end of the URL like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=yourlatitude,yourlongitude&radius=5000&sensor=true&key=SERVERKEY

Now, to obtain the server key, just follow these steps:

1) Go to Developer Console https://code.google.com/apis/console/

2) In the Credentials, under Public API Access, Create New key

3) Select the server key from the option.

4) Enter your IP Address on the field and if you have more ip addresses, you can just add on every single line.NOTE: Enter the IP Address only when you want to use it for your testing purpose. Else leave the IP Address section blank.

5) Once you are done, click create and your new Server Key will be generated and you can then add that server key to your URL.

Last thing is that, instead of putting the sensor=true in the middle of the URL, you can add it in the end like this:

https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=yourlatitude,yourlongitude&radius=5000&key=SERVERKEY&sensor=true

This will definitely solve the issue and just remember to use the server key for Places API.

EDIT

I believe the web URL has changed in the past years. You can access developers console from here now - https://console.developers.google.com/apis/dashboard

  • Navigate to developers console - https://console.developers.google.com/ or use the link from details to navigate directly to API dashboard.
  • Under developer console, find Label from the left navigation panel
  • Select project
  • Choose Credentials from the left Navigation panel
  • You could create credentials type from the Top nav bar as required.

Hope this answer will help you and other viewers. Good Luck .. :)

Confirm postback OnClientClick button ASP.NET

try this : OnClientClick="return confirm('Are you sure ?');" Also set : CausesValidation="False"

How to refresh or show immediately in datagridview after inserting?

In the form designer add a new timer using the toolbox. In properties set "Enabled" equal to "True".

enter image description here

The set the DataGridView to equal your new data in the timer

enter image description here

What is the difference between WCF and WPF?

WCF = Windows Communication Foundation is used to build service-oriented applications. WPF = Windows Presentation Foundation is used to write platform-independent applications.

onMeasure custom view explanation

If you don't need to change something onMeasure - there's absolutely no need for you to override it.

Devunwired code (the selected and most voted answer here) is almost identical to what the SDK implementation already does for you (and I checked - it had done that since 2009).

You can check the onMeasure method here :

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),
            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));
}

public static int getDefaultSize(int size, int measureSpec) {
    int result = size;
    int specMode = MeasureSpec.getMode(measureSpec);
    int specSize = MeasureSpec.getSize(measureSpec);

    switch (specMode) {
    case MeasureSpec.UNSPECIFIED:
        result = size;
        break;
    case MeasureSpec.AT_MOST:
    case MeasureSpec.EXACTLY:
        result = specSize;
        break;
    }
    return result;
}

Overriding SDK code to be replaced with the exact same code makes no sense.

This official doc's piece that claims "the default onMeasure() will always set a size of 100x100" - is wrong.

Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1

To make it clear, in addition to @SLaks' answer, that meant you need to change this line :

List<RootObject> datalist = JsonConvert.DeserializeObject<List<RootObject>>(jsonstring);

to something like this :

RootObject datalist = JsonConvert.DeserializeObject<RootObject>(jsonstring);

'heroku' does not appear to be a git repository

First, make sure you're logged into heroku:

heroku login 

Enter your credentials.

It's common to get this error when using a cloned git repo onto a new machine. Even if your heroku credentials are already on the machine, there is no link between the cloned repo and heroku locally yet. To do this, cd into the root dir of the cloned repo and run

heroku git:remote -a yourapp

Chrome DevTools Devices does not detect device when plugged in

Samsung Note 8 User here - all i had to do was

  1. Enable USB Debugging on the phone.
  2. Install and run the "ADB and Fastboot" tool
  3. Input command adb devices in the adb prompt.
  4. Go to chrome://inspect/#devices and the device shows up.

After that i got a message on my phone and chrome recognized the phone.

How do I convert struct System.Byte byte[] to a System.IO.Stream object in C#?

The easiest way to convert a byte array to a stream is using the MemoryStream class:

Stream stream = new MemoryStream(byteArray);

Error: Failed to lookup view in Express

I had the same issue and could fix it with the solution from dougwilson: from Apr 5, 2017, Github.

  1. I changed the filename from index.js to index.pug
  2. Then used in the '/' route: res.render('index.pug') - instead of res.render('index')
  3. Set environment variable: DEBUG=express:view Now it works like a charm.

How to fill a datatable with List<T>

Just in case you have a nullable property in your class object:

private static DataTable ConvertToDatatable<T>(List<T> data)
{
    PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T));
    DataTable table = new DataTable();
    for (int i = 0; i < props.Count; i++)
    {
        PropertyDescriptor prop = props[i];
        if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
            table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]); 
        else
            table.Columns.Add(prop.Name, prop.PropertyType);
    }

    object[] values = new object[props.Count];
    foreach (T item in data)
    {
        for (int i = 0; i < values.Length; i++)
        {
            values[i] = props[i].GetValue(item);
        }
        table.Rows.Add(values);
    }
    return table;
 }

MySQL Database won't start in XAMPP Manager-osx

Just Click on Managed Servers Tab in XAMPP MANAGER , Now select MySQL Database, Click on configure on right side.

Change port from 3306 to 3307 and it will work.

Is there a list of Pytz Timezones?

Don't create your own list - pytz has a built-in set:

import pytz
set(pytz.all_timezones_set)  
>>> {'Europe/Vienna', 'America/New_York', 'America/Argentina/Salta',..}

You can then apply a timezone:

import datetime
tz = pytz.timezone('Pacific/Johnston')
ct = datetime.datetime.now(tz=tz)
>>> ct.isoformat()
2017-01-13T11:29:22.601991-05:00

Or if you already have a datetime object that is TZ aware (not naive):

# This timestamp is in UTC
my_ct = datetime.datetime.now(tz=pytz.UTC)

# Now convert it to another timezone
new_ct = my_ct.astimezone(tz)
>>> new_ct.isoformat()
2017-01-13T11:29:22.601991-05:00

Convert float to std::string in C++

If you're worried about performance, check out the Boost::lexical_cast library.

Getting TypeError: __init__() missing 1 required positional argument: 'on_delete' when trying to add parent table after child table with entries

Here are available options if it helps anyone for on_delete

CASCADE, DO_NOTHING, PROTECT, SET, SET_DEFAULT, SET_NULL

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Xcode 12

Removing VALID_ARCH from Build settings under User-Defined group work for me.

enter image description here

Is there any way to specify a suggested filename when using data: URI?

you can add a download attribute to the anchor element.

sample:

<a download="abcd.cer"
    href="data:application/stream;base64,MIIDhTC......">down</a>

How to create global variables accessible in all views using Express / Node.JS?

For Express 4.0 I found that using application level variables works a little differently & Cory's answer did not work for me.

From the docs: http://expressjs.com/en/api.html#app.locals

I found that you could declare a global variable for the app in

app.locals

e.g

app.locals.baseUrl = "http://www.google.com"

And then in your application you can access these variables & in your express middleware you can access them in the req object as

req.app.locals.baseUrl

e.g.

console.log(req.app.locals.baseUrl)
//prints out http://www.google.com

Set port for php artisan.php serve

Andreas' answer above was helpful in solving my problem of how to test artisan on port 80. Port 80 can be specified like the other port numbers, but regular users do not have permissions to run anything on that port.

Drop a little common sense on there and you end up with this for Linux:

sudo php artisan serve --port=80

This will allow you to test on localhost without specifying the port in your browser. You can also use this to set up a temporary demo, as I have done.

Keep in mind, however, that PHP's built in server is not designed for production. Use nginx/Apache for production.

Convert char to int in C#

char c = '1';
int i = (int)(c-'0');

and you can create a static method out of it:

static int ToInt(this char c)
{
    return (int)(c - '0');
}

Updating a dataframe column in spark

Commonly when updating a column, we want to map an old value to a new value. Here's a way to do that in pyspark without UDF's:

# update df[update_col], mapping old_value --> new_value
from pyspark.sql import functions as F
df = df.withColumn(update_col,
    F.when(df[update_col]==old_value,new_value).
    otherwise(df[update_col])).

What is the proper way to re-attach detached objects in Hibernate?

Entity states

JPA defines the following entity states:

New (Transient)

A newly created object that hasn’t ever been associated with a Hibernate Session (a.k.a Persistence Context) and is not mapped to any database table row is considered to be in the New (Transient) state.

To become persisted we need to either explicitly call the EntityManager#persist method or make use of the transitive persistence mechanism.

Persistent (Managed)

A persistent entity has been associated with a database table row and it’s being managed by the currently running Persistence Context. Any change made to such an entity is going to be detected and propagated to the database (during the Session flush-time).

With Hibernate, we no longer have to execute INSERT/UPDATE/DELETE statements. Hibernate employs a transactional write-behind working style and changes are synchronized at the very last responsible moment, during the current Session flush-time.

Detached

Once the currently running Persistence Context is closed all the previously managed entities become detached. Successive changes will no longer be tracked and no automatic database synchronization is going to happen.

Entity state transitions

You can change the entity state using various methods defined by the EntityManager interface.

To understand the JPA entity state transitions better, consider the following diagram:

JPA entity state transitions

When using JPA, to reassociate a detached entity to an active EntityManager, you can use the merge operation.

When using the native Hibernate API, apart from merge, you can reattach a detached entity to an active Hibernate Sessionusing the update methods, as demonstrated by the following diagram:

Hibernate entity state transitions

Merging a detached entity

The merge is going to copy the detached entity state (source) to a managed entity instance (destination).

Consider we have persisted the following Book entity, and now the entity is detached as the EntityManager that was used to persist the entity got closed:

Book _book = doInJPA(entityManager -> {
    Book book = new Book()
    .setIsbn("978-9730228236")
    .setTitle("High-Performance Java Persistence")
    .setAuthor("Vlad Mihalcea");
 
    entityManager.persist(book);
 
    return book;
});

While the entity is in the detached state, we modify it as follows:

_book.setTitle(
    "High-Performance Java Persistence, 2nd edition"
);

Now, we want to propagate the changes to the database, so we can call the merge method:

doInJPA(entityManager -> {
    Book book = entityManager.merge(_book);
 
    LOGGER.info("Merging the Book entity");
 
    assertFalse(book == _book);
});

And Hibernate is going to execute the following SQL statements:

SELECT
    b.id,
    b.author AS author2_0_,
    b.isbn AS isbn3_0_,
    b.title AS title4_0_
FROM
    book b
WHERE
    b.id = 1
 
-- Merging the Book entity
 
UPDATE
    book
SET
    author = 'Vlad Mihalcea',
    isbn = '978-9730228236',
    title = 'High-Performance Java Persistence, 2nd edition'
WHERE
    id = 1

If the merging entity has no equivalent in the current EntityManager, a fresh entity snapshot will be fetched from the database.

Once there is a managed entity, JPA copies the state of the detached entity onto the one that is currently managed, and during the Persistence Context flush, an UPDATE will be generated if the dirty checking mechanism finds that the managed entity has changed.

So, when using merge, the detached object instance will continue to remain detached even after the merge operation.

Reattaching a detached entity

Hibernate, but not JPA supports reattaching through the update method.

A Hibernate Session can only associate one entity object for a given database row. This is because the Persistence Context acts as an in-memory cache (first level cache) and only one value (entity) is associated with a given key (entity type and database identifier).

An entity can be reattached only if there is no other JVM object (matching the same database row) already associated with the current Hibernate Session.

Considering we have persisted the Book entity and that we modified it when the Book entity was in the detached state:

Book _book = doInJPA(entityManager -> {
    Book book = new Book()
    .setIsbn("978-9730228236")
    .setTitle("High-Performance Java Persistence")
    .setAuthor("Vlad Mihalcea");
 
    entityManager.persist(book);
 
    return book;
});
      
_book.setTitle(
    "High-Performance Java Persistence, 2nd edition"
);

We can reattach the detached entity like this:

doInJPA(entityManager -> {
    Session session = entityManager.unwrap(Session.class);
 
    session.update(_book);
 
    LOGGER.info("Updating the Book entity");
});

And Hibernate will execute the following SQL statement:

-- Updating the Book entity
 
UPDATE
    book
SET
    author = 'Vlad Mihalcea',
    isbn = '978-9730228236',
    title = 'High-Performance Java Persistence, 2nd edition'
WHERE
    id = 1

The update method requires you to unwrap the EntityManager to a Hibernate Session.

Unlike merge, the provided detached entity is going to be reassociated with the current Persistence Context and an UPDATE is scheduled during flush whether the entity has modified or not.

To prevent this, you can use the @SelectBeforeUpdate Hibernate annotation which will trigger a SELECT statement that fetched loaded state which is then used by the dirty checking mechanism.

@Entity(name = "Book")
@Table(name = "book")
@SelectBeforeUpdate
public class Book {
 
    //Code omitted for brevity
}

Beware of the NonUniqueObjectException

One problem that can occur with update is if the Persistence Context already contains an entity reference with the same id and of the same type as in the following example:

Book _book = doInJPA(entityManager -> {
    Book book = new Book()
    .setIsbn("978-9730228236")
    .setTitle("High-Performance Java Persistence")
    .setAuthor("Vlad Mihalcea");
 
    Session session = entityManager.unwrap(Session.class);
    session.saveOrUpdate(book);
 
    return book;
});
 
_book.setTitle(
    "High-Performance Java Persistence, 2nd edition"
);
 
try {
    doInJPA(entityManager -> {
        Book book = entityManager.find(
            Book.class,
            _book.getId()
        );
 
        Session session = entityManager.unwrap(Session.class);
        session.saveOrUpdate(_book);
    });
} catch (NonUniqueObjectException e) {
    LOGGER.error(
        "The Persistence Context cannot hold " +
        "two representations of the same entity",
        e
    );
}

Now, when executing the test case above, Hibernate is going to throw a NonUniqueObjectException because the second EntityManager already contains a Book entity with the same identifier as the one we pass to update, and the Persistence Context cannot hold two representations of the same entity.

org.hibernate.NonUniqueObjectException:
    A different object with the same identifier value was already associated with the session : [com.vladmihalcea.book.hpjp.hibernate.pc.Book#1]
    at org.hibernate.engine.internal.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:651)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:227)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:92)
    at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
    at org.hibernate.internal.SessionImpl.fireSaveOrUpdate(SessionImpl.java:682)
    at org.hibernate.internal.SessionImpl.saveOrUpdate(SessionImpl.java:674)

Conclusion

The merge method is to be preferred if you are using optimistic locking as it allows you to prevent lost updates.

The update is good for batch updates as it can prevent the additional SELECT statement generated by the merge operation, therefore reducing the batch update execution time.

What is the difference between state and props in React?

You can understand it best by relating it to Plain JS functions.

Simply put,

State is the local state of the component which cannot be accessed and modified outside of the component. It's equivalent to local variables in a function.

Plain JS Function

const DummyFunction = () => {
  let name = 'Manoj';
  console.log(`Hey ${name}`)
}

React Component

class DummyComponent extends React.Component {
  state = {
    name: 'Manoj'
  }
  render() {
    return <div>Hello {this.state.name}</div>;
  }

Props, on the other hand, make components reusable by giving components the ability to receive data from their parent component in the form of props. They are equivalent to function parameters.

Plain JS Function

const DummyFunction = (name) => {
  console.log(`Hey ${name}`)
}

// when using the function
DummyFunction('Manoj');
DummyFunction('Ajay');

React Component

class DummyComponent extends React.Component {
  render() {
    return <div>Hello {this.props.name}</div>;
  }

}

// when using the component
<DummyComponent name="Manoj" />
<DummyComponent name="Ajay" />

Credits: Manoj Singh Negi

Article Link: React State vs Props explained

How to add a button dynamically in Android?

try this

private void createLayoutDynamically(int n) {

    for (int i = 0; i < n; i++) {
        Button myButton = new Button(this);
        myButton.setText("Button :"+i);
        myButton.setId(i);
        final int id_ = myButton.getId();

        LinearLayout layout = (LinearLayout) findViewById(R.id.myDynamicLayout);
        layout.addView(myButton);

        myButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                Toast.makeText(DynamicLayout.this,
                        "Button clicked index = " + id_, Toast.LENGTH_SHORT)
                        .show();
            }
        });
    }

Set background color of WPF Textbox in C# code

You can use hex colors:

your_contorl.Color = DirectCast(ColorConverter.ConvertFromString("#D8E0A627"), Color)

Parsing a pcap file in python

You might want to start with scapy.

Why is it said that "HTTP is a stateless protocol"?

From Wikipedia:

HTTP is a stateless protocol. A stateless protocol does not require the server to retain information or status about each user for the duration of multiple requests.

But some web applications may have to track the user's progress from page to page, for example when a web server is required to customize the content of a web page for a user. Solutions for these cases include:

  • the use of HTTP cookies.
  • server side sessions,
  • hidden variables (when the current page contains a form), and
  • URL-rewriting using URI-encoded parameters, e.g., /index.php?session_id=some_unique_session_code.

What makes the protocol stateless is that the server is not required to track state over multiple requests, not that it cannot do so if it wants to. This simplifies the contract between client and server, and in many cases (for instance serving up static data over a CDN) minimizes the amount of data that needs to be transferred. If servers were required to maintain the state of clients' visits the structure of issuing and responding to requests would be more complex. As it is, the simplicity of the model is one of its greatest features.

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

Webpack is a bundler. Like Browserfy it looks in the codebase for module requests (require or import) and resolves them recursively. What is more, you can configure Webpack to resolve not just JavaScript-like modules, but CSS, images, HTML, literally everything. What especially makes me excited about Webpack, you can combine both compiled and dynamically loaded modules in the same app. Thus one get a real performance boost, especially over HTTP/1.x. How exactly you you do it I described with examples here http://dsheiko.com/weblog/state-of-javascript-modules-2017/ As an alternative for bundler one can think of Rollup.js (https://rollupjs.org/), which optimizes the code during compilation, but stripping all the found unused chunks.

For AMD, instead of RequireJS one can go with native ES2016 module system, but loaded with System.js (https://github.com/systemjs/systemjs)

Besides, I would point that npm is often used as an automating tool like grunt or gulp. Check out https://docs.npmjs.com/misc/scripts. I personally go now with npm scripts only avoiding other automation tools, though in past I was very much into grunt. With other tools you have to rely on countless plugins for packages, that often are not good written and not being actively maintained. npm knows its packages, so you call to any of locally installed packages by name like:

{
  "scripts": {
    "start": "npm http-server"
  },
  "devDependencies": {
    "http-server": "^0.10.0"
  }
}

Actually you as a rule do not need any plugin if the package supports CLI.

Git stash pop- needs merge, unable to refresh index

If anyone is having this issue outside of a merge/conflict/action, then it could be the git lock file for your project causing the issue.

git reset
     fatal: Unable to create '/PATH_TO_PROJECT/.git/index.lock': File exists.
rm -f /PATH_TO_PROJECT/.git/index.lock
git reset
git stash pop

Remove excess whitespace from within a string

There are security flaws to using preg_replace(), if you get the payload from user input [or other untrusted sources]. PHP executes the regular expression with eval(). If the incoming string isn't properly sanitized, your application risks being subjected to code injection.

In my own application, instead of bothering sanitizing the input (and as I only deal with short strings), I instead made a slightly more processor intensive function, though which is secure, since it doesn't eval() anything.

function secureRip(string $str): string { /* Rips all whitespace securely. */
  $arr = str_split($str, 1);
  $retStr = '';
  foreach ($arr as $char) {
    $retStr .= trim($char);
  }
  return $retStr;
}

Sorting object property by values

This could be a simple way to handle it as a real ordered object. Not sure how slow it is. also might be better with a while loop.

Object.sortByKeys = function(myObj){
  var keys = Object.keys(myObj)
  keys.sort()
  var sortedObject = Object()
  for(i in keys){
    key = keys[i]
    sortedObject[key]=myObj[key]
   }

  return sortedObject

}

And then I found this invert function from: http://nelsonwells.net/2011/10/swap-object-key-and-values-in-javascript/

Object.invert = function (obj) {

  var new_obj = {};

  for (var prop in obj) {
    if(obj.hasOwnProperty(prop)) {
      new_obj[obj[prop]] = prop;
    }
  }

  return new_obj;
};

So

var list = {"you": 100, "me": 75, "foo": 116, "bar": 15};
var invertedList = Object.invert(list)
var invertedOrderedList = Object.sortByKeys(invertedList)
var orderedList = Object.invert(invertedOrderedList)

Get key and value of object in JavaScript?

$.each(top_brands, function(index, el) {
  for (var key in el) {
    if (el.hasOwnProperty(key)) {
         brand_options.append($("<option />").val(key).text(key+ " "  + el[key]));
    }
  }
});

But if your data structure is var top_brands = {'Adidas': 100, 'Nike': 50};, then thing will be much more simple.

for (var key in top_brands) {
  if (top_brands.hasOwnProperty(key)) {
       brand_options.append($("<option />").val(key).text(key+ " "  + el[key]));
  }
}

Or use the jquery each:

$.each(top_brands, function(key, value) {
    brand_options.append($("<option />").val(key).text(key + " "  + value));
});

Creating Threads in python

Python 3 has the facility of Launching parallel tasks. This makes our work easier.

It has for thread pooling and Process pooling.

The following gives an insight:

ThreadPoolExecutor Example

import concurrent.futures
import urllib.request

URLS = ['http://www.foxnews.com/',
        'http://www.cnn.com/',
        'http://europe.wsj.com/',
        'http://www.bbc.co.uk/',
        'http://some-made-up-domain.com/']

# Retrieve a single page and report the URL and contents
def load_url(url, timeout):
    with urllib.request.urlopen(url, timeout=timeout) as conn:
        return conn.read()

# We can use a with statement to ensure threads are cleaned up promptly
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    # Start the load operations and mark each future with its URL
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS}
    for future in concurrent.futures.as_completed(future_to_url):
        url = future_to_url[future]
        try:
            data = future.result()
        except Exception as exc:
            print('%r generated an exception: %s' % (url, exc))
        else:
            print('%r page is %d bytes' % (url, len(data)))

Another Example

import concurrent.futures
import math

PRIMES = [
    112272535095293,
    112582705942171,
    112272535095293,
    115280095190773,
    115797848077099,
    1099726899285419]

def is_prime(n):
    if n % 2 == 0:
        return False

    sqrt_n = int(math.floor(math.sqrt(n)))
    for i in range(3, sqrt_n + 1, 2):
        if n % i == 0:
            return False
    return True

def main():
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        for number, prime in zip(PRIMES, executor.map(is_prime, PRIMES)):
            print('%d is prime: %s' % (number, prime))

if __name__ == '__main__':
    main()

WP -- Get posts by category?

Check here : http://codex.wordpress.org/Template_Tags/get_posts

Note: The category parameter needs to be the ID of the category, and not the category name.

How to create a new component in Angular 4 using CLI

You should be in the src/app folder of your angular-cli project on command line. For example:

D:\angular2-cli\first-app\src\app> ng generate component test

Only then it will generate your component.

PowerShell : retrieve JSON object by field value

Hows about this:

$json=Get-Content -Raw -Path 'my.json' | Out-String | ConvertFrom-Json
$foo="TheVariableYourUsingToSelectSomething"
$json.SomePathYouKnow.psobject.properties.Where({$_.name -eq $foo}).value

which would select from json structured

{"SomePathYouKnow":{"TheVariableYourUsingToSelectSomething": "Tada!"}

This is based on this accessing values in powershell SO question . Isn't powershell fabulous!

Laravel requires the Mcrypt PHP extension

For php-fpm installations on Ubuntu 14.04, the following worked for me :

sudo apt-get install php5-mcrypt

This will create mcrypt.ini file inside /etc/php5/mods-available/

Then

sudo php5enmod mcrypt

will create a symlink in: /etc/php5/fpm/conf.d/

Just restart php-fpm services sudo service php5-fpm restart

How to mark-up phone numbers?

I use the normal <a href="tel:+123456">12 34 56</a> markup and make those links non-clickable for desktop users via pointer-events: none;

a[href^="tel:"] {
    text-decoration: none;
}
.no-touch a[href^="tel:"] {
    pointer-events: none;
    cursor: text;
}

for browsers that don't support pointer-events (IE < 11), the click can be prevented with JavaScript (example relies on Modernizr and jQuery):

if(!Modernizr.touch) {
    $(document).on('click', '[href^="tel:"]', function(e) {
        e.preventDefault();
        return false;
    });
}

SASS and @font-face

I’ve been struggling with this for a while now. Dycey’s solution is correct in that specifying the src multiple times outputs the same thing in your css file. However, this seems to break in OSX Firefox 23 (probably other versions too, but I don’t have time to test).

The cross-browser @font-face solution from Font Squirrel looks like this:

@font-face {
    font-family: 'fontname';
    src: url('fontname.eot');
    src: url('fontname.eot?#iefix') format('embedded-opentype'),
         url('fontname.woff') format('woff'),
         url('fontname.ttf') format('truetype'),
         url('fontname.svg#fontname') format('svg');
    font-weight: normal;
    font-style: normal;
}

To produce the src property with the comma-separated values, you need to write all of the values on one line, since line-breaks are not supported in Sass. To produce the above declaration, you would write the following Sass:

@font-face
  font-family: 'fontname'
  src: url('fontname.eot')
  src: url('fontname.eot?#iefix') format('embedded-opentype'), url('fontname.woff') format('woff'), url('fontname.ttf') format('truetype'), url('fontname.svg#fontname') format('svg')
  font-weight: normal
  font-style: normal

I think it seems silly to write out the path a bunch of times, and I don’t like overly long lines in my code, so I worked around it by writing this mixin:

=font-face($family, $path, $svg, $weight: normal, $style: normal)
  @font-face
    font-family: $family
    src: url('#{$path}.eot')
    src: url('#{$path}.eot?#iefix') format('embedded-opentype'), url('#{$path}.woff') format('woff'), url('#{$path}.ttf') format('truetype'), url('#{$path}.svg##{$svg}') format('svg')
    font-weight: $weight
    font-style: $style

Usage: For example, I can use the previous mixin to setup up the Frutiger Light font like this:

+font-face('frutigerlight', '../fonts/frutilig-webfont', 'frutigerlight')

Converting NSData to NSString in Objective c

NSString *string = [NSString stringWithUTF8String:[Data bytes]];

What is REST? Slightly confused

http://en.wikipedia.org/wiki/Representational_State_Transfer

The basic idea is that instead of having an ongoing connection to the server, you make a request, get some data, show that to a user, but maybe not all of it, and then when the user does something which calls for more data, or to pass some up to the server, the client initiates a change to a new state.

javascript regular expression to check for IP addresses

This is what I did and it's fast and works perfectly:

function isIPv4Address(inputString) {
    let regex = new RegExp(/^(([0-9]{1,3}\.){3}[0-9]{1,3})$/);
    if(regex.test(inputString)){
        let arInput = inputString.split(".")
        for(let i of arInput){
            if(i.length > 1 && i.charAt(0) === '0')
                return false;
            else{
                if(parseInt(i) < 0 || parseInt(i) >=256)
                   return false;
            }
        }
    }
    else
        return false;
    return true;
}

Explanation: First, with the regex check that the IP format is correct. Although, the regex won't check any value ranges.

I mean, if you can use Javascript to manage regex, why not use it?. So, instead of using a crazy regex, use Regex only for checking that the format is fine and then check that each value in the octet is in the correct value range (0 to 255). Hope this helps anybody else. Peace.

How to make HTML element resizable using pure Javascript?

I just created a CodePen that shows how this can be done pretty easily using ES6.

http://codepen.io/travist/pen/GWRBQV

Basically, here is the class that does this.

let getPropertyValue = function(style, prop) {
  let value = style.getPropertyValue(prop);
  value = value ? value.replace(/[^0-9.]/g, '') : '0';
  return parseFloat(value);
}

let getElementRect = function(element) {
  let style = window.getComputedStyle(element, null);
  return {
    x: getPropertyValue(style, 'left'),
    y: getPropertyValue(style, 'top'),
    width: getPropertyValue(style, 'width'),
    height: getPropertyValue(style, 'height')
  }
}

class Resizer {
    constructor(wrapper, element, options) {
        this.wrapper = wrapper;
        this.element = element;
        this.options = options;
        this.offsetX = 0;
        this.offsetY = 0;
        this.handle = document.createElement('div');
        this.handle.setAttribute('class', 'drag-resize-handlers');
        this.handle.setAttribute('data-direction', 'br');
        this.wrapper.appendChild(this.handle);
        this.wrapper.style.top = this.element.style.top;
        this.wrapper.style.left = this.element.style.left;
        this.wrapper.style.width = this.element.style.width;
        this.wrapper.style.height = this.element.style.height;
        this.element.style.position = 'relative';
        this.element.style.top = 0;
        this.element.style.left = 0;
        this.onResize = this.resizeHandler.bind(this);
        this.onStop = this.stopResize.bind(this);
        this.handle.addEventListener('mousedown', this.initResize.bind(this));
    }

    initResize(event) {
        this.stopResize(event, true);
        this.handle.addEventListener('mousemove', this.onResize);
        this.handle.addEventListener('mouseup', this.onStop);
    }

    resizeHandler(event) {
        this.offsetX = event.clientX - (this.wrapper.offsetLeft + this.handle.offsetLeft);
        this.offsetY = event.clientY - (this.wrapper.offsetTop + this.handle.offsetTop);
        let wrapperRect = getElementRect(this.wrapper);
        let elementRect = getElementRect(this.element);
        this.wrapper.style.width = (wrapperRect.width + this.offsetX) + 'px';
        this.wrapper.style.height = (wrapperRect.height + this.offsetY) + 'px';
        this.element.style.width = (elementRect.width + this.offsetX) + 'px';
        this.element.style.height = (elementRect.height + this.offsetY) + 'px';
    }

    stopResize(event, nocb) {
        this.handle.removeEventListener('mousemove', this.onResize); 
        this.handle.removeEventListener('mouseup', this.onStop);
    }
}

class Dragger {
    constructor(wrapper, element, options) {
        this.wrapper = wrapper;
        this.options = options;
        this.element = element;
        this.element.draggable = true;
        this.element.setAttribute('draggable', true);
        this.element.addEventListener('dragstart', this.dragStart.bind(this));
    }

    dragStart(event) {
        let wrapperRect = getElementRect(this.wrapper);
        var x = wrapperRect.x - parseFloat(event.clientX);
        var y = wrapperRect.y - parseFloat(event.clientY);
        event.dataTransfer.setData("text/plain", this.element.id + ',' + x + ',' + y);
    }

    dragStop(event, prevX, prevY) {
        var posX = parseFloat(event.clientX) + prevX;
        var posY = parseFloat(event.clientY) + prevY;
        this.wrapper.style.left = posX + 'px';
        this.wrapper.style.top = posY + 'px';
    }
}

class DragResize {
    constructor(element, options) {
        options = options || {};
        this.wrapper = document.createElement('div');
        this.wrapper.setAttribute('class', 'tooltip drag-resize');
        if (element.parentNode) {
          element.parentNode.insertBefore(this.wrapper, element);
        }
        this.wrapper.appendChild(element);
        element.resizer = new Resizer(this.wrapper, element, options);
        element.dragger = new Dragger(this.wrapper, element, options);
    }
}

document.body.addEventListener('dragover', function (event) {
    event.preventDefault();
    return false;
});

document.body.addEventListener('drop', function (event) {
    event.preventDefault();
    var dropData = event.dataTransfer.getData("text/plain").split(',');
    var element = document.getElementById(dropData[0]);
    element.dragger.dragStop(event, parseFloat(dropData[1]), parseFloat(dropData[2]));
    return false;
});

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

How can I resize an image using Java?

I have developed a solution with the freely available classes ( AnimatedGifEncoder, GifDecoder, and LWZEncoder) available for handling GIF Animation.
You can download the jgifcode jar and run the GifImageUtil class. Link: http://www.jgifcode.com

Override and reset CSS style: auto or none don't work

"none" does not do what you assume it does. In order to "clear" a CSS property, you must set it back to its default, which is defined by the CSS standard. Thus you should look up the defaults in your favorite reference.

table.other {
    width: auto;
    min-width: 0;
    display:table;
}

Default value in an asp.net mvc view model

What will you have? You'll probably end up with a default search and a search that you load from somewhere. Default search requires a default constructor, so make one like Dismissile has already suggested.

If you load the search criteria from elsewhere, then you should probably have some mapping logic.

How to escape JSON string?

I ran speed tests on some of these answers for a long string and a short string. Clive Paterson's code won by a good bit, presumably because the others are taking into account serialization options. Here are my results:

Apple Banana
System.Web.HttpUtility.JavaScriptStringEncode: 140ms
System.Web.Helpers.Json.Encode: 326ms
Newtonsoft.Json.JsonConvert.ToString: 230ms
Clive Paterson: 108ms

\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\"things\to\escape\some\long\path\with\lots"\of\things\to\escape
System.Web.HttpUtility.JavaScriptStringEncode: 2849ms
System.Web.Helpers.Json.Encode: 3300ms
Newtonsoft.Json.JsonConvert.ToString: 2827ms
Clive Paterson: 1173ms

And here is the test code:

public static void Main(string[] args)
{
    var testStr1 = "Apple Banana";
    var testStr2 = @"\\some\long\path\with\lots\of\things\to\escape\some\long\path\t\with\lots\of\n\things\to\escape\some\long\path\with\lots\of\""things\to\escape\some\long\path\with\lots""\of\things\to\escape";

    foreach (var testStr in new[] { testStr1, testStr2 })
    {
        var results = new Dictionary<string,List<long>>();

        for (var n = 0; n < 10; n++)
        {
            var count = 1000 * 1000;

            var sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = System.Web.HttpUtility.JavaScriptStringEncode(testStr);
            }
            var t = sw.ElapsedMilliseconds;
            results.GetOrCreate("System.Web.HttpUtility.JavaScriptStringEncode").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = System.Web.Helpers.Json.Encode(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("System.Web.Helpers.Json.Encode").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = Newtonsoft.Json.JsonConvert.ToString(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("Newtonsoft.Json.JsonConvert.ToString").Add(t);

            sw = Stopwatch.StartNew();
            for (var i = 0; i < count; i++)
            {
                var s = cleanForJSON(testStr);
            }
            t = sw.ElapsedMilliseconds;
            results.GetOrCreate("Clive Paterson").Add(t);
        }

        Console.WriteLine(testStr);
        foreach (var result in results)
        {
            Console.WriteLine(result.Key + ": " + Math.Round(result.Value.Skip(1).Average()) + "ms");
        }
        Console.WriteLine();
    }

    Console.ReadLine();
}

What is the difference between getText() and getAttribute() in Selenium WebDriver?

  <input attr1='a' attr2='b' attr3='c'>foo</input>

getAttribute(attr1) you get 'a'

getAttribute(attr2) you get 'b'

getAttribute(attr3) you get 'c'

getText() with no parameter you can only get 'foo'

Iterate through string array in Java

You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:

String[] elements = {"a", "a", "a", "a"};   
for (String s: elements) {           
    //Do your stuff here
    System.out.println(s); 
}

How to convert date to timestamp in PHP?

Here is a very simple and effective solution using the split and mtime functions:

$date="30/07/2010 13:24"; //Date example
list($day, $month, $year, $hour, $minute) = split('[/ :]', $date); 

//The variables should be arranged according to your date format and so the separators
$timestamp = mktime($hour, $minute, 0, $month, $day, $year);
echo date("r", $timestamp);

It worked like a charm for me.

How do I configure git to ignore some files locally?

I think you are looking for:

git update-index --skip-worktree FILENAME

which ignore changes made local

Here's http://devblog.avdi.org/2011/05/20/keep-local-modifications-in-git-tracked-files/ more explanation about these solution!

to undo use:

git update-index --no-skip-worktree FILENAME

PHP script to loop through all of the files in a directory?

If you don't have access to DirectoryIterator class try this:

<?php
$path = "/path/to/files";

if ($handle = opendir($path)) {
    while (false !== ($file = readdir($handle))) {
        if ('.' === $file) continue;
        if ('..' === $file) continue;

        // do something with the file
    }
    closedir($handle);
}
?>

Python datetime strptime() and strftime(): how to preserve the timezone information

Try this:

import pytz
import datetime

fmt = '%Y-%m-%d %H:%M:%S %Z'

d = datetime.datetime.now(pytz.timezone("America/New_York"))
d_string = d.strftime(fmt)
d2 = pytz.timezone('America/New_York').localize(d.strptime(d_string,fmt), is_dst=None)
print(d_string)
print(d2.strftime(fmt))

Why is "cursor:pointer" effect in CSS not working

I have the same issue, when I close the chrome window popup browser inspector its working fine for me.

Angular 2 - Setting selected value on dropdown list

If your values are coming from the database, show selected values in that way.

<div class="form-group">
    <label for="status">Status</label>
    <select class="form-control" name="status" [(ngModel)]="category.status">
       <option [value]="1" [selected]="category.status ==1">Active</option>
       <option [value]="0" [selected]="category.status ==0">In Active</option>
    </select>
</div>

How can I insert new line/carriage returns into an element.textContent?

I found that inserting \\n works. I.e., you escape the escaped new line character

How to get the day name from a selected date?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessTheDay
{
class Program
{
    static void Main(string[] args)
    { 
 Console.WriteLine("Enter the Day Number ");
 int day = int.Parse(Console.ReadLine());
 Console.WriteLine(" Enter The Month");
int month = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Year ");
int year = int.Parse(Console.ReadLine());
DateTime mydate = new DateTime(year,month,day);
string formatteddate = string.Format("{0:dddd}", mydate);
Console.WriteLine("The day should be " + formatteddate);
}  
 } 
   }

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

Unfortunately this error is not descriptive for a range of different problems related to the same issue - a binding error. It also does not specify where the error is, and so your problem is not necessarily in the execution, but the sql statement that was already 'prepared'.

These are the possible errors and their solutions:

  1. There is a parameter mismatch - the number of fields does not match the parameters that have been bound. Watch out for arrays in arrays. To double check - use var_dump($var). "print_r" doesn't necessarily show you if the index in an array is another array (if the array has one value in it), whereas var_dump will.

  2. You have tried to bind using the same binding value, for example: ":hash" and ":hash". Every index has to be unique, even if logically it makes sense to use the same for two different parts, even if it's the same value. (it's similar to a constant but more like a placeholder)

  3. If you're binding more than one value in a statement (as is often the case with an "INSERT"), you need to bindParam and then bindValue to the parameters. The process here is to bind the parameters to the fields, and then bind the values to the parameters.

    // Code snippet
    $column_names = array();
    $stmt->bindParam(':'.$i, $column_names[$i], $param_type);
    $stmt->bindValue(':'.$i, $values[$i], $param_type);
    $i++;
    //.....
    
  4. When binding values to column_names or table_names you can use `` but its not necessary, but make sure to be consistent.

  5. Any value in '' single quotes is always treated as a string and will not be read as a column/table name or placeholder to bind to.

correct way to define class variables in Python

Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:

  • Elements outside the __init__ method are static elements; they belong to the class.
  • Elements inside the __init__ method are elements of the object (self); they don't belong to the class.

You'll see it more clearly with some code:

class MyClass:
    static_elem = 123

    def __init__(self):
        self.object_elem = 456

c1 = MyClass()
c2 = MyClass()

# Initial values of both elements
>>> print c1.static_elem, c1.object_elem 
123 456
>>> print c2.static_elem, c2.object_elem
123 456

# Nothing new so far ...

# Let's try changing the static element
MyClass.static_elem = 999

>>> print c1.static_elem, c1.object_elem
999 456
>>> print c2.static_elem, c2.object_elem
999 456

# Now, let's try changing the object element
c1.object_elem = 888

>>> print c1.static_elem, c1.object_elem
999 888
>>> print c2.static_elem, c2.object_elem
999 456

As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.

How do I set default values for functions parameters in Matlab?

if you would use octave you could do it like this - but sadly matlab does not support this possibility

function hello (who = "World")
  printf ("Hello, %s!\n", who);
endfunction

(taken from the doc)

Javascript array sort and unique

The fastest and simpleness way to do this task.

const N = Math.pow(8, 8)
let data = Array.from({length:  N}, () => Math.floor(Math.random() * N))
let newData = {}
let len = data.length

// the magic
while (len--) {
    newData[data[len]] = true
}

Maven "build path specifies execution environment J2SE-1.5", even though I changed it to 1.7

  1. Right-click on your project
  2. Click Properties
  3. Click the "Java Compiler" option on the left menu
  4. Under JDK compliance section on the right, change it to "1.7"
  5. Run a Maven clean and then Maven build.

How can I clear previous output in Terminal in Mac OS X?

Or you can send a page break (ASCII form feed) by pressing Ctrl + L.

While this technically just starts a new page, this has the same net effect as all the other methods, while being a lot faster (except for the Apple + K solution, of course).

And because this is an ASCII control command, and it works in all shells.

Security of REST authentication schemes

If you require the hash of the body as one of the parameters in the URL and that URL is signed via a private key, then a man-in-the-middle attack would only be able to replace the body with content that would generate the same hash. Easy to do with MD5 hash values now at least and when SHA-1 is broken, well, you get the picture.

To secure the body from tampering, you would need to require a signature of the body, which a man-in-the-middle attack would be less likely to be able to break since they wouldn't know the private key that generates the signature.

How can I calculate the difference between two dates?

To find the difference, you need to get the current date and the date in the future. In the following case, I used 2 days for an example of the future date. Calculated by:

2 days * 24 hours * 60 minutes * 60 seconds. We expect the number of seconds in 2 days to be 172,800.

// Set the current and future date
let now = Date()
let nowPlus2Days = Date(timeInterval: 2*24*60*60, since: now)

// Get the number of seconds between these two dates
let secondsInterval = DateInterval(start: now, end: nowPlus2Days).duration

print(secondsInterval) // 172800.0

Rounding Bigdecimal values with 2 Decimal Places

Add 0.001 first to the number and then call setScale(2, RoundingMode.ROUND_HALF_UP)

Code example:

public static void main(String[] args) {
    BigDecimal a = new BigDecimal("10.12445").add(new BigDecimal("0.001"));
    BigDecimal b = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(b);
}

How to loop through a HashMap in JSP?

Below code works for me

first I defined the partnerTypesMap like below in the server side,

Map<String, String> partnerTypes = new HashMap<>();

after adding values to it I added the object to model,

model.addAttribute("partnerTypesMap", partnerTypes);

When rendering the page I use below foreach to print them one by one.

<c:forEach items="${partnerTypesMap}" var="partnerTypesMap">
      <form:option value="${partnerTypesMap['value']}">${partnerTypesMap['key']}</form:option>
</c:forEach>

Excel: replace part of cell's string value

What you need to do is as follows:

  1. List item
  2. Select the entire column by clicking once on the corresponding letter or by simply selecting the cells with your mouse.
  3. Press Ctrl+H.
  4. You are now in the "Find and Replace" dialog. Write "Author" in the "Find what" text box.
  5. Write "Authoring" in the "Replace with" text box.
  6. Click the "Replace All" button.

That's it!

How do I load a file from resource folder?

this.getClass().getClassLoader().getResource("filename").getPath()

Can I access constants in settings.py from templates in Django?

If using a class-based view:

#
# in settings.py
#
YOUR_CUSTOM_SETTING = 'some value'

#
# in views.py
#
from django.conf import settings #for getting settings vars

class YourView(DetailView): #assuming DetailView; whatever though

    # ...

    def get_context_data(self, **kwargs):

        context = super(YourView, self).get_context_data(**kwargs)
        context['YOUR_CUSTOM_SETTING'] = settings.YOUR_CUSTOM_SETTING

        return context

#
# in your_template.html, reference the setting like any other context variable
#
{{ YOUR_CUSTOM_SETTING }}

Why does ENOENT mean "No such file or directory"?

It's simply “No such directory entry”. Since directory entries can be directories or files (or symlinks, or sockets, or pipes, or devices), the name ENOFILE would have been too narrow in its meaning.

.NET Core vs Mono

This question is especially actual because yesterday Microsoft officially announced .NET Core 1.0 release. Assuming that Mono implements most of the standard .NET libraries, the difference between Mono and .NET core can be seen through the difference between .NET Framework and .NET Core:

  • APIs — .NET Core contains many of the same, but fewer, APIs as the .NET Framework, and with a different factoring (assembly names are
    different; type shape differs in key cases). These differences
    currently typically require changes to port source to .NET Core. .NET Core implements the .NET Standard Library API, which will grow to
    include more of the .NET Framework BCL APIs over time.
  • Subsystems — .NET Core implements a subset of the subsystems in the .NET Framework, with the goal of a simpler implementation and
    programming model. For example, Code Access Security (CAS) is not
    supported, while reflection is supported.

If you need to launch something quickly, go with Mono because it is currently (June 2016) more mature product, but if you are building a long-term website, I would suggest .NET Core. It is officially supported by Microsoft and the difference in supported APIs will probably disappear soon, taking into account the effort that Microsoft puts in the development of .NET Core.

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

Linq and Entity framework are included in .NET Core, so you are safe to take a shot.

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

How do I reverse a commit in git?

This article has an excellent explanation as to how to go about various scenarios (where a commit has been done as well as the push OR just a commit, before the push):

http://christoph.ruegg.name/blog/git-howto-revert-a-commit-already-pushed-to-a-remote-reposit.html

From the article, the easiest command I saw to revert a previous commit by its commit id, was:

git revert dd61ab32

Rename multiple files by replacing a particular pattern in the filenames using a shell script

An example to help you get off the ground.

for f in *.jpg; do mv "$f" "$(echo "$f" | sed s/IMG/VACATION/)"; done

In this example, I am assuming that all your image files contain the string IMG and you want to replace IMG with VACATION.

The shell automatically evaluates *.jpg to all the matching files.

The second argument of mv (the new name of the file) is the output of the sed command that replaces IMG with VACATION.

If your filenames include whitespace pay careful attention to the "$f" notation. You need the double-quotes to preserve the whitespace.

"Gradle Version 2.10 is required." Error

First Check your Project-level settings at

File > Settings > Build, Executions, Deployment > Build Tools > Gradle

and Select the Option :

  • Use default gradle wrapper (recommended)

then go to Project's

Gradle > wrapper > gradle-wrapper.properties

and edit version of the distributionUrl

distributionUrl=https://services.gradle.org/distributions/gradle-2.10-all.zip

And you are done :)

Ruby 2.0.0p0 IRB warning: "DL is deprecated, please use Fiddle"

I ran into this myself when I wanted to make a thor command under Windows.

To avoid having that message output everytime I ran my thor application I temporarily muted warnings while loading thor:

begin
  original_verbose = $VERBOSE
  $VERBOSE = nil
  require "thor"
ensure
  $VERBOSE = original_verbose
end

That saved me from having to edit third party source files.

Under what conditions is a JSESSIONID created?

Beware if your page is including other .jsp or .jspf (fragment)! If you don't set

<%@ page session="false" %>

on them as well, the parent page will end up starting a new session and setting the JSESSIONID cookie.

For .jspf pages in particular, this happens if you configured your web.xml with such a snippet:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jspf</url-pattern>
    </jsp-property-group>
</jsp-config>

in order to enable scriptlets inside them.

How to validate an OAuth 2.0 access token for a resource server?

An update on @Scott T.'s answer: the interface between Resource Server and Authorization Server for token validation was standardized in IETF RFC 7662 in October 2015, see: https://tools.ietf.org/html/rfc7662. A sample validation call would look like:

POST /introspect HTTP/1.1
Host: server.example.com
Accept: application/json
Content-Type: application/x-www-form-urlencoded
Authorization: Bearer 23410913-abewfq.123483

token=2YotnFZFEjr1zCsicMWpAA

and a sample response:

HTTP/1.1 200 OK
Content-Type: application/json

{
  "active": true,
  "client_id": "l238j323ds-23ij4",
  "username": "jdoe",
  "scope": "read write dolphin",
  "sub": "Z5O3upPC88QrAjx00dis",
  "aud": "https://protected.example.net/resource",
  "iss": "https://server.example.com/",
  "exp": 1419356238,
  "iat": 1419350238,
  "extension_field": "twenty-seven"
}

Of course adoption by vendors and products will have to happen over time.

Redirect to Action by parameter mvc

Try this,

return RedirectToAction("ActionEventName", "Controller", new { ID = model.ID, SiteID = model.SiteID });

Here i mention you are pass multiple values or model also. That's why here i mention that.

How to write a PHP ternary operator

echo ($result ->vocation == 1) ? 'Sorcerer'
        : ($result->vocation == 2) ? 'Druid'
           :  ($result->vocation == 3) ? 'Paladin'
                    ....

;

It’s kind of ugly. You should stick with normal if statements.

Client on Node.js: Uncaught ReferenceError: require is not defined

This worked for me

  1. Save the file https://requirejs.org/docs/release/2.3.5/minified/require.js. It is the file for RequestJS which is what we will use.
  2. Load it into your HTML content like this: <script data-main="your-script.js" src="require.js"></script>

Notes!

Use require(['moudle-name']) in your-script.js, not require('moudle-name')

Use const {ipcRenderer} = require(['electron']), not const {ipcRenderer} = require('electron')

Disable browser's back button

<script>
    $(document).ready(function() {
        function disableBack() { window.history.forward() }

        window.onload = disableBack();
        window.onpageshow = function(evt) { if (evt.persisted) disableBack() }
    });
</script>

How do I read a large csv file with pandas?

I proceeded like this:

chunks=pd.read_table('aphro.csv',chunksize=1000000,sep=';',\
       names=['lat','long','rf','date','slno'],index_col='slno',\
       header=None,parse_dates=['date'])

df=pd.DataFrame()
%time df=pd.concat(chunk.groupby(['lat','long',chunk['date'].map(lambda x: x.year)])['rf'].agg(['sum']) for chunk in chunks)

Display Back Arrow on Toolbar

If you want to get the back arrow on a Toolbar that's not set as your SupportActionBar:

(kotlin)

val resId = getResIdFromAttribute(toolbar.context, android.R.attr.homeAsUpIndicator)
toolbarFilter.navigationIcon = ContextCompat.getDrawable(toolbar.context, resId)
toolbarFilter.setNavigationOnClickListener { fragmentManager?.popBackStack() }

to get res from attributes:

@AnyRes
fun getResIdFromAttribute(context: Context, @AttrRes attr: Int): Int {
    if (attr == 0) return 0
    val typedValueAttr = TypedValue()
    context.theme.resolveAttribute(attr, typedValueAttr, true)
    return typedValueAttr.resourceId
}

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

jQuery autohide element after 5 seconds

You use setTimeout on you runEffect function :

function runEffect() {
    setTimeout(function(){
        var selectedEffect = 'blind';
        var options = {};
        $("#successMessage").hide(selectedEffect, options, 500)
     }, 5000);
}

Is it possible to pull just one file in Git?

Yes, here is the process:

# Navigate to a directory and initiate a local repository
git init        

# Add remote repository to be tracked for changes:   
git remote add origin https://github.com/username/repository_name.git

# Track all changes made on above remote repository
# This will show files on remote repository not available on local repository
git fetch

# Add file present in staging area for checkout
git check origin/master -m /path/to/file
# NOTE: /path/to/file is a relative path from repository_name
git add /path/to/file

# Verify track of file(s) being committed to local repository
git status

# Commit to local repository
git commit -m "commit message"

# You may perform a final check of the staging area again with git status

Get the directory from a file path in java (android)

I have got solution on this after 4 days, Please note following points while giving path to File class in Android(Java):

  1. Use path for internal storage String path="/storage/sdcard0/myfile.txt";
  2. path="/storage/sdcard1/myfile.txt";
  3. mention permissions in Manifest file.

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

  4. First check file length for confirmation.
  5. Check paths in ES File Explorer regarding sdcard0 & sdcard1 is this same or else......

e.g.

File file=new File(path);
long=file.length();//in Bytes

How to get files in a relative path in C#

string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");

The first parameter is the path. The second is the search pattern you want to use.

How to create a drop shadow only on one side of an element?

If your background is solid (or you can reproduce it using CSS), you can use linear gradient that way:

_x000D_
_x000D_
div {_x000D_
  background-image: linear-gradient(to top, rgba(0, 0, 0, 0) 0%, rgba(0, 0, 0, 0.3) 5px, #fff 5px, #fff 100%)_x000D_
}
_x000D_
<div>_x000D_
<p>Foobar</p>_x000D_
<p>test</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will generate a 5px gradient at the bottom of the element, from black at 30% opacity to completely transparent. The rest of the element has white background. Of course, changing the last 2 color stops of the linear gradient, you could make the background completely transparent.

The ResourceConfig instance does not contain any root resource classes

I am getting this exception, because of a missing ResourseConfig in Web.xml.

Add:

<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>/* Name of Package where your service class exists */</param-value>
</init-param>

Service class means: class which contains services like: @Path("/orders")

Use stored procedure to insert some data into a table

If you are trying to return back the ID within the scope, using the SCOPE_IDENTITY() would be a better approach. I would not advice to use @@IDENTITY, as this can return any ID.

CREATE PROC [dbo].[sp_Test] (
  @myID int output,
  @myFirstName nvarchar(50),
  @myLastName nvarchar(50),
  @myAddress nvarchar(50),
  @myPort int
) AS
BEGIN
    INSERT INTO Dvds (myFirstName, myLastName, myAddress, myPort)
    VALUES (@myFirstName, @myLastName, @myAddress, @myPort);

    SET @myID = SCOPE_IDENTITY();
END
GO

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

It is General sibling combinator and is explained in @Salaman's answer very well.

What I did miss is Adjacent sibling combinator which is + and is closely related to ~.

example would be

.a + .b {
  background-color: #ff0000;
}

<ul>
  <li class="a">1st</li>
  <li class="b">2nd</li>
  <li>3rd</li>
  <li class="b">4th</li>
  <li class="a">5th</li>
</ul>
  • Matches elements that are .b
  • Are adjacent to .a
  • After .a in HTML

In example above it will mark 2nd li but not 4th.

_x000D_
_x000D_
   .a + .b {_x000D_
     background-color: #ff0000;_x000D_
   }
_x000D_
<ul>_x000D_
  <li class="a">1st</li>_x000D_
  <li class="b">2nd</li>_x000D_
  <li>3rd</li>_x000D_
  <li class="b">4th</li>_x000D_
  <li class="a">5th</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

JSFiddle

javax.el.PropertyNotFoundException: Property 'foo' not found on type com.example.Bean

I believe the id accessors don't match the bean naming conventions and that's why the exception is thrown. They should be as follows:

public Integer getId() { return id; }    
public void setId(Integer i){ id= i; }

How to do a GitHub pull request

I've started a project to help people making their first GitHub pull request. You can do the hands-on tutorial to make your first PR here

The workflow is simple as

  • Fork the repo in github
  • Get clone url by clicking on clone repo button
  • Go to terminal and run git clone <clone url you copied earlier>
  • Make a branch for changes you're makeing git checkout -b branch-name
  • Make necessary changes
  • Commit your changes git commit
  • Push your changes to your fork on GitHub git push origin branch-name
  • Go to your fork on GitHub to see a Compare and pull request button
  • Click on it and give necessary details

Making interface implementations async

Neither of these options is correct. You're trying to implement a synchronous interface asynchronously. Don't do that. The problem is that when DoOperation() returns, the operation won't be complete yet. Worse, if an exception happens during the operation (which is very common with IO operations), the user won't have a chance to deal with that exception.

What you need to do is to modify the interface, so that it is asynchronous:

interface IIO
{
    Task DoOperationAsync(); // note: no async here
}

class IOImplementation : IIO
{
    public async Task DoOperationAsync()
    {
        // perform the operation here
    }
}

This way, the user will see that the operation is async and they will be able to await it. This also pretty much forces the users of your code to switch to async, but that's unavoidable.

Also, I assume using StartNew() in your implementation is just an example, you shouldn't need that to implement asynchronous IO. (And new Task() is even worse, that won't even work, because you don't Start() the Task.)

How to host a Node.Js application in shared hosting

Connect with SSH and follow these instructions to install Node on a shared hosting

In short you first install NVM, then you install the Node version of your choice with NVM.

wget -qO- https://cdn.rawgit.com/creationix/nvm/master/install.sh | bash

Your restart your shell (close and reopen your sessions). Then you

nvm install stable

to install the latest stable version for example. You can install any version of your choice. Check node --version for the node version you are currently using and nvm list to see what you've installed.

In bonus you can switch version very easily (nvm use <version>)

There's no need of PHP or whichever tricky workaround if you have SSH.

python max function using 'key' and lambda expression

How does the max function work?

It looks for the "largest" item in an iterable. I'll assume that you can look up what that is, but if not, it's something you can loop over, i.e. a list or string.

What is use of the keyword key in max function? I know it is also used in context of sort function

Key is a lambda function that will tell max which objects in the iterable are larger than others. Say if you were sorting some object that you created yourself, and not something obvious, like integers.

Meaning of the lambda expression? How to read them? How do they work?

That's sort of a larger question. In simple terms, a lambda is a function you can pass around, and have other pieces of code use it. Take this for example:

def sum(a, b, f):
    return (f(a) + f(b))

This takes two objects, a and b, and a function f. It calls f() on each object, then adds them together. So look at this call:

>>> sum(2, 2, lambda a:  a * 2)
8

sum() takes 2, and calls the lambda expression on it. So f(a) becomes 2 * 2, which becomes 4. It then does this for b, and adds the two together.

In not so simple terms, lambdas come from lambda calculus, which is the idea of a function that returns a function; a very cool math concept for expressing computation. You can read about that here, and then actually understand it here.

It's probably better to read about this a little more, as lambdas can be confusing, and it's not immediately obvious how useful they are. Check here.

Call a stored procedure with another in Oracle

Sure, you just call it from within the SP, there's no special syntax.

Ex:

   PROCEDURE some_sp
   AS
   BEGIN
      some_other_sp('parm1', 10, 20.42);
   END;

If the procedure is in a different schema than the one the executing procedure is in, you need to prefix it with schema name.

   PROCEDURE some_sp
   AS
   BEGIN
      other_schema.some_other_sp('parm1', 10, 20.42);
   END;

HTTP POST with URL query parameters -- good idea or not?

If your action is not idempotent, then you MUST use POST. If you don't, you're just asking for trouble down the line. GET, PUT and DELETE methods are required to be idempotent. Imagine what would happen in your application if the client was pre-fetching every possible GET request for your service – if this would cause side effects visible to the client, then something's wrong.

I agree that sending a POST with a query string but without a body seems odd, but I think it can be appropriate in some situations.

Think of the query part of a URL as a command to the resource to limit the scope of the current request. Typically, query strings are used to sort or filter a GET request (like ?page=1&sort=title) but I suppose it makes sense on a POST to also limit the scope (perhaps like ?action=delete&id=5).

Should try...catch go inside or outside a loop?

If its an all-or-nothing fail, then the first format makes sense. If you want to be able to process/return all the non-failing elements, you need to use the second form. Those would be my basic criteria for choosing between the methods. Personally, if it is all-or-nothing, I wouldn't use the second form.

Dismissing a Presented View Controller

Swift

let rootViewController:UIViewController = (UIApplication.shared.keyWindow?.rootViewController)!

        if (rootViewController.presentedViewController != nil) {
            rootViewController.dismiss(animated: true, completion: {
                //completion block.
            })
        }

Bootstrap 4 - Responsive cards in card-columns

I realize this question was posted a while ago; nonetheless, Bootstrap v4.0 has card layout support out of the box. You can find the documentation here: Bootstrap Card Layouts.

I've gotten back into using Bootstrap for a recent project that relies heavily on the card layout UI. I've found success with the following implementation across the standard breakpoints:

_x000D_
_x000D_
<link href="https://unpkg.com/[email protected]/css/tachyons.min.css" rel="stylesheet"/>_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div class="flex justify-center" id="cars" v-cloak>_x000D_
    <!-- RELEVANT MARKUP BEGINS HERE -->_x000D_
    <div class="container mh0 w-100">_x000D_
        <div class="page-header text-center mb5">_x000D_
            <h1 class="avenir text-primary mb-0">Cars</h1>_x000D_
            <p class="text-secondary">Add and manage your cars for sale.</p>_x000D_
            <div class="header-button">_x000D_
                <button class="btn btn-outline-primary" @click="clickOpenAddCarModalButton">Add a car for sale</button>_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="container pa0 flex justify-center">_x000D_
            <div class="listings card-columns">_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
                <div class="card mv2">_x000D_
                    <img src="https://farm4.staticflickr.com/3441/3361756632_8d84aa8560.jpg" class="card-img-top"_x000D_
                        alt="Mazda hatchback">_x000D_
                    <div class="card-body">_x000D_
                        <h5 class="card-title">Card title</h5>_x000D_
                        <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's_x000D_
                            content._x000D_
                        </p>_x000D_
                        <a href="#" class="btn btn-primary">Go somewhere</a>_x000D_
                    </div>_x000D_
                    <div class="card-footer">_x000D_
                        buttons here_x000D_
                    </div>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

After trying both the Bootstrap .card-group and .card-deck card layout classes with quirky results at best across the standard breakpoints, I finally decided to give the .card-columns class a shot. And it worked!

Your results may vary, but .card-columns seems to be the most stable implementation here.

React Router v4 - How to get current route?

In react router 4 the current route is in - this.props.location.pathname. Just get this.props and verify. If you still do not see location.pathname then you should use the decorator withRouter.

This might look something like this:

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

const SomeComponent = withRouter(props => <MyComponent {...props}/>);

class MyComponent extends React.Component {
  SomeMethod () {
    const {pathname} = this.props.location;
  }
}

Rails Root directory path?

In some cases you may want the Rails root without having to load Rails.

For example, you get a quicker feedback cycle when TDD'ing models that do not depend on Rails by requiring spec_helper instead of rails_helper.

# spec/spec_helper.rb

require 'pathname'

rails_root = Pathname.new('..').expand_path(File.dirname(__FILE__))

[
  rails_root.join('app', 'models'),
  # Add your decorators, services, etc.
].each do |path|
  $LOAD_PATH.unshift path.to_s
end

Which allows you to easily load Plain Old Ruby Objects from their spec files.

# spec/models/poro_spec.rb

require 'spec_helper'

require 'poro'

RSpec.describe ...

Updating property value in properties file without deleting other values

Properties prop = new Properties();
prop.load(...); // FileInputStream 
prop.setProperty("key", "value");
prop.store(...); // FileOutputStream 

Best way to convert strings to symbols in hash

In case the reason you need to do this is because your data originally came from JSON, you could skip any of this parsing by just passing in the :symbolize_names option upon ingesting JSON.

No Rails required and works with Ruby >1.9

JSON.parse(my_json, :symbolize_names => true)

AngularJS $http-post - convert binary to excel file and download

I created a service that will do this for you.

Pass in a standard $http object, and add some extra parameters.

1) A "type" parameter. Specifying the type of file you're retrieving. Defaults to: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
2) A "fileName" parameter. This is required, and should include the extension.

Example:

httpDownloader({
  method : 'POST',
  url : '--- enter the url that returns a file here ---',
  data : ifYouHaveDataEnterItHere,
  type : 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', // this is the default
  fileName : 'YourFileName.xlsx'
}).then(res => {}).catch(e => {});

That's all you need. The file will be downloaded to the user's device without a popup.

Here's the git repo: https://github.com/stephengardner/ngHttpDownloader

What is the difference between .text, .value, and .value2?

.Text is the formatted cell's displayed value; .Value is the value of the cell possibly augmented with date or currency indicators; .Value2 is the raw underlying value stripped of any extraneous information.

range("A1") = Date
range("A1").numberformat = "yyyy-mm-dd"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
2018-06-14
6/14/2018 
43265 

range("A1") = "abc"
range("A1").numberformat = "_(_(_(@"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
   abc
abc
abc

range("A1") = 12
range("A1").numberformat = "0 \m\m"
debug.print range("A1").text
debug.print range("A1").value
debug.print range("A1").value2

'results from Immediate window
12 mm
12
12

If you are processing the cell's value then reading the raw .Value2 is marginally faster than .Value or .Text. If you are locating errors then .Text will return something like #N/A as text and can be compared to a string while .Value and .Value2 will choke comparing their returned value to a string. If you have some custom cell formatting applied to your data then .Text may be the better choice when building a report.

Assign pandas dataframe column dtypes

For those coming from Google (etc.) such as myself:

convert_objects has been deprecated since 0.17 - if you use it, you get a warning like this one:

FutureWarning: convert_objects is deprecated.  Use the data-type specific converters 
pd.to_datetime, pd.to_timedelta and pd.to_numeric.

You should do something like the following:

How to format DateTime to 24 hours time?

Use upper-case HH for 24h format:

String s = curr.ToString("HH:mm");

See DateTime.ToString Method.

Get the new record primary key ID from MySQL insert query?

Here what you are looking for !!!

select LAST_INSERT_ID()

This is the best alternative of SCOPE_IDENTITY() function being used in SQL Server.

You also need to keep in mind that this will only work if Last_INSERT_ID() is fired following by your Insert query. That is the query returns the id inserted in the schema. You can not get specific table's last inserted id.

For more details please go through the link The equivalent of SQLServer function SCOPE_IDENTITY() in mySQL?

String replacement in batch file

This works fine

@echo off    
set word=table    
set str=jump over the chair    
set rpl=%str:chair=%%word%    
echo %rpl%

what are the .map files used for in Bootstrap 3.x?

Map files (source maps) are there to de-reference minified code (css and javascript).

And they are mainly used to help developers debugging a production environment, because developers usually use minified files for production which makes it impossible to debug. Map files help them de-referencing the code to see how the original file looked like.

Prevent Sequelize from outputting SQL to the console on execution of query?

All of these answers are turned off the logging at creation time.

But what if we need to turn off the logging on runtime ?

By runtime i mean after initializing the sequelize object using new Sequelize(.. function.

I peeked into the github source, found a way to turn off logging in runtime.

// Somewhere your code, turn off the logging
sequelize.options.logging = false

// Somewhere your code, turn on the logging
sequelize.options.logging = true 

Pass by pointer & Pass by reference

In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.

Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.

Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.

References have a couple more advantages compared to pointers (e. g. they can't be NULL, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.

Set attribute without value

The attr() function is also a setter function. You can just pass it an empty string.

$('body').attr('data-body','');

An empty string will simply create the attribute with no value.

<body data-body>

Reference - http://api.jquery.com/attr/#attr-attributeName-value

attr( attributeName , value )

How to save and load numpy.array() data properly?

For a short answer you should use np.save and np.load. The advantages of these is that they are made by developers of the numpy library and they already work (plus are likely already optimized nicely) e.g.

import numpy as np
from pathlib import Path

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

np.save(path/'x', x)
np.save(path/'y', y)

x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')

print(x is x_loaded) # False
print(x == x_loaded) # [[ True  True  True  True  True]]

Expanded answer:

In the end it really depends in your needs because you can also save it human readable format (see this Dump a NumPy array into a csv file) or even with other libraries if your files are extremely large (see this best way to preserve numpy arrays on disk for an expanded discussion).

However, (making an expansion since you use the word "properly" in your question) I still think using the numpy function out of the box (and most code!) most likely satisfy most user needs. The most important reason is that it already works. Trying to use something else for any other reason might take you on an unexpectedly LONG rabbit hole to figure out why it doesn't work and force it work.

Take for example trying to save it with pickle. I tried that just for fun and it took me at least 30 minutes to realize that pickle wouldn't save my stuff unless I opened & read the file in bytes mode with wb. Took time to google, try thing, understand the error message etc... Small detail but the fact that it already required me to open a file complicated things in unexpected ways. To add that it required me to re-read this (which btw is sort of confusing) Difference between modes a, a+, w, w+, and r+ in built-in open function?.

So if there is an interface that meets your needs use it unless you have a (very) good reason (e.g. compatibility with matlab or for some reason your really want to read the file and printing in python really doesn't meet your needs, which might be questionable). Furthermore, most likely if you need to optimize it you'll find out later down the line (rather than spend ages debugging useless stuff like opening a simple numpy file).

So use the interface/numpy provide. It might not be perfect it's most likely fine, especially for a library that's been around as long as numpy.

I already spent the saving and loading data with numpy in a bunch of way so have fun with it, hope it helps!

import numpy as np
import pickle
from pathlib import Path

path = Path('~/data/tmp/').expanduser()
path.mkdir(parents=True, exist_ok=True)

lb,ub = -1,1
num_samples = 5
x = np.random.uniform(low=lb,high=ub,size=(1,num_samples))
y = x**2 + x + 2

# using save (to npy), savez (to npz)
np.save(path/'x', x)
np.save(path/'y', y)
np.savez(path/'db', x=x, y=y)
with open(path/'db.pkl', 'wb') as db_file:
    pickle.dump(obj={'x':x, 'y':y}, file=db_file)

## using loading npy, npz files
x_loaded = np.load(path/'x.npy')
y_load = np.load(path/'y.npy')
db = np.load(path/'db.npz')
with open(path/'db.pkl', 'rb') as db_file:
    db_pkl = pickle.load(db_file)

print(x is x_loaded)
print(x == x_loaded)
print(x == db['x'])
print(x == db_pkl['x'])
print('done')

Some comments on what I learned:

  • np.save as expected, this already compresses it well (see https://stackoverflow.com/a/55750128/1601580), works out of the box without any file opening. Clean. Easy. Efficient. Use it.
  • np.savez uses a uncompressed format (see docs) Save several arrays into a single file in uncompressed .npz format. If you decide to use this (you were warned to go away from the standard solution so expect bugs!) you might discover that you need to use argument names to save it, unless you want to use the default names. So don't use this if the first already works (or any works use that!)
  • Pickle also allows for arbitrary code execution. Some people might not want to use this for security reasons.
  • human readable files are expensive to make etc. Probably not worth it.
  • there is something called hdf5 for large files. Cool! https://stackoverflow.com/a/9619713/1601580

Note this is not an exhaustive answer. But for other resources check this:

SQLSTATE[42S22]: Column not found: 1054 Unknown column - Laravel

Try to change where Member class

public function users() {
    return $this->hasOne('User');
} 

return $this->belongsTo('User');

Can't install any packages in Node.js using "npm install"

npm set registry http://85.10.209.91/

(this proxy fetches the original data from registry.npmjs.org and manipulates the tarball urls to fix the tarball file structure issue).

The other solutions seem to have outdated versions.

On a CSS hover event, can I change another div's styling?

A pure solution without jQuery:

Javascript (Head)

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
}   

HTML (Body)

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>

JSFiddle: http://jsfiddle.net/YShs2/

Cleanest Way to Invoke Cross-Thread Events

I made the following 'universal' cross thread call class for my own purpose, but I think it's worth to share it:

using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace CrossThreadCalls
{
  public static class clsCrossThreadCalls
  {
    private delegate void SetAnyPropertyCallBack(Control c, string Property, object Value);
    public static void SetAnyProperty(Control c, string Property, object Value)
    {
      if (c.GetType().GetProperty(Property) != null)
      {
        //The given property exists
        if (c.InvokeRequired)
        {
          SetAnyPropertyCallBack d = new SetAnyPropertyCallBack(SetAnyProperty);
          c.BeginInvoke(d, c, Property, Value);
        }
        else
        {
          c.GetType().GetProperty(Property).SetValue(c, Value, null);
        }
      }
    }

    private delegate void SetTextPropertyCallBack(Control c, string Value);
    public static void SetTextProperty(Control c, string Value)
    {
      if (c.InvokeRequired)
      {
        SetTextPropertyCallBack d = new SetTextPropertyCallBack(SetTextProperty);
        c.BeginInvoke(d, c, Value);
      }
      else
      {
        c.Text = Value;
      }
    }
  }

And you can simply use SetAnyProperty() from another thread:

CrossThreadCalls.clsCrossThreadCalls.SetAnyProperty(lb_Speed, "Text", KvaserCanReader.GetSpeed.ToString());

In this example the above KvaserCanReader class runs its own thread and makes a call to set the text property of the lb_Speed label on the main form.

Using headers with the Python requests library's get method

According to the API, the headers can all be passed in using requests.get:

import requests
r=requests.get("http://www.example.com/", headers={"content-type":"text"})

Python subprocess/Popen with a modified environment

In certain circumstances you may want to only pass down the environment variables your subprocess needs, but I think you've got the right idea in general (that's how I do it too).

Saving a text file on server using JavaScript

It's not possible to save content to the website using only client-side scripting such as JavaScript and jQuery, but by submitting the data in an AJAX POST request you could perform the other half very easily on the server-side.

However, I would not recommend having raw content such as scripts so easily writeable to your hosting as this could easily be exploited. If you want to learn more about AJAX POST requests, you can read the jQuery API page:

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

And here are some things you ought to be aware of if you still want to save raw script files on your hosting. You have to be very careful with security if you are handling files like this!

File uploading (most of this applies if sending plain text too if javascript can choose the name of the file) http://www.developershome.com/wap/wapUpload/wap_upload.asp?page=security https://www.owasp.org/index.php/Unrestricted_File_Upload

How is a JavaScript hash map implemented?

JavaScript objects cannot be implemented purely on top of hash maps.

Try this in your browser console:

var foo = {
    a: true,
    b: true,
    z: true,
    c: true
}

for (var i in foo) {
    console.log(i);
}

...and you'll recieve them back in insertion order, which is de facto standard behaviour.

Hash maps inherently do not maintain ordering, so JavaScript implementations may use hash maps somehow, but if they do, it'll require at least a separate index and some extra book-keeping for insertions.

Here's a video of Lars Bak explaining why v8 doesn't use hash maps to implement objects.

jQuery issue - #<an Object> has no method

This usually has to do with a selector not being used properly. Check and make sure that you are using the jQuery selectors like intended. For example I had this problem when creating a click method:

$("[editButton]").click(function () {
    this.css("color", "red");
});

Because I was not using the correct selector method $(this) for jQuery it gave me the same error.

So simply enough, check your selectors!

Android Shared preferences for creating one time activity (example)

Shared Preferences is so easy to learn, so take a look on this simple tutorial about sharedpreference

import android.os.Bundle;
import android.preference.PreferenceActivity;

    public class UserSettingActivity extends PreferenceActivity {

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

      addPreferencesFromResource(R.xml.settings);

    }
}

Convert a hexadecimal string to an integer efficiently in C?

If you don't have the stdlib then you have to do it manually.

unsigned long hex2int(char *a, unsigned int len)
{
    int i;
    unsigned long val = 0;

    for(i=0;i<len;i++)
       if(a[i] <= 57)
        val += (a[i]-48)*(1<<(4*(len-1-i)));
       else
        val += (a[i]-55)*(1<<(4*(len-1-i)));

    return val;
}

Note: This code assumes uppercase A-F. It does not work if len is beyond your longest integer 32 or 64bits, and there is no error trapping for illegal hex characters.

How link to any local file with markdown syntax?

How are you opening the rendered Markdown?

If you host it over HTTP, i.e. you access it via http:// or https://, most modern browsers will refuse to open local links, e.g. with file://. This is a security feature:

For security purposes, Mozilla applications block links to local files (and directories) from remote files. This includes linking to files on your hard drive, on mapped network drives, and accessible via Uniform Naming Convention (UNC) paths. This prevents a number of unpleasant possibilities, including:

  • Allowing sites to detect your operating system by checking default installation paths
  • Allowing sites to exploit system vulnerabilities (e.g., C:\con\con in Windows 95/98)
  • Allowing sites to detect browser preferences or read sensitive data

There are some workarounds listed on that page, but my recommendation is to avoid doing this if you can.

PHP not displaying errors even though display_errors = On

When you update the configuration in the php.ini file, you might have to restart apache. Try running apachectl restart or apache2ctl restart, or something like that.

Also, in you ini file, make sure you have display_errors = on, but only in a development environment, never in a production machine.

Also, the strictest error reporting is exactly what you have cited, E_ALL | E_STRICT. You can find more information on error levels at the php docs.

HTML table with 100% width, with vertical scroll inside tbody

Create two tables one after other, put second table in a div of fixed height and set the overflow property to auto. Also keep all the td's inside thead in second table empty.

<div>
    <table>
        <thead>
            <tr>
                <th>Head 1</th>
                <th>Head 2</th>
                <th>Head 3</th>
                <th>Head 4</th>
                <th>Head 5</th>
            </tr>
        </thead>
    </table>
</div>

<div style="max-height:500px;overflow:auto;">
    <table>
        <thead>
            <tr>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <tr>
            <td>Content 1</td>
            <td>Content 2</td>
            <td>Content 3</td>
            <td>Content 4</td>
            <td>Content 5</td>
        </tr>
        </tbody>
    </table>    
</div>

What are .dex files in Android?

.dex file

Compiled Android application code file.

Android programs are compiled into .dex (Dalvik Executable) files, which are in turn zipped into a single .apk file on the device. .dex files can be created automatically by Android, by translating the compiled applications written in the Java programming language.

How to add background-image using ngStyle (angular2)?

My background image wasn't working because the URL had a space in it and thus I needed to URL encode it.

You can check if this is the issue you're having by trying a different image URL that doesn't have characters that need escaping.

You could do this to the data in the component just using Javascripts built in encodeURI() method.

Personally I wanted to create a pipe for it so that it could be used in the template.

To do this you can create a very simple pipe. For example:

src/app/pipes/encode-uri.pipe.ts

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'encodeUri'
})
export class EncodeUriPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return encodeURI(value);
  }
}

src/app/app.module.ts

import { EncodeUriPipe } from './pipes/encode-uri.pipe';
...

@NgModule({
  imports: [
    BrowserModule,
    AppRoutingModule
    ...
  ],
  exports: [
    ...
  ],
 declarations: [
    AppComponent,
    EncodeUriPipe
 ],
 bootstrap: [ AppComponent ]
})

export class AppModule { }

src/app/app.component.ts

import {Component} from '@angular/core';

@Component({
  // tslint:disable-next-line
  selector: 'body',
  template: '<router-outlet></router-outlet>'
})
export class AppComponent {
  myUrlVariable: string;
  constructor() {
    this.myUrlVariable = 'http://myimagewith space init.com';
  }
}

src/app/app.component.html

<div [style.background-image]="'url(' + (myUrlVariable | encodeUri) + ')'" ></div>

Java - Get a list of all Classes loaded in the JVM

Well, what I did was simply listing all the files in the classpath. It may not be a glorious solution, but it works reliably and gives me everything I want, and more.

How to pass an ArrayList to a varargs method parameter?

A shorter version of the accepted answer using Guava:

.getMap(Iterables.toArray(locations, WorldLocation.class));

can be shortened further by statically importing toArray:

import static com.google.common.collect.toArray;
// ...

    .getMap(toArray(locations, WorldLocation.class));

Remove Elements from a HashSet while Iterating

Java 8 Collection has a nice method called removeIf that makes things easier and safer. From the API docs:

default boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate. 
Errors or runtime exceptions thrown during iteration or by the predicate 
are relayed to the caller.

Interesting note:

The default implementation traverses all elements of the collection using its iterator(). 
Each matching element is removed using Iterator.remove().

From: https://docs.oracle.com/javase/8/docs/api/java/util/Collection.html#removeIf-java.util.function.Predicate-

git diff between cloned and original remote repository

This example might help someone:

Note "origin" is my alias for remote "What is on Github"
Note "mybranch" is my alias for my branch "what is local" that I'm syncing with github
--your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch to show where the branch name parameter is used.


What exactly are my remote repos on github?

$ git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)

Add the "other github repository of the same code" - we call this a fork:

$ git remote add someOtherRepo https://github.com/otherUser/Playground.git

$git remote -v
origin  https://github.com/flipmcf/Playground.git (fetch)
origin  https://github.com/flipmcf/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (push)
someOtherRepo https://github.com/otherUser/Playground.git (fetch)

make sure our local repo is up to date:

$ git fetch

Change some stuff locally. let's say file ./foo/bar.py

$ git status
# On branch mybranch
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
#   modified:   foo/bar.py

Review my uncommitted changes

$ git diff mybranch
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index b4fb1be..516323b 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

Commit locally.

$ git commit foo/bar.py -m"I changed stuff"
[myfork 9f31ff7] I changed stuff
1 files changed, 2 insertions(+), 1 deletions(-)

Now, I'm different than my remote (on github)

$ git status
# On branch mybranch
# Your branch is ahead of 'origin/mybranch' by 1 commit.
#
nothing to commit (working directory clean)

Diff this with remote - your fork: (this is frequently done with git diff master origin)

$ git diff mybranch origin
diff --git a/playground/foo/bar.py b/playground/foo/bar.py
index 516323b..b4fb1be 100655
--- a/playground/foo/bar.py
+++ b/playground/foo/bar.py
@@ -1,27 +1,29 @@
- This line is wrong
+ This line is fixed now - yea!
+ And I added this line too.

(git push to apply these to remote)

How does my remote branch differ from the remote master branch?

$ git diff origin/mybranch origin/master

How does my local stuff differ from the remote master branch?

$ git diff origin/master

How does my stuff differ from someone else's fork, master branch of the same repo?

$git diff mybranch someOtherRepo/master

Remove all multiple spaces in Javascript and replace with single space

You could use a regular expression replace:

str = str.replace(/ +(?= )/g,'');

Credit: The above regex was taken from Regex to replace multiple spaces with a single space

jQuery DIV click, with anchors

If you return "false" from your function it'll stop the event bubbling, so only your first event handler will get triggered (ie. your anchor will not see the click).

$("div.clickable").click(
function()
{
    window.location = $(this).attr("url");
    return false;
});

See event.preventDefault() vs. return false for details on return false vs. preventDefault.

Simple Java Client/Server Program

If you got your IP address from an external web site (http://whatismyipaddress.com/), you have your external IP address. If your server is on the same local network, you may need an internal IP address instead. Local IP addresses look like 10.X.X.X, 172.X.X.X, or 192.168.X.X.

Try the suggestions on this page to find what your machine thinks its IP address is.

Rename column SQL Server 2008

Try:

EXEC sp_rename 'TableName.OldName', 'NewName', 'COLUMN'

Download a file from HTTPS using download.file()

Here's an update as of Nov 2014. I find that setting method='curl' did the trick for me (while method='auto', does not).

For example:

# does not work
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
              destfile='localfile.zip')

# does not work. this appears to be the default anyway
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
              destfile='localfile.zip', method='auto')

# works!
download.file(url='https://s3.amazonaws.com/tripdata/201307-citibike-tripdata.zip',
              destfile='localfile.zip', method='curl')

<modules runAllManagedModulesForAllRequests="true" /> Meaning

Modules Preconditions:

The IIS core engine uses preconditions to determine when to enable a particular module. Performance reasons, for example, might determine that you only want to execute managed modules for requests that also go to a managed handler. The precondition in the following example (precondition="managedHandler") only enables the forms authentication module for requests that are also handled by a managed handler, such as requests to .aspx or .asmx files:

<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" preCondition="managedHandler" />

If you remove the attribute precondition="managedHandler", Forms Authentication also applies to content that is not served by managed handlers, such as .html, .jpg, .doc, but also for classic ASP (.asp) or PHP (.php) extensions. See "How to Take Advantage of IIS Integrated Pipeline" for an example of enabling ASP.NET modules to run for all content.

You can also use a shortcut to enable all managed (ASP.NET) modules to run for all requests in your application, regardless of the "managedHandler" precondition.

To enable all managed modules to run for all requests without configuring each module entry to remove the "managedHandler" precondition, use the runAllManagedModulesForAllRequests property in the <modules> section:

<modules runAllManagedModulesForAllRequests="true" />    

When you use this property, the "managedHandler" precondition has no effect and all managed modules run for all requests.

Copied from IIS Modules Overview: Preconditions

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

.NET End vs Form.Close() vs Application.Exit Cleaner way to close one's app

If you are in a loop (Do While, For, ...) and you call Me.Close(), you should follow with an Exit command (Exit Do, ...) or a Return() to force the message processing to terminate properly. I caught programs hanging due to this.

HTML button calling an MVC Controller and Action method

You can use Url.Action to specify generate the url to a controller action, so you could use either of the following:

<form method="post" action="<%: Url.Action("About", "Home") %>">
   <input type="submit" value="Click me to go to /Home/About" />
</form>

or:

<form action="#">
  <input type="submit" onclick="parent.location='<%: Url.Action("About", "Home") %>';return false;" value="Click me to go to /Home/About" />
  <input type="submit" onclick="parent.location='<%: Url.Action("Register", "Account") %>';return false;" value="Click me to go to /Account/Register" />
</form>

Measure execution time for a Java method

You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.


From "Java Platform Performance: Strategies and Tactics" book:

With System.currentTimeMillis()

class TimeTest1 {
   public static void main(String[] args) {

      long startTime = System.currentTimeMillis();

      long total = 0;
      for (int i = 0; i < 10000000; i++) {
         total += i;
      }

      long stopTime = System.currentTimeMillis();
      long elapsedTime = stopTime - startTime;
      System.out.println(elapsedTime);
   }
}

With a StopWatch class

You can use this StopWatch class, and call start() and stop before and after the method.

class TimeTest2 {
   public static void main(String[] args) {

      Stopwatch timer = new Stopwatch().start();

      long total = 0;
      for (int i = 0; i < 10000000; i++) {
         total += i;
      }

      timer.stop();
      System.out.println(timer.getElapsedTime());
   }
}

See here (archived).


NetBeans Profiler:

Application Performance Application

Performance profiles method-level CPU performance (execution time). You can choose to profile the entire application or a part of the application.

See here.

JPA eager fetch does not join

The fetchType attribute controls whether the annotated field is fetched immediately when the primary entity is fetched. It does not necessarily dictate how the fetch statement is constructed, the actual sql implementation depends on the provider you are using toplink/hibernate etc.

If you set fetchType=EAGER This means that the annotated field is populated with its values at the same time as the other fields in the entity. So if you open an entitymanager retrieve your person objects and then close the entitymanager, subsequently doing a person.address will not result in a lazy load exception being thrown.

If you set fetchType=LAZY the field is only populated when it is accessed. If you have closed the entitymanager by then a lazy load exception will be thrown if you do a person.address. To load the field you need to put the entity back into an entitymangers context with em.merge(), then do the field access and then close the entitymanager.

You might want lazy loading when constructing a customer class with a collection for customer orders. If you retrieved every order for a customer when you wanted to get a customer list this may be a expensive database operation when you only looking for customer name and contact details. Best to leave the db access till later.

For the second part of the question - how to get hibernate to generate optimised SQL?

Hibernate should allow you to provide hints as to how to construct the most efficient query but I suspect there is something wrong with your table construction. Is the relationship established in the tables? Hibernate may have decided that a simple query will be quicker than a join especially if indexes etc are missing.

FormData.append("key", "value") is not working

New in Chrome 50+ and Firefox 39+ (resp. 44+):

  • formdata.entries() (combine with Array.from() for debugability)
  • formdata.get(key)
  • and more very useful methods

Original answer:

What I usually do to 'debug' a FormData object, is just send it (anywhere!) and check the browser logs (eg. Chrome devtools' Network tab).

You don't need a/the same Ajax framework. You don't need any details. Just send it:

var xhr = new XMLHttpRequest;
xhr.open('POST', '/', true);
xhr.send(data);

Easy.

How to post raw body data with curl?

curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/

Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

enter image description here

ValueError: cannot reshape array of size 30470400 into shape (50,1104,104)

In Matrix terms, the number of elements always has to equal the product of the number of rows and columns. In this particular case, the condition is not matching.

How to create many labels and textboxes dynamically depending on the value of an integer variable?

I would create a user control which holds a Label and a Text Box in it and simply create instances of that user control 'n' times. If you want to know a better way to do it and use properties to get access to the values of Label and Text Box from the user control, please let me know.

Simple way to do it would be:

int n = 4; // Or whatever value - n has to be global so that the event handler can access it

private void btnDisplay_Click(object sender, EventArgs e)
{
    TextBox[] textBoxes = new TextBox[n];
    Label[] labels = new Label[n];

    for (int i = 0; i < n; i++)
    {
        textBoxes[i] = new TextBox();
        // Here you can modify the value of the textbox which is at textBoxes[i]

        labels[i] = new Label();
        // Here you can modify the value of the label which is at labels[i]
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(textBoxes[i]);
        this.Controls.Add(labels[i]);
    }
}

The code above assumes that you have a button btnDisplay and it has a onClick event assigned to btnDisplay_Click event handler. You also need to know the value of n and need a way of figuring out where to place all controls. Controls should have a width and height specified as well.

To do it using a User Control simply do this.

Okay, first of all go and create a new user control and put a text box and label in it.

Lets say they are called txtSomeTextBox and lblSomeLabel. In the code behind add this code:

public string GetTextBoxValue() 
{ 
    return this.txtSomeTextBox.Text; 
} 

public string GetLabelValue() 
{ 
    return this.lblSomeLabel.Text; 
} 

public void SetTextBoxValue(string newText) 
{ 
    this.txtSomeTextBox.Text = newText; 
} 

public void SetLabelValue(string newText) 
{ 
    this.lblSomeLabel.Text = newText; 
}

Now the code to generate the user control will look like this (MyUserControl is the name you have give to your user control):

private void btnDisplay_Click(object sender, EventArgs e)
{
    MyUserControl[] controls = new MyUserControl[n];

    for (int i = 0; i < n; i++)
    {
        controls[i] = new MyUserControl();

        controls[i].setTextBoxValue("some value to display in text");
        controls[i].setLabelValue("some value to display in label");
        // Now if you write controls[i].getTextBoxValue() it will return "some value to display in text" and controls[i].getLabelValue() will return "some value to display in label". These value will also be displayed in the user control.
    }

    // This adds the controls to the form (you will need to specify thier co-ordinates etc. first)
    for (int i = 0; i < n; i++)
    {
        this.Controls.Add(controls[i]);
    }
}

Of course you can create more methods in the usercontrol to access properties and set them. Or simply if you have to access a lot, just put in these two variables and you can access the textbox and label directly:

public TextBox myTextBox;
public Label myLabel;

In the constructor of the user control do this:

myTextBox = this.txtSomeTextBox;
myLabel = this.lblSomeLabel;

Then in your program if you want to modify the text value of either just do this.

control[i].myTextBox.Text = "some random text"; // Same applies to myLabel

Hope it helped :)

Open a URL in a new tab (and not a new window)

Whether to open the URL in a new tab or a new window, is actually controlled by the user's browser preferences. There is no way to override it in JavaScript.

window.open() behaves differently depending on how it is being used. If it is called as a direct result of a user action, let us say a button click, it should work fine and open a new tab (or window):

const button = document.querySelector('#openTab');

// add click event listener
button.addEventListener('click', () => {
    // open a new tab
    const tab = window.open('https://attacomsian.com', '_blank');
});

However, if you try to open a new tab from an AJAX request callback, the browser will block it as it was not a direct user action.

To bypass the popup blocker and open a new tab from a callback, here is a little hack:

const button = document.querySelector('#openTab');

// add click event listener
button.addEventListener('click', () => {

    // open an empty window
    const tab = window.open('about:blank');

    // make an API call
    fetch('/api/validate')
        .then(res => res.json())
        .then(json => {

            // TODO: do something with JSON response

            // update the actual URL
            tab.location = 'https://attacomsian.com';
            tab.focus();
        })
        .catch(err => {
            // close the empty window
            tab.close();
        });
});

Authentication failed for https://xxx.visualstudio.com/DefaultCollection/_git/project

I've tried lots of options, but the one that worked for me was to:

  1. Download the Git Password Manager from its Releases section

  2. Try to do simple git fetch which will automatically bring the window(alternate to default windows one for example) and ask to enter username and password but with more elegant way than the standard one.

After correctly entering the credentials it worked, though I was getting an error before.

P.S. If you are getting "Wrong Credentials" kind of errors always check if the repository username and password are correct. If you hesitate just reset the password and try to use the same one in the Git Password manager window.

LINQ to read XML

A couple of plain old foreach loops provides a clean solution:

foreach (XElement level1Element in XElement.Load("data.xml").Elements("level1"))
{
    result.AppendLine(level1Element.Attribute("name").Value);

    foreach (XElement level2Element in level1Element.Elements("level2"))
    {
        result.AppendLine("  " + level2Element.Attribute("name").Value);
    }
}

How can I get the active screen dimensions?

Beware of the scale factor of your windows (100% / 125% / 150% / 200%). You can get the real screen size by using the following code:

SystemParameters.FullPrimaryScreenHeight
SystemParameters.FullPrimaryScreenWidth

Keep a line of text as a single line - wrap the whole line or none at all

You could also put non-breaking spaces (&nbsp;) in lieu of the spaces so that they're forced to stay together.

How do I wrap this line of text
-&nbsp;asked&nbsp;by&nbsp;Peter&nbsp;2&nbsp;days&nbsp;ago

Is it possible for UIStackView to scroll?

I was looking to do the same thing and stumbled upon this excellent post. If you want to do this programmatically using the anchor API, this is the way to go.

To summarize, embed your UIStackView in your UIScrollView, and set the anchor constraints of the UIStackView to match those of the UIScrollView:

stackView.leadingAnchor.constraintEqualToAnchor(scrollView.leadingAnchor).active = true
stackView.trailingAnchor.constraintEqualToAnchor(scrollView.trailingAnchor).active = true
stackView.bottomAnchor.constraintEqualToAnchor(scrollView.bottomAnchor).active = true
stackView.topAnchor.constraintEqualToAnchor(scrollView.topAnchor).active = true
stackView.widthAnchor.constraintEqualToAnchor(scrollView.widthAnchor).active = true

How can I clear an HTML file input with JavaScript?

The above answers offer somewhat clumsy solutions for the following reasons:

  1. I don't like having to wrap the input first and then getting the html, it is very involved and dirty.

  2. Cross browser JS is handy and it seems that in this case there are too many unknowns to reliably use type switching (which, again, is a bit dirty) and setting value to ''

So I offer you my jQuery based solution:

$('#myinput').replaceWith($('#myinput').clone())

It does what it says, it replaces the input with a clone of itself. The clone won't have the file selected.

Advantages:

  1. Simple and understandable code
  2. No clumsy wrapping or type switching
  3. Cross browser compatibility (correct me if I am wrong here)

Result: Happy programmer