Programs & Examples On #Puremvc

PureMVC is a lightweight framework for creating applications based upon the classic Model, View and Controller concept.

Getting the SQL from a Django QuerySet

The accepted answer did not work for me when using Django 1.4.4. Instead of the raw query, a reference to the Query object was returned: <django.db.models.sql.query.Query object at 0x10a4acd90>.

The following returned the query:

>>> queryset = MyModel.objects.all()
>>> queryset.query.__str__()

Set TextView text from html-formatted string resource in XML

As the top answer here is suggesting something wrong (or at least too complicated), I feel this should be updated, although the question is quite old:

When using String resources in Android, you just have to call getString(...) from Java code or use android:text="@string/..." in your layout XML.

Even if you want to use HTML markup in your Strings, you don't have to change a lot:

The only characters that you need to escape in your String resources are:

  • double quotation mark: " becomes \"
  • single quotation mark: ' becomes \'
  • ampersand: & becomes &#38; or &amp;

That means you can add your HTML markup without escaping the tags:

<string name="my_string"><b>Hello World!</b> This is an example.</string>

However, to be sure, you should only use <b>, <i> and <u> as they are listed in the documentation.

If you want to use your HTML strings from XML, just keep on using android:text="@string/...", it will work fine.

The only difference is that, if you want to use your HTML strings from Java code, you have to use getText(...) instead of getString(...) now, as the former keeps the style and the latter will just strip it off.

It's as easy as that. No CDATA, no Html.fromHtml(...).

You will only need Html.fromHtml(...) if you did encode your special characters in HTML markup. Use it with getString(...) then. This can be necessary if you want to pass the String to String.format(...).

This is all described in the docs as well.

Edit:

There is no difference between getText(...) with unescaped HTML (as I've proposed) or CDATA sections and Html.fromHtml(...).

See the following graphic for a comparison:

enter image description here

Generating a random password in php

Tiny code with 2 line.

demo: http://codepad.org/5rHMHwnH

function rand_string( $length ) {

    $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    return substr(str_shuffle($chars),0,$length);

}

echo rand_string(8);

with rand_string you can define how much character will be create.

Running JAR file on Windows

In Windows Vista or Windows 7, the manual file association editor has been removed.

The easiest way is to run Jarfix, a tiny but powerful freeware tool. Just run it and your Java apps is back... double-clickable again.

What is the difference between String and string in C#?

I prefer the capitalized .NET types (rather than the aliases) for formatting reasons. The .NET types are colored the same as other object types (the value types are proper objects, after all).

Conditional and control keywords (like if, switch, and return) are lowercase and colored dark blue (by default). And I would rather not have the disagreement in use and format.

Consider:

String someString; 
string anotherString; 

Jquery to change form action

Use jQuery.attr() in your click handler:

$("#myform").attr('action', 'page1.php');

How can I use external JARs in an Android project?

Turns out I have not looked good enough at my stack trace, the problem is not that the external JAR is not included.

The problem is that Android platform is missing javax.naming.* and many other packages that the external JAR has dependencies too.

Adding external JAR files, and setting Order and Export in Eclipse works as expected with Android projects.

How to put php inside JavaScript?

All the explanations above doesn't work if you work with .js files. If you want to parse PHP into .js files, you have to make changes on your server by modfiying the .htaccess in which the .js files reside using the following commands:

<FilesMatch "\.(js)$">
    AddHandler application/x-httpd-php .js
</FilesMatch>

Then, a file test.js files containing the following code will execute .JS on client side with the parsed PHP on server-side:

<html>
<head>
<script>
function myFunction(){
   alert("Hello World!");
}
</script>
</head>
<body>
<button onclick="myFunction()"><?php echo "My button";?></button>
</body>
</html>

Declaring an unsigned int in Java

There are good answers here, but I don’t see any demonstrations of bitwise operations. Like Visser (the currently accepted answer) says, Java signs integers by default (Java 8 has unsigned integers, but I have never used them). Without further ado, let‘s do it...

RFC 868 Example

What happens if you need to write an unsigned integer to IO? Practical example is when you want to output the time according to RFC 868. This requires a 32-bit, big-endian, unsigned integer that encodes the number of seconds since 12:00 A.M. January 1, 1900. How would you encode this?

Make your own unsigned 32-bit integer like this:

Declare a byte array of 4 bytes (32 bits)

Byte my32BitUnsignedInteger[] = new Byte[4] // represents the time (s)

This initializes the array, see Are byte arrays initialised to zero in Java?. Now you have to fill each byte in the array with information in the big-endian order (or little-endian if you want to wreck havoc). Assuming you have a long containing the time (long integers are 64 bits long in Java) called secondsSince1900 (Which only utilizes the first 32 bits worth, and you‘ve handled the fact that Date references 12:00 A.M. January 1, 1970), then you can use the logical AND to extract bits from it and shift those bits into positions (digits) that will not be ignored when coersed into a Byte, and in big-endian order.

my32BitUnsignedInteger[0] = (byte) ((secondsSince1900 & 0x00000000FF000000L) >> 24); // first byte of array contains highest significant bits, then shift these extracted FF bits to first two positions in preparation for coersion to Byte (which only adopts the first 8 bits)
my32BitUnsignedInteger[1] = (byte) ((secondsSince1900 & 0x0000000000FF0000L) >> 16);
my32BitUnsignedInteger[2] = (byte) ((secondsSince1900 & 0x000000000000FF00L) >> 8);
my32BitUnsignedInteger[3] = (byte) ((secondsSince1900 & 0x00000000000000FFL); // no shift needed

Our my32BitUnsignedInteger is now equivalent to an unsigned 32-bit, big-endian integer that adheres to the RCF 868 standard. Yes, the long datatype is signed, but we ignored that fact, because we assumed that the secondsSince1900 only used the lower 32 bits). Because of coersing the long into a byte, all bits higher than 2^7 (first two digits in hex) will be ignored.

Source referenced: Java Network Programming, 4th Edition.

How do I select elements of an array given condition?

Actually I would do it this way:

L1 is the index list of elements satisfying condition 1;(maybe you can use somelist.index(condition1) or np.where(condition1) to get L1.)

Similarly, you get L2, a list of elements satisfying condition 2;

Then you find intersection using intersect(L1,L2).

You can also find intersection of multiple lists if you get multiple conditions to satisfy.

Then you can apply index in any other array, for example, x.

Sound effects in JavaScript / HTML5

Here's an idea. Load all of your audio for a certain class of sounds into a single individual audio element where the src data is all of your samples in a contiguous audio file (probably want some silence between so you can catch and cut the samples with a timeout with less risk of bleeding to the next sample). Then, seek to the sample and play it when needed.

If you need more than one of these to play you can create an additional audio element with the same src so that it is cached. Now, you effectively have multiple "tracks". You can utilize groups of tracks with your favorite resource allocation scheme like Round Robin etc.

You could also specify other options like queuing sounds into a track to play when that resource becomes available or cutting a currently playing sample.

Angular 4 checkbox change value

I am guessing that this is what something you are trying to achieve.

<input type="checkbox" value="a" (click)="click($event)">A
<input type="checkbox" value="b" (click)="click($event)">B

click(ev){
   console.log(ev.target.defaultValue);
}

c++ exception : throwing std::string

In addition to probably throwing something derived from std::exception you should throw anonymous temporaries and catch by reference:

void Foo::Bar(){
  if(!QueryPerformanceTimer(&m_baz)){
    throw std::string("it's the end of the world!");
  }
}

void Foo:Caller(){
  try{
    this->Bar();// should throw
  }catch(std::string& caught){ // not quite sure the syntax is ok here...
    std::cout<<"Got "<<caught<<std::endl;
  }
}
  • You should throw anonymous temporaries so the compiler deals with the object lifetime of whatever you're throwing - if you throw something new-ed off the heap, someone else needs to free the thing.
  • You should catch references to prevent object slicing

.

See Meyer's "Effective C++ - 3rd edition" for details or visit https://www.securecoding.cert.org/.../ERR02-A.+Throw+anonymous+temporaries+and+catch+by+reference

how to find all indexes and their columns for tables, views and synonyms in oracle

SELECT * FROM user_cons_columns WHERE table_name = 'table_name';

How do I make a delay in Java?

Use Thread.sleep(100);. The unit of time is milliseconds

For example:

public class SleepMessages {
    public static void main(String args[])
        throws InterruptedException {
        String importantInfo[] = {
            "Mares eat oats",
            "Does eat oats",
            "Little lambs eat ivy",
            "A kid will eat ivy too"
        };

        for (int i = 0;
             i < importantInfo.length;
             i++) {
            //Pause for 4 seconds
            Thread.sleep(4000);
            //Print a message
            System.out.println(importantInfo[i]);
        }
    }
}

"Please try running this command again as Root/Administrator" error when trying to install LESS

npm has an official page about fixing npm permissions when you get the EACCES (Error: Access) error. The page even has a video.

You can fix this problem using one of two options:

  1. Change the permission to npm's default directory.
  2. Change npm's default directory to another directory.

How can I get the image url in a Wordpress theme?

I had to use Stylesheet directory to work for me.

<img src="<?php echo get_stylesheet_directory_uri(); ?>/images/image.png">

Gunicorn worker timeout error

We had the same problem using Django+nginx+gunicorn. From Gunicorn documentation we have configured the graceful-timeout that made almost no difference.

After some testings, we found the solution, the parameter to configure is: timeout (And not graceful timeout). It works like a clock..

So, Do:

1) open the gunicorn configuration file

2) set the TIMEOUT to what ever you need - the value is in seconds

NUM_WORKERS=3
TIMEOUT=120

exec gunicorn ${DJANGO_WSGI_MODULE}:application \
--name $NAME \
--workers $NUM_WORKERS \
--timeout $TIMEOUT \
--log-level=debug \
--bind=127.0.0.1:9000 \
--pid=$PIDFILE

Show/Hide the console window of a C# console application

"Just to hide" you can:

Change the output type from Console Application to Windows Application,

And Instead of Console.Readline/key you can use new ManualResetEvent(false).WaitOne() at the end to keep the app running.

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

How to search multiple columns in MySQL?

If it is just for searching then you may be able to use CONCATENATE_WS. This would allow wild card searching. There may be performance issues depending on the size of the table.

SELECT * 
FROM pages 
WHERE CONCAT_WS('', column1, column2, column3) LIKE '%keyword%'

Javascript Get Values from Multiple Select Option Box

Take a look at HTMLSelectElement.selectedOptions.

HTML

<select name="north-america" multiple>
  <option valud="ca" selected>Canada</a>
  <option value="mx" selected>Mexico</a>
  <option value="us">USA</a>
</select>

JavaScript

var elem = document.querySelector("select");

console.log(elem.selectedOptions);
//=> HTMLCollection [<option value="ca">Canada</option>, <option value="mx">Mexico</option>]

This would also work on non-multiple <select> elements


Warning: Support for this selectedOptions seems pretty unknown at this point

Windows Forms ProgressBar: Easiest way to start/stop marquee?

There's a nice article with code on this topic on MSDN. I'm assuming that setting the Style property to ProgressBarStyle.Marquee is not appropriate (or is that what you are trying to control?? -- I don't think it is possible to stop/start this animation although you can control the speed as @Paul indicates).

How to get the last five characters of a string using Substring() in C#?

In C# 8.0 and later you can use [^5..] to get the last five characters combined with a ? operator to avoid a potential ArgumentOutOfRangeException.

string input1 = "0123456789";
string input2 = "0123";
Console.WriteLine(input1.Length >= 5 ? input1[^5..] : input1); //returns 56789
Console.WriteLine(input2.Length >= 5 ? input2[^5..] : input2); //returns 0123

index-from-end-operator and range-operator

How to query first 10 rows and next time query other 10 rows from table

LIMIT limit OFFSET offset will work.

But you need a stable ORDER BY clause, or the values may be ordered differently for the next call (after any write on the table for instance).

SELECT *
FROM   msgtable
WHERE  cdate = '2012-07-18'
ORDER  BY msgtable_id  -- or whatever is stable 
LIMIT  10
OFFSET 50;  -- to skip to page 6

Use standard-conforming date style (ISO 8601 in my example), which works irregardless of your locale settings.

Paging will still shift if involved rows are inserted or deleted or changed in relevant columns. It has to.

To avoid that shift or for better performance with big tables use smarter paging strategies:

Trust Anchor not found for Android SSL Connection

The solution of @Chrispix is dangerous! Trusting all certificates allows anybody to do a man in the middle attack! Just send ANY certificate to the client and it will accept it!

Add your certificate(s) to a custom trust manager like described in this post: Trusting all certificates using HttpClient over HTTPS

Although it is a bit more complex to establish a secure connection with a custom certificate, it will bring you the wanted ssl encryption security without the danger of man in the middle attack!

MatPlotLib: Multiple datasets on the same scatter plot

I don't know, it works fine for me. Exact commands:

import scipy, pylab
ax = pylab.subplot(111)
ax.scatter(scipy.randn(100), scipy.randn(100), c='b')
ax.scatter(scipy.randn(100), scipy.randn(100), c='r')
ax.figure.show()

How can I view an old version of a file with Git?

To quickly see the differences with older revisions of a file:

git show -1 filename.txt > to compare against the last revision of file

git show -2 filename.txt > to compare against the 2nd last revision

git show -3 fielname.txt > to compare against the last 3rd last revision

Cannot add or update a child row: a foreign key constraint fails

Yet another weird case that gave me this error. I had erroneously referenced my foreign keys to the id primary key. This was caused by incorrect alter table commands. I found this out by querying the INFORMATION_SCHEMA table (See this stackoverflow answer)

The table was so confused it could not be fixed by any ALTER TABLE commands. I finally dropped the table and reconstructed it. This got rid of the integrityError.

Difference between a theta join, equijoin and natural join

Natural is a subset of Equi which is a subset of Theta.

If I use the = sign on a theta join is it exactly the same as just using a natural join???

Not necessarily, but it would be an Equi. Natural means you are matching on all similarly named columns, Equi just means you are using '=' exclusively (and not 'less than', like, etc)

This is pure academia though, you could work with relational databases for years and never hear anyone use these terms.

How do I remove the blue styling of telephone numbers on iPhone/iOS?

Simple trick worked for me, adding a hidden object in the middle of phone number.

<span style="color: #fff;">
0800<i style="display:none;">-</i> 9996369</span>

This will help you to override phone number color for IOS.

How to see remote tags?

Even without cloning or fetching, you can check the list of tags on the upstream repo with git ls-remote:

git ls-remote --tags /url/to/upstream/repo

(as illustrated in "When listing git-ls-remote why there's “^{}” after the tag name?")

xbmono illustrates in the comments that quotes are needed:

git ls-remote --tags /some/url/to/repo "refs/tags/MyTag^{}"

Note that you can always push your commits and tags in one command with (git 1.8.3+, April 2013):

git push --follow-tags

See Push git commits & tags simultaneously.


Regarding Atlassian SourceTree specifically:

Note that, from this thread, SourceTree ONLY shows local tags.

There is an RFE (Request for Enhancement) logged in SRCTREEWIN-4015 since Dec. 2015.

A simple workaround:

see a list of only unpushed tags?

git push --tags

or check the "Push all tags" box on the "Push" dialog box, all tags will be pushed to your remote.

https://community.atlassian.com/tnckb94959/attachments/tnckb94959/sourcetree-questions/10923/1/Screen%20Shot%202015-12-15%20at%208.49.48%20AM.png

That way, you will be "sure that they are present in remote so that other developers can pull them".

Android Gradle Could not reserve enough space for object heap

I ran into the same issue, here's my post:

Android Studio - Gradle build failing - Java Heap Space

exec summary: Windows looks for the gradle.properties file here:

C:\Users\.gradle\gradle.properties

So create that file, and add a line like this:

org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m

as per @Faiz Siddiqui post

UnicodeDecodeError when reading CSV file in Pandas with Python

with open('filename.csv') as f:
   print(f)

after executing this code you will find encoding of 'filename.csv' then execute code as following

data=pd.read_csv('filename.csv', encoding="encoding as you found earlier"

there you go

What exactly is the 'react-scripts start' command?

As Sagiv b.g. pointed out, the npm start command is a shortcut for npm run start. I just wanted to add a real-life example to clarify it a bit more.

The setup below comes from the create-react-app github repo. The package.json defines a bunch of scripts which define the actual flow.

"scripts": {
  "start": "npm-run-all -p watch-css start-js",
  "build": "npm run build-css && react-scripts build",
  "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
  "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
  "start-js": "react-scripts start"
},

For clarity, I added a diagram. enter image description here

The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name> command. But as you can see, actually there are only 2 practical flows:

  • npm run start
  • npm run build

The grey boxes are commands which can be executed from the command line.

So, for instance, if you run npm start (or npm run start) that actually translate to the npm-run-all -p watch-css start-js command, which is executed from the commandline.

In my case, I have this special npm-run-all command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2> switch. So, here it executes 2 scripts, i.e. watch-css and start-js. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)

  • The watch-css makes sure that the *.scss files are translated to *.cssfiles, and looks for future updates.

  • The start-js points to the react-scripts start which hosts the website in a development mode.

In conclusion, the npm start command is configurable. If you want to know what it does, then you have to check the package.json file. (and you may want to make a little diagram when things get complicated).

HTTP authentication logout via PHP

Workaround (not a clean, nice (or even working! see comments) solution):

Disable his credentials one time.

You can move your HTTP authentication logic to PHP by sending the appropriate headers (if not logged in):

Header('WWW-Authenticate: Basic realm="protected area"');
Header('HTTP/1.0 401 Unauthorized');

And parsing the input with:

$_SERVER['PHP_AUTH_USER'] // httpauth-user
$_SERVER['PHP_AUTH_PW']   // httpauth-password

So disabling his credentials one time should be trivial.

Reading Email using Pop3 in C#

I've successfully used OpenPop.NET to access emails via POP3.

What's the difference between next() and nextLine() methods from Scanner class?

Both functions are used to move to the next Scanner token.

The difference lies in how the scanner token is generated

next() generates scanner tokens using delimiter as White Space

nextLine() generates scanner tokens using delimiter as '\n' (i.e Enter key presses)

How to get the current working directory using python 3?

Using pathlib you can get the folder in which the current file is located. __file__ is the pathname of the file from which the module was loaded. Ref: docs

import pathlib

current_dir = pathlib.Path(__file__).parent
current_file = pathlib.Path(__file__)

Doc ref: link

Printing hexadecimal characters in C

Indeed, there is type conversion to int. Also you can force type to char by using %hhx specifier.

printf("%hhX", a);

In most cases you will want to set the minimum length as well to fill the second character with zeroes:

printf("%02hhX", a);

ISO/IEC 9899:201x says:

7 The length modifiers and their meanings are: hh Specifies that a following d, i, o, u, x, or X conversion specifier applies to a signed char or unsigned char argument (the argument will have been promoted according to the integer promotions, but its value shall be converted to signed char or unsigned char before printing); or that a following

How to trigger SIGUSR1 and SIGUSR2?

They are user-defined signals, so they aren't triggered by any particular action. You can explicitly send them programmatically:

#include <signal.h>

kill(pid, SIGUSR1);

where pid is the process id of the receiving process. At the receiving end, you can register a signal handler for them:

#include <signal.h>

void my_handler(int signum)
{
    if (signum == SIGUSR1)
    {
        printf("Received SIGUSR1!\n");
    }
}

signal(SIGUSR1, my_handler);

How to compare two java objects

1) == evaluates reference equality in this case
2) im not too sure about the equals, but why not simply overriding the compare method and plant it inside MyClass?

ImportError: No module named _ssl

Unrelated to the original question, but because this is the first Google result... I hit this on Google AppEngine and had to add:

libraries:
- name: ssl
  version: latest

to app.yaml per: https://cloud.google.com/appengine/docs/python/sockets/ssl_support

Please NOTE: This seems to work upto Python version 2.7.9 but not for 2.7.10 or 2.7.11.

How do I parse JSON into an int?

You may use parseInt :

int id = Integer.parseInt(jsonObj.get("id"));

or better and more directly the getInt method :

int id = jsonObj.getInt("id");

How do you handle a "cannot instantiate abstract class" error in C++?

Visual Studio's Error List pane only shows you the first line of the error. Invoke View>Output and I bet you'll see something like:

c:\path\to\your\code.cpp(42): error C2259: 'AmbientOccluder' : cannot instantiate abstract class
          due to following members:
          'ULONG MysteryUnimplementedMethod(void)' : is abstract
          c:\path\to\some\include.h(8) : see declaration of 'MysteryUnimplementedMethod'

Why is it that "No HTTP resource was found that matches the request URI" here?

Please check the class you inherited. Whether it is simply Controller or APIController.

By mistake we might create a controller from MVC 5 controller. It should be from Web API Controller.

Convert A String (like testing123) To Binary In Java

public class HexadecimalToBinaryAndLong{
  public static void main(String[] args) throws IOException{
    BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
    System.out.println("Enter the hexa value!");
    String hex = bf.readLine();
    int i = Integer.parseInt(hex);               //hex to decimal
    String by = Integer.toBinaryString(i);       //decimal to binary
    System.out.println("This is Binary: " + by);
    }
}

How to deploy a React App on Apache web server

You can run it through the Apache proxy, but it would have to be running in a virtual directory (e.g. http://mysite.something/myreactapp ).

This may seem sort of redundant but if you have other pages that are not part of your React app (e.g. PHP pages), you can serve everything via port 80 and make it apear that the whole thing is a cohesive website.

1.) Start your react app with npm run, or whatever command you are using to start the node server. Assuming it is running on http://127.0.0.1:8080

2.) Edit httpd-proxy.conf and add:

ProxyRequests On
ProxyVia On
<Proxy *>
  Order deny,allow
  Allow from all
  </Proxy>

ProxyPass /myreactapp http://127.0.0.1:8080/
ProxyPassReverse /myreactapp  http://127.0.0.1:8080/

3.) Restart Apache

Java: recommended solution for deep cloning/copying an instance

For complicated objects and when performance is not significant i use gson to serialize the object to json text, then deserialize the text to get new object.

gson which based on reflection will works in most cases, except that transient fields will not be copied and objects with circular reference with cause StackOverflowError.

public static <ObjectType> ObjectType Copy(ObjectType AnObject, Class<ObjectType> ClassInfo)
{
    Gson gson = new GsonBuilder().create();
    String text = gson.toJson(AnObject);
    ObjectType newObject = gson.fromJson(text, ClassInfo);
    return newObject;
}
public static void main(String[] args)
{
    MyObject anObject ...
    MyObject copyObject = Copy(o, MyObject.class);

}

get next and previous day with PHP

Use

$time = time();

For previous day -

date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)- 1 ,date("Y", $time)));

For 2 days ago

date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time) -2 ,date("Y", $time)));

For Next day -

date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time)+ 1 ,date("Y", $time)));

For next 2 days

date("Y-m-d", mktime(0,0,0,date("n", $time),date("j",$time) +2 ,date("Y", $time)));

bootstrap 4 file input doesn't show the file name

I have used following for the same:

<script type="application/javascript">
    $('input[type="file"]').change(function(e){
        var fileName = e.target.files[0].name;
        $('.custom-file-label').html(fileName);
    });
</script>

Automatically set appsettings.json for dev and release environments in asp.net core?

In ASP.NET Core you should rather use Environment Variables instead of build configuration for proper appsettings.json

  1. Right click on you project > Properties > Debug > Environment Variables

    environment variables

  2. ASP.NET Core will use the appropriate appsettings.json file:

    example of appsettings files in solution explorer

  3. Now you can use that Environment Variable like this:

    public Startup(IHostingEnvironment env)
    {
        var builder = new ConfigurationBuilder()
            .SetBasePath(env.ContentRootPath)
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
            .AddEnvironmentVariables();
    
        Configuration = builder.Build();
    }
    

Note: If you use @Dmitry's answer, you can run into problems eg. when overriding appsettings.json values on Azure.

MsgBox "" vs MsgBox() in VBScript

The difference between "" and () is:

With "" you are not calling anything.
With () you are calling a sub.

Example with sub:

Sub = MsgBox("Msg",vbYesNo,vbCritical,"Title")
Select Case Sub
     Case = vbYes
          MsgBox"You said yes"
     Case = vbNo
          MsgBox"You said no"
 End Select

vs Normal:

 MsgBox"This is normal"

How to send a correct authorization header for basic authentication

You can include the user and password as part of the URL:

http://user:[email protected]/index.html

see this URL, for more

HTTP Basic Authentication credentials passed in URL and encryption

of course, you'll need the username password, it's not 'Basic hashstring.

hope this helps...

How to check if a date is in a given range?

$startDatedt = strtotime($start_date)
$endDatedt = strtotime($end_date)
$usrDatedt = strtotime($date_from_user)

if( $usrDatedt >= $startDatedt && $usrDatedt <= $endDatedt)
{
   //..falls within range
}

How to change color of ListView items on focus and on click

listview.setOnItemLongClickListener(new OnItemLongClickListener() {

        @Override
        public boolean onItemLongClick(final AdapterView<?> parent, View view,
                final int position, long id) {
            // TODO Auto-generated method stub

             parent.getChildAt(position).setBackgroundColor(getResources().getColor(R.color.listlongclick_selection));

            return false;
        }
    });

How to redirect on another page and pass parameter in url from table?

Do this :

<script type="text/javascript">
function showDetails(username)
{
   window.location = '/player_detail?username='+username;
}
</script>

<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">

Is there a way to cast float as a decimal without rounding and preserving its precision?

cast (field1 as decimal(53,8)
) field 1

The default is: decimal(18,0)

'Incomplete final line' warning when trying to read a .csv file into R

Use readLines() (with warn = FALSE) to read the file into a character vector first.

After that use the text = option to read the vector into a data frame with read.table()

    pheasant <- read.table( 
        text = readLines(file.choose(), warn = FALSE), 
        header = TRUE,  
        sep = "," 
    )

JQuery Datatables : Cannot read property 'aDataSort' of undefined

In my case I had

$(`#my_table`).empty();

Where it should have been

$(`#my_table tbody`).empty();

Note: in my case I had to empty the table since i had data that I wanted gone before inserting new data.

Just thought of sharing where it "might" help someone in the future!

Calling a Sub in VBA

For anyone still coming to this post, the other option is to simply omit the parentheses:

Sub SomeOtherSub(Stattyp As String)
    'Daty and the other variables are defined here

    CatSubProduktAreakum Stattyp, Daty + UBound(SubCategories) + 2

End Sub

The Call keywords is only really in VBA for backwards compatibilty and isn't actually required.

If however, you decide to use the Call keyword, then you have to change your syntax to suit.

'// With Call
Call Foo(Bar)

'// Without Call
Foo Bar

Both will do exactly the same thing.


That being said, there may be instances to watch out for where using parentheses unnecessarily will cause things to be evaluated where you didn't intend them to be (as parentheses do this in VBA) so with that in mind the better option is probably to omit the Call keyword and the parentheses

Storing an object in state of a React component?

this.setState({abc: {xyz: 'new value'}}); will NOT work, as state.abc will be entirely overwritten, not merged.

This works for me:

this.setState((previousState) => {
  previousState.abc.xyz = 'blurg';
  return previousState;
});

Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html

Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:

const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);

iOS 7 - Status bar overlaps the view

This is the default behaviour for UIViewController on iOS 7. The view will be full-screen which means the status bar will cover the top of your view.

If you have a UIViewController within a UINavigationController and the navigationBar is visible, you can have the following code in your viewDidLoad or have a background image for navigationBar do the trick.

self.edgesForExtendedLayout = UIRectEdgeNone;

If you have navigationBar hidden, then you have to adjust all the UIView elements by shifting 20 points. I dont't see any other solution. Use auto layout will help a little bit.

Here is the sample code for detecting the iOS version, if you want to backward compatibility.

NSUInteger DeviceSystemMajorVersion() {
    static NSUInteger _deviceSystemMajorVersion = -1;
    static dispatch_once_t onceToken;

    dispatch_once(&onceToken, ^{
        NSString *systemVersion = [UIDevice currentDevice].systemVersion;
        _deviceSystemMajorVersion = [[systemVersion componentsSeparatedByString:@"."][0] intValue];
    });

   return _deviceSystemMajorVersion;
}

What does .class mean in Java?

That means a Class with a type of anything (unknown).

You should read java generics tutorial to get to understand it better

Using Jquery Datatable with AngularJs

I know it's tempting to use drag and drop angular modules created by other devs - but actually, unless you are doing something non-standard like dynamically adding / removing rows from the ng-repeated data set by calling $http services chance are you really don't need a directive based solution, so if you do go this direction you probably just created extra watchers you don't actually need.

What this implementation provides:

  • Pagination is always correct
  • Filtering is always correct (even if you add custom filters but of course they just need to be in the same closure)

The implementation is easy. Just use angular's version of jQuery dom ready from your view's controller:

Inside your controller:

'use strict';

var yourApp = angular.module('yourApp.yourController.controller', []);

yourApp.controller('yourController', ['$scope', '$http', '$q', '$timeout', function ($scope, $http, $q, $timeout) {

    $scope.users = [
        {
            email: '[email protected]',
            name: {
                first: 'User',
                last: 'Last Name'
            },
            phone: '(416) 555-5555',
            permissions: 'Admin'
        },
        {
            email: '[email protected]',
            name: {
                first: 'First',
                last: 'Last'
            },
            phone: '(514) 222-1111',
            permissions: 'User'
        }
    ];

    angular.element(document).ready( function () {
         dTable = $('#user_table')
         dTable.DataTable();
     });

}]);

Now in your html view can do:

<div class="table table-data clear-both" data-ng-show="viewState === possibleStates[0]">
        <table id="user_table" class="users list dtable">
            <thead>
                <tr>
                    <th>E-mail</th>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Phone</th>
                    <th>Permissions</th>
                    <th class="blank-cell"></th>
                </tr>
            </thead>
            <tbody>
                <tr data-ng-repeat="user in users track by $index">
                    <td>{{ user.email }}</td>
                    <td>{{ user.name.first }}</td>
                    <td>{{ user.name.last }}</td>
                    <td>{{ user.phone }}</td>
                    <td>{{ user.permissions }}</td>
                    <td class="users controls blank-cell">
                        <a class="btn pointer" data-ng-click="showEditUser( $index )">Edit</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>

What are the best practices for using a GUID as a primary key, specifically regarding performance?

This link says it better than I could and helped in my decision making. I usually opt for an int as a primary key, unless I have a specific need not to and I also let SQL server auto-generate/maintain this field unless I have some specific reason not to. In reality, performance concerns need to be determined based on your specific app. There are many factors at play here including but not limited to expected db size, proper indexing, efficient querying, and more. Although people may disagree, I think in many scenarios you will not notice a difference with either option and you should choose what is more appropriate for your app and what allows you to develop easier, quicker, and more effectively (If you never complete the app what difference does the rest make :).

https://web.archive.org/web/20120812080710/http://databases.aspfaq.com/database/what-should-i-choose-for-my-primary-key.html

P.S. I'm not sure why you would use a Composite PK or what benefit you believe that would give you.

How does jQuery work when there are multiple elements with the same ID value?

If you have multiple elements with same id or same name, just assign same class to those multiple elements and access them by index & perform your required operation.

  <div>
        <span id="a" class="demo">1</span>
        <span id="a" class="demo">2</span>
        <span>3</span>
    </div>

JQ:

$($(".demo")[0]).val("First span");
$($(".demo")[1]).val("Second span");

CSS /JS to prevent dragging of ghost image?

You can assign an alternate ghost image if you really need to use drag events and can't set draggable=false. So just assign a blank png like so:

    $('#img').bind({
        dragstart: function(e) {
            var dragIcon = document.createElement('img');
            dragIcon.src = 'blank.png';
            dragIcon.width = 100;
            e.dataTransfer.setDragImage(dragIcon, -10, -10);
        }
    });

Integer ASCII value to character in BASH using printf

For capital letters:

i=67
letters=({A..Z})
echo "${letters[$i-65]}"

Output:

C

CSS content property: is it possible to insert HTML instead of Text?

It is not possible prolly cuz it would be so easy to XSS. Also , current HTML sanitizers that are available don't disallow content property.

(Definitely not the greatest answer here but I just wanted to share an insight other than the "according to spec... ")

What's the difference between returning value or Promise.resolve from then()

In simple terms, inside a then handler function:

A) When x is a value (number, string, etc):

  1. return x is equivalent to return Promise.resolve(x)
  2. throw x is equivalent to return Promise.reject(x)

B) When x is a Promise that is already settled (not pending anymore):

  1. return x is equivalent to return Promise.resolve(x), if the Promise was already resolved.
  2. return x is equivalent to return Promise.reject(x), if the Promise was already rejected.

C) When x is a Promise that is pending:

  1. return x will return a pending Promise, and it will be evaluated on the subsequent then.

Read more on this topic on the Promise.prototype.then() docs.

How to open the command prompt and insert commands using Java?

String[] command = {"cmd.exe" , "/c", "start" , "cmd.exe" , "/k" , "\" dir && ipconfig 
\"" };
ProcessBuilder probuilder = new ProcessBuilder( command );
probuilder.directory(new File("D:\\Folder1"));
Process process = probuilder.start();

Scala Doubles, and Precision

Those are great answers in this thread. In order to better show the difference, here is just an example. The reason I put it here b/c during my work the numbers are required to be NOT half-up :

    import org.apache.spark.sql.types._
    val values = List(1.2345,2.9998,3.4567,4.0099,5.1231)
    val df = values.toDF
    df.show()
    +------+
    | value|
    +------+
    |1.2345|
    |2.9998|
    |3.4567|
    |4.0099|
    |5.1231|
    +------+

    val df2 = df.withColumn("floor_val", floor(col("value"))).
    withColumn("dec_val", col("value").cast(DecimalType(26,2))).
    withColumn("floor2", (floor(col("value") * 100.0)/100.0).cast(DecimalType(26,2)))

    df2.show()
+------+---------+-------+------+
| value|floor_val|dec_val|floor2|
+------+---------+-------+------+
|1.2345|        1|   1.23|  1.23|
|2.9998|        2|   3.00|  2.99|
|3.4567|        3|   3.46|  3.45|
|4.0099|        4|   4.01|  4.00|
|5.1231|        5|   5.12|  5.12|
+------+---------+-------+------+

floor function floors to the largest interger less than current value. DecimalType by default will enable HALF_UP mode, not just cut to precision you want. If you want to cut to a certain precision without using HALF_UP mode, you can use above solution instead ( or use scala.math.BigDecimal (where you have to explicitly define rounding modes).

Converting Select results into Insert script - SQL Server

1- Explanation of Scripts

A)Syntax for inserting data in table is as below

Insert into table(col1,col2,col3,col4,col5)    

             -- To achieve this part i    
             --have used below variable
                ------@CSV_COLUMN-------

values(Col1 data in quote, Col2..quote,..Col5..quote)

-- To achieve this part 
-- i.e column data in 
--quote i have used 
--below variable
----@QUOTED_DATA---

C)To get above data from existing table we have to write the select query in such way that the output will be in form of as above scripts

D)Then Finally i have Concatenated above variable to create final script that's will generate insert script on execution

E)

@TEXT='SELECT ''INSERT INTO
 '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER_CONDITION

F)And Finally Executed the above query EXECUTE(TEXT)

G)QUOTENAME() function is used to wrap column data inside quote

H)ISNULL is used because if any row has NULL data for any column the query fails and return NULL thats why to avoid that i have used ISNULL

I)And created the sp sp_generate_insertscripts for same

1- Just put the table name for which you want insert script

2- Filter condition if you want specific results

----------Final Procedure To generate Script------

CREATE PROCEDURE sp_generate_insertscripts
(
    @TABLE_NAME VARCHAR(MAX),
    @FILTER_CONDITION VARCHAR(MAX)=''
)
AS
BEGIN

SET NOCOUNT ON

DECLARE @CSV_COLUMN VARCHAR(MAX),
        @QUOTED_DATA VARCHAR(MAX),
        @TEXT VARCHAR(MAX)

SELECT @CSV_COLUMN=STUFF
(
    (
     SELECT ',['+ NAME +']' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @QUOTED_DATA=STUFF
(
    (
     SELECT ' ISNULL(QUOTENAME('+NAME+','+QUOTENAME('''','''''')+'),'+'''NULL'''+')+'','''+'+' FROM sys.all_columns 
     WHERE OBJECT_ID=OBJECT_ID(@TABLE_NAME) AND 
     is_identity!=1 FOR XML PATH('')
    ),1,1,''
)

SELECT @TEXT='SELECT ''INSERT INTO '+@TABLE_NAME+'('+@CSV_COLUMN+')VALUES('''+'+'+SUBSTRING(@QUOTED_DATA,1,LEN(@QUOTED_DATA)-5)+'+'+''')'''+' Insert_Scripts FROM '+@TABLE_NAME + @FILTER_CONDITION

--SELECT @CSV_COLUMN AS CSV_COLUMN,@QUOTED_DATA AS QUOTED_DATA,@TEXT TEXT

EXECUTE (@TEXT)

SET NOCOUNT OFF

END

Python conditional assignment operator

No, not knowing which variables are defined is a bug, not a feature in Python.

Use dicts instead:

d = {}
d.setdefault('key', 1)
d['key'] == 1

d['key'] = 2
d.setdefault('key', 1)
d['key'] == 2

What's alternative to angular.copy in Angular

As others have already pointed out, using lodash or underscore is probably the best solution. But if you do not need those libraries for anything else, you can probably use something like this:

  function deepClone(obj) {

    // return value is input is not an Object or Array.
    if (typeof(obj) !== 'object' || obj === null) {
      return obj;    
    }

    let clone;

    if(Array.isArray(obj)) {
      clone = obj.slice();  // unlink Array reference.
    } else {
      clone = Object.assign({}, obj); // Unlink Object reference.
    }

    let keys = Object.keys(clone);

    for (let i=0; i<keys.length; i++) {
      clone[keys[i]] = deepClone(clone[keys[i]]); // recursively unlink reference to nested objects.
    }

    return clone; // return unlinked clone.

  }

That's what we decided to do.

What does hash do in python?

A hash is an fixed sized integer that identifies a particular value. Each value needs to have its own hash, so for the same value you will get the same hash even if it's not the same object.

>>> hash("Look at me!")
4343814758193556824
>>> f = "Look at me!"
>>> hash(f)
4343814758193556824

Hash values need to be created in such a way that the resulting values are evenly distributed to reduce the number of hash collisions you get. Hash collisions are when two different values have the same hash. Therefore, relatively small changes often result in very different hashes.

>>> hash("Look at me!!")
6941904779894686356

These numbers are very useful, as they enable quick look-up of values in a large collection of values. Two examples of their use are Python's set and dict. In a list, if you want to check if a value is in the list, with if x in values:, Python needs to go through the whole list and compare x with each value in the list values. This can take a long time for a long list. In a set, Python keeps track of each hash, and when you type if x in values:, Python will get the hash-value for x, look that up in an internal structure and then only compare x with the values that have the same hash as x.

The same methodology is used for dictionary lookup. This makes lookup in set and dict very fast, while lookup in list is slow. It also means you can have non-hashable objects in a list, but not in a set or as keys in a dict. The typical example of non-hashable objects is any object that is mutable, meaning that you can change its value. If you have a mutable object it should not be hashable, as its hash then will change over its life-time, which would cause a lot of confusion, as an object could end up under the wrong hash value in a dictionary.

Note that the hash of a value only needs to be the same for one run of Python. In Python 3.3 they will in fact change for every new run of Python:

$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
1849024199686380661
>>> 
$ /opt/python33/bin/python3
Python 3.3.2 (default, Jun 17 2013, 17:49:21) 
[GCC 4.6.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> hash("foo")
-7416743951976404299

This is to make is harder to guess what hash value a certain string will have, which is an important security feature for web applications etc.

Hash values should therefore not be stored permanently. If you need to use hash values in a permanent way you can take a look at the more "serious" types of hashes, cryptographic hash functions, that can be used for making verifiable checksums of files etc.

What is the difference between a URI, a URL and a URN?

See this document. Specifically,

a URL is a type of URI that identifies a resource via a representation of its primary access mechanism (e.g., its network "location"), rather than by some other attributes it may have.

It's not an extremely clear term, really.

Working with time DURATION, not time of day

With custom format of a cell you can insert a type like this: d "days", h:mm:ss, which will give you a result like 16 days, 13:56:15 in an excel-cell.

If you would like to show the duration in hours you use the following type [h]:mm:ss, which will lead to something like 397:56:15. Control check: 16 =(397 hours -13 hours)/24

enter image description here

Regex to check whether a string contains only numbers

Why dont use something like:

$.isNumeric($(input).val())

Is jquery tested, and the most common case are checked

React Native Error: ENOSPC: System limit for number of file watchers reached

As already pointed out by @snishalaka, you can increase the number of inotify watchers.

However, I think the default number is high enough and is only reached when processes are not cleaned up properly. Hence, I simply restarted my computer as proposed on a related github issue and the error message was gone.

Time complexity of accessing a Python dict

My program seems to suffer from linear access to dictionaries, its run-time grows exponentially even though the algorithm is quadratic.

I use a dictionary to memoize values. That seems to be a bottleneck.

This is evidence of a bug in your memoization method.

How to install packages offline?

Download the wheel file (for example dlb-0.5.0-py3-none-any.whl) from Pypi and

pip install dlb-0.5.0-py3-none-any.whl

Google Recaptcha v3 example demo

I process POST on PHP from an angular ajax call. I also like to see the SCORE from google.

This works well for me...

$postData = json_decode(file_get_contents('php://input'), true); //get data sent via post
$captcha = $postData['g-recaptcha-response'];

header('Content-Type: application/json');
if($captcha === ''){
    //Do something with error
    echo '{ "status" : "bad", "score" : "none"}';
} else {
    $secret   = 'your-secret-key';
    $response = file_get_contents(
        "https://www.google.com/recaptcha/api/siteverify?secret=" . $secret . "&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']
    );
    // use json_decode to extract json response
    $response = json_decode($response);

    if ($response->success === false) {
        //Do something with error
        echo '{ "status" : "bad", "score" : "none"}';
    }else if ($response->success==true && $response->score <= 0.5) {
        echo '{ "status" : "bad", "score" : "'.$response->score.'"}';
    }else {
        echo '{ "status" : "ok", "score" : "'.$response->score.'"}';
    }
}

On HTML

<input type="hidden" id="g-recaptcha-response" name="g-recaptcha-response">

On js

$scope.grabCaptchaV3=function(){
    var params = {
                     method: 'POST',
                     url: 'api/recaptcha.php',
                     headers: {
                       'Content-Type': undefined
                     },
                     data:   {'g-recaptcha-response' : myCaptcha }
     }
     $http(params).then(function(result){ 
                console.log(result.data);
     }, function(response){
                console.log(response.statusText);
     }); 
}

SQL query question: SELECT ... NOT IN

Given it's SQL 2005, you can also try this It's similar to Oracle's MINUS command (opposite of UNION)

But I would also suggest adding the DATEPART ( hour, insertDate) column for debug

SELECT idCustomer FROM reservations 
EXCEPT
SELECT idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2

HashMap(key: String, value: ArrayList) returns an Object instead of ArrayList?

Using generics (as in the above answers) is your best bet here. I've just double checked and:

test.put("test", arraylistone); 
ArrayList current = new ArrayList();
current = (ArrayList) test.get("test");

will work as well, through I wouldn't recommend it as the generics ensure that only the correct data is added, rather than trying to do the handling at retrieval time.

What's the valid way to include an image with no src?

As written in comments, this method is wrong.

I didn't find this answer before, but acording to W3 Specs valid empty src tag would be an anchor link #.

Example: src="#", src="#empty"

Page validates successfully and no extra request are made.

How do I get indices of N maximum values in a NumPy array?

Method np.argpartition only returns the k largest indices, performs a local sort, and is faster than np.argsort(performing a full sort) when array is quite large. But the returned indices are NOT in ascending/descending order. Let's say with an example:

Enter image description here

We can see that if you want a strict ascending order top k indices, np.argpartition won't return what you want.

Apart from doing a sort manually after np.argpartition, my solution is to use PyTorch, torch.topk, a tool for neural network construction, providing NumPy-like APIs with both CPU and GPU support. It's as fast as NumPy with MKL, and offers a GPU boost if you need large matrix/vector calculations.

Strict ascend/descend top k indices code will be:

Enter image description here

Note that torch.topk accepts a torch tensor, and returns both top k values and top k indices in type torch.Tensor. Similar with np, torch.topk also accepts an axis argument so that you can handle multi-dimensional arrays/tensors.

Codeigniter - multiple database connections

Use this.

$dsn1 = 'mysql://user:password@localhost/db1';
$this->db1 = $this->load->database($dsn1, true);     

$dsn2 = 'mysql://user:password@localhost/db2';
$this->db2= $this->load->database($dsn2, true);     

$dsn3 = 'mysql://user:password@localhost/db3';
$this->db3= $this->load->database($dsn3, true);   

Usage

$this->db1 ->insert('tablename', $insert_array);
$this->db2->insert('tablename', $insert_array);
$this->db3->insert('tablename', $insert_array);

Can the Twitter Bootstrap Carousel plugin fade in and out on slide transition

If you are using Bootstrap 3.3.x then use this code (you need to add class name carousel-fade to your carousel).

.carousel-fade .carousel-inner .item {
  -webkit-transition-property: opacity;
          transition-property: opacity;
}
.carousel-fade .carousel-inner .item,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  opacity: 0;
}
.carousel-fade .carousel-inner .active,
.carousel-fade .carousel-inner .next.left,
.carousel-fade .carousel-inner .prev.right {
  opacity: 1;
}
.carousel-fade .carousel-inner .next,
.carousel-fade .carousel-inner .prev,
.carousel-fade .carousel-inner .active.left,
.carousel-fade .carousel-inner .active.right {
  left: 0;
  -webkit-transform: translate3d(0, 0, 0);
          transform: translate3d(0, 0, 0);
}
.carousel-fade .carousel-control {
  z-index: 2;
}

Array.push() and unique items

You can use the Set structure from ES6 to make your code faster and more readable:

// Create Set
this.items = new Set();

add(item) {
    this.items.add(item);

    // Set to array
    console.log([...this.items]);
}

Android: Force EditText to remove focus?

you have to remove <requestFocus/>

if you don't use it and still the same problem

user LinearLayout as a parent and set

android:focusable="true"
android:focusableInTouchMode="true"

Hope it's help you.

Examples of Algorithms which has O(1), O(n log n) and O(log n) complexities

O(2N)

O(2N) denotes an algorithm whose growth doubles with each additon to the input data set. The growth curve of an O(2N) function is exponential - starting off very shallow, then rising meteorically. An example of an O(2N) function is the recursive calculation of Fibonacci numbers:

int Fibonacci (int number)
{
if (number <= 1) return number;
return Fibonacci(number - 2) + Fibonacci(number - 1);
}

Prevent overwriting a file using cmd if exist

Use the FULL path to the folder in your If Not Exist code. Then you won't even have to CD anymore:

If Not Exist "C:\Documents and Settings\John\Start Menu\Programs\SoftWareFolder\"

CSS text-align not working

You have to make the UL inside the div behave like a block. Try adding

.navigation ul {
     display: inline-block;
}

Margin-Top not working for span element?

span is an inline element that doesn't support vertical margins. Put the margin on the outer div instead.

How do you subtract Dates in Java?

Well you can remove the third calendar instance.

GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2000, 1, 1);
c2.set(2010,1, 1);
c2.add(GregorianCalendar.MILLISECOND, -1 * c1.getTimeInMillis());

What is the recommended way to delete a large number of items from DynamoDB?

If you want to delete items after some time, e.g. after a month, just use Time To Live option. It will not count write units.

In your case, I would add ttl when logs expire and leave those after a user is deleted. TTL would make sure logs are removed eventually.

When Time To Live is enabled on a table, a background job checks the TTL attribute of items to see if they are expired.

DynamoDB typically deletes expired items within 48 hours of expiration. The exact duration within which an item truly gets deleted after expiration is specific to the nature of the workload and the size of the table. Items that have expired and not been deleted will still show up in reads, queries, and scans. These items can still be updated and successful updates to change or remove the expiration attribute will be honored.

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/TTL.html https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/howitworks-ttl.html

What characters do I need to escape in XML documents?

If you use an appropriate class or library, they will do the escaping for you. Many XML issues are caused by string concatenation.

XML escape characters

There are only five:

"   &quot;
'   &apos;
<   &lt;
>   &gt;
&   &amp;

Escaping characters depends on where the special character is used.

The examples can be validated at the W3C Markup Validation Service.

Text

The safe way is to escape all five characters in text. However, the three characters ", ' and > needn't be escaped in text:

<?xml version="1.0"?>
<valid>"'></valid>

Attributes

The safe way is to escape all five characters in attributes. However, the > character needn't be escaped in attributes:

<?xml version="1.0"?>
<valid attribute=">"/>

The ' character needn't be escaped in attributes if the quotes are ":

<?xml version="1.0"?>
<valid attribute="'"/>

Likewise, the " needn't be escaped in attributes if the quotes are ':

<?xml version="1.0"?>
<valid attribute='"'/>

Comments

All five special characters must not be escaped in comments:

<?xml version="1.0"?>
<valid>
<!-- "'<>& -->
</valid>

CDATA

All five special characters must not be escaped in CDATA sections:

<?xml version="1.0"?>
<valid>
<![CDATA["'<>&]]>
</valid>

Processing instructions

All five special characters must not be escaped in XML processing instructions:

<?xml version="1.0"?>
<?process <"'&> ?>
<valid/>

XML vs. HTML

HTML has its own set of escape codes which cover a lot more characters.

Insert text with single quotes in PostgreSQL

you can use the postrgesql chr(int) function:

insert into test values (2,'|| chr(39)||'my users'||chr(39)||');

Date to milliseconds and back to date in Swift

let dateTimeStamp = NSDate(timeIntervalSince1970:Double(currentTimeInMiliseconds())/1000)  //UTC time  //YOUR currentTimeInMiliseconds METHOD
let dateFormatter = NSDateFormatter()
dateFormatter.timeZone = NSTimeZone.localTimeZone() 
dateFormatter.dateFormat = "yyyy-MM-dd"
dateFormatter.dateStyle = NSDateFormatterStyle.FullStyle
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle


let strDateSelect = dateFormatter.stringFromDate(dateTimeStamp)
print("Local Time", strDateSelect) //Local time


let dateFormatter2 = NSDateFormatter()
dateFormatter2.timeZone = NSTimeZone(name: "UTC") as NSTimeZone!
dateFormatter2.dateFormat = "yyyy-MM-dd"

let date3 = dateFormatter.dateFromString(strDateSelect)
print("DATE",date3)

How to remove components created with Angular-CLI

No As of now you can't do this by any command. You've to remove Manually from app.module.ts and app.routing.module.ts if you're using Angular 5

How to add /usr/local/bin in $PATH on Mac

I tend to find this neat

sudo mkdir -p /etc/paths.d   # was optional in my case
echo /usr/local/git/bin  | sudo tee /etc/paths.d/mypath1

Calling functions in a DLL from C++

Can also export functions from dll and import from the exe, it is more tricky at first but in the end is much easier than calling LoadLibrary/GetProcAddress. See MSDN.

When creating the project with the VS wizard there's a check box in the dll that let you export functions.

Then, in the exe application you only have to #include a header from the dll with the proper definitions, and add the dll project as a dependency to the exe application.

Check this other question if you want to investigate this point further Exporting functions from a DLL with dllexport.

CodeIgniter -> Get current URL relative to base url

you can use the some Codeigniter functions and some core functions and make combination to achieve your URL with query string. I found solution of this problem.

base_url($this->uri->uri_string()).strrchr($_SERVER['REQUEST_URI'], "?");

and if you loaded URL helper so you can also do this current_url().strrchr($_SERVER['REQUEST_URI'], "?");

Java Regex Capturing Groups

Your understanding is correct. However, if we walk through:

  • (.*) will swallow the whole string;
  • it will need to give back characters so that (\\d+) is satistifed (which is why 0 is captured, and not 3000);
  • the last (.*) will then capture the rest.

I am not sure what the original intent of the author was, however.

Check if string contains only digits

it checks valid number integers or float or double not a string

regex that i used

simple regex

 1. ^[0-9]*[.]?[0-9]*$

advance regex

 2. ^-?[\d.]+(?:e-?\d+)?$    

eg:only numbers

_x000D_
_x000D_
var str='1232323';
var reg=/^[0-9]*[.]?[0-9]*$/;

console.log(reg.test(str))
_x000D_
_x000D_
_x000D_

it allows

eg:123434

eg:.1232323

eg:12.3434434

it does not allow

eg:1122212.efsffasf

eg:2323fdf34434

eg:0.3232rf3333

advance regex

////////////////////////////////////////////////////////////////////

int or float or exponent all types of number in string

^-?[\d.]+(?:e-?\d+)?$

eg:13123123

eg:12344.3232

eg:2323323e4

eg:0.232332

Getting The ASCII Value of a character in a C# string

Here's an alternative since you don't like the cast to int:

foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
    Console.Write(b.ToString());

dynamic_cast and static_cast in C++

A dynamic_cast performs a type checking using RTTI. If it fails it'll throw you an exception (if you gave it a reference) or NULL if you gave it a pointer.

Class constructor type in typescript?

I am not sure if this was possible in TypeScript when the question was originally asked, but my preferred solution is with generics:

class Zoo<T extends Animal> {
    constructor(public readonly AnimalClass: new () => T) {
    }
}

This way variables penguin and lion infer concrete type Penguin or Lion even in the TypeScript intellisense.

const penguinZoo = new Zoo(Penguin);
const penguin = new penguinZoo.AnimalClass(); // `penguin` is of `Penguin` type.

const lionZoo = new Zoo(Lion);
const lion = new lionZoo.AnimalClass(); // `lion` is `Lion` type.

git checkout all the files

If you want to checkout all the files 'anywhere'

git checkout -- $(git rev-parse --show-toplevel)

How do I select an element in jQuery by using a variable for the ID?

Doing $('body').find(); is not necessary when looking up by ID; there is no performance gain.

Please also note that having an ID that starts with a number is not valid HTML:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

How to check a string against null in java?

I'm not sure what was wrong with The MYYN's answer.

if (yourString != null) {
  //do fun stuff with yourString here
}

The above null check is quite alright.

If you are trying to check if a String reference is equal (ignoring case) to another string that you know is not a null reference, then do something like this:

String x = "this is not a null reference"
if (x.equalsIgnoreCase(yourStringReferenceThatMightBeNull) ) {
  //do fun stuff
}

If there is any doubt as to whether or not you have null references for both Strings you are comparing, you'll need to check for a null reference on at least one of them to avoid the possibility of a NullPointerException.

submitting a form when a checkbox is checked

I've been messing around with this for about four hours and decided to share this with you.

You can submit a form by clicking a checkbox but the weird thing is that when checking for the submission in php, you would expect the form to be set when you either check or uncheck the checkbox. But this is not true. The form only gets set when you actually check the checkbox, if you uncheck it it won't be set. the word checked at the end of a checkbox input type will cause the checkbox to display checked, so if your field is checked it will have to reflect that like in the example below. When it gets unchecked the php updates the field state which will cause the word checked the disappear.

You HTML should look like this:

<form method='post' action='#'>
<input type='checkbox' name='checkbox' onChange='submit();'
<?php if($page->checkbox_state == 1) { echo 'checked' }; ?>>
</form>

and the php:

if(isset($_POST['checkbox'])) {
   // the checkbox has just been checked 
   // save the new state of the checkbox somewhere
   $page->checkbox_state == 1;
} else {
   // the checkbox has just been unchecked
   // if you have another form ont the page which uses than you should
   // make sure that is not the one thats causing the page to handle in input
   // otherwise the submission of the other form will uncheck your checkbox
   // so this this line is optional:
      if(!isset($_POST['submit'])) {
          $page->checkbox_state == 0;
      }
}

How to verify an XPath expression in Chrome Developers tool or Firefox's Firebug?

I verify XPath and CSS selectors using WebSync Chrome extension.

It provides possibility to verify selectors and also to generate/modify selectors by clicking on element attributes.

https://chrome.google.com/webstore/detail/natu-websync/aohpgnblncapofbobbilnlfliihianac

enter image description here

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

How to delete all files and folders in a folder by cmd call

I had an index folder with 33 folders that needed all the files and subfolders removed in them. I opened a command line in the index folder and then used these commands:

for /d in (*) do rd /s /q "%a" & (
md "%a")

I separated them into two lines (hit enter after first line, and when asked for more add second line) because if entered on a single line this may not work. This command will erase each directory and then create a new one which is empty, thus removing all files and subflolders in the original directory.

MySQL Trigger: Delete From Table AFTER DELETE

I think there is an error in the trigger code. As you want to delete all rows with the deleted patron ID, you have to use old.id (Otherwise it would delete other IDs)

Try this as the new trigger:

CREATE TRIGGER log_patron_delete AFTER DELETE on patrons
FOR EACH ROW
BEGIN
DELETE FROM patron_info
    WHERE patron_info.pid = old.id;
END

Dont forget the ";" on the delete query. Also if you are entering the TRIGGER code in the console window, make use of the delimiters also.

Call javascript from MVC controller action

For those that just used a standard form submit (non-AJAX), there's another way to fire some Javascript/JQuery code upon completion of your action.

First, create a string property on your Model.

public class MyModel 
{
    public string JavascriptToRun { get; set;}
}

Now, bind to your new model property in the Javascript of your view:

<script type="text/javascript">
     @Model.JavascriptToRun
</script>

Now, also in your view, create a Javascript function that does whatever you need to do:

<script type="text/javascript">
     @Model.JavascriptToRun

     function ShowErrorPopup() {
          alert('Sorry, we could not process your order.');
     }

</script>

Finally, in your controller action, you need to call this new Javascript function:

[HttpPost]
public ActionResult PurchaseCart(MyModel model)
{
    // Do something useful
    ...

    if (success == false)
    {
        model.JavascriptToRun= "ShowErrorPopup()";
        return View(model);
    }
    else
        return RedirectToAction("Success");
}

Git - Ignore files during merge

Example:

  1. You have two branches: master, develop
  2. You created file in develop branch and want to ignore it while merging

Code:

git config --global merge.ours.driver true
git checkout master
echo "path/file_to_ignore merge=ours" >> .gitattributes
git merge develop

You can also ignore files with same extension

for example all files with .txt extension:

echo "*.txt merge=ours" >> .gitattributes

How Can I Remove “public/index.php” in the URL Generated Laravel?

Don't get confused with other option the snippet below I am using and will be useful for you too. Put the below htacces in your root.

<IfModule mod_rewrite.c>
    RewriteEngine on
    RewriteRule    ^$    public/    [L]
    RewriteRule    (.*) public/$1    [L]
</IfModule>

Go to your public directory and put another htaccess file with the code snippet below

<IfModule mod_rewrite.c>
    RewriteEngine On
    # Removes index.php from ExpressionEngine URLs  
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?url=$1 [PT,L]

</IfModule>

Its working... !!!

Laravel Uses below .htaccess

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]

How to convert an int value to string in Go?

It is interesting to note that strconv.Itoa is shorthand for

func FormatInt(i int64, base int) string

with base 10

For Example:

strconv.Itoa(123)

is equivalent to

strconv.FormatInt(int64(123), 10)

How to delete or change directory of a cloned git repository on a local computer

Just move it :)

command line :

move "C:\Documents and Setings\$USER\project" C:\project

or just drag the folder in explorer.

Git won't care where it is - all the metadata for the repository is inside a folder called .git inside your project folder.

Cause of a process being a deadlock victim

Here is how this particular deadlock problem actually occurred and how it was actually resolved. This is a fairly active database with 130K transactions occurring daily. The indexes in the tables in this database were originally clustered. The client requested us to make the indexes nonclustered. As soon as we did, the deadlocking began. When we reestablished the indexes as clustered, the deadlocking stopped.

Bootstrap push div content to new line

Do a row div.

Like this:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
        <div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
    </div>_x000D_
    <div class="row">_x000D_
        <div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to check the exit status using an if statement

Every command that runs has an exit status.

That check is looking at the exit status of the command that finished most recently before that line runs.

If you want your script to exit when that test returns true (the previous command failed) then you put exit 1 (or whatever) inside that if block after the echo.

That being said if you are running the command and wanting to test its output using the following is often more straight-forward.

if some_command; then
    echo command returned true
else
    echo command returned some error
fi

Or to turn that around use ! for negation

if ! some_command; then
    echo command returned some error
else
    echo command returned true
fi

Note though that neither of those cares what the error code is. If you know you only care about a specific error code then you need to check $? manually.

NGINX - No input file specified. - php Fast/CGI

Same problem.

Cause : My root wasn't specified in open_basedir.
Fix : Adding my site root directory in :

/etc/php5/fpm/pool.d/mysite.conf<br>

by adding this directive :

php_value[open_basedir] = /my/root/site/dir:/other/directory/allowed

Accessing a matrix element in the "Mat" object (not the CvMat object) in OpenCV C++

On the documentation:

http://docs.opencv.org/2.4/modules/core/doc/basic_structures.html#mat

It says:

(...) if you know the matrix element type, e.g. it is float, then you can use at<>() method

That is, you can use:

Mat M(100, 100, CV_64F);
cout << M.at<double>(0,0);

Maybe it is easier to use the Mat_ class. It is a template wrapper for Mat. Mat_ has the operator() overloaded in order to access the elements.

How to show matplotlib plots in python

In case anyone else ends up here using Jupyter Notebooks, you just need

%matplotlib inline

Purpose of "%matplotlib inline"

Android SDK Manager Not Installing Components

Try running Android Studio as an administrator, by right-clicking on the .exe and selecting "Run As Administrator".

Also, some anti-virus programs have been known to interfere with SDK Manager.

Why should C++ programmers minimize use of 'new'?

The core reason is that objects on heap are always difficult to use and manage than simple values. Writing code that are easy to read and maintain is always the first priority of any serious programmer.

Another scenario is the library we are using provides value semantics and make dynamic allocation unnecessary. Std::string is a good example.

For object oriented code however, using a pointer - which means use new to create it beforehand - is a must. In order to simplify the complexity of resource management, we have dozens of tools to make it as simple as possible, such as smart pointers. The object based paradigm or generic paradigm assumes value semantics and requires less or no new, just as the posters elsewhere stated.

Traditional design patterns, especially those mentioned in GoF book, use new a lot, as they are typical OO code.

How can I reorder my divs using only CSS?

As others have said, this isn't something you'd want to be doing in CSS. You can fudge it with absolute positioning and strange margins, but it's just not a robust solution. The best option in your case would be to turn to javascript. In jQuery, this is a very simple task:

$('#secondDiv').insertBefore('#firstDiv');

or more generically:

$('.swapMe').each(function(i, el) {
    $(el).insertBefore($(el).prev());
});

Leave only two decimal places after the dot

You can use this

"String.Format("{0:F2}", String Value);"

Gives you only the two digits after Dot, exactly two digits.

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

There is a simple, easy and better approach, if we need to change only the color of hamburger/back icon.

It is better as it changes color only of desired icon, whereas colorControlNormal and android:textColorSecondary might affect other childviews of toolbar as well.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

Inserting string at position x of another string

Maybe it's even better if you determine position using indexOf() like this:

function insertString(a, b, at)
{
    var position = a.indexOf(at); 

    if (position !== -1)
    {
        return a.substr(0, position) + b + a.substr(position);    
    }  

    return "substring not found";
}

then call the function like this:

insertString("I want apple", "an ", "apple");

Note, that I put a space after the "an " in the function call, rather than in the return statement.

Postgres: How to convert a json string to text?

An easy way of doing this:

SELECT  ('[' || to_json('Some "text"'::TEXT) || ']')::json ->> 0;

Just convert the json string into a json list

How can I convert this foreach code to Parallel.ForEach?

For big file use the following code (you are less memory hungry)

Parallel.ForEach(File.ReadLines(txtProxyListPath.Text), line => {
    //Your stuff
});

How to get numeric value from a prompt box?

var xInt = parseInt(x)

This will return either the integer value, or NaN.

Read more about parseInt here.

Push origin master error on new repository

Bumping an old thread.

If you have created a repository on Github with a Readme or a .gitignore, you might have to rebase the local master with the remote master. Because, if you are using a project scaffolding tool, like create-app, it creates these files for you, and the remote master needs to be synced with your local before you push.

If you are creating an empty repository on Github, then you can simply push.

Shall we always use [unowned self] inside closure in Swift

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        let storyboard = UIStoryboard(name: "Main", bundle: nil)
        let controller = storyboard.instantiateViewController(withIdentifier: "AnotherViewController")
        self.navigationController?.pushViewController(controller, animated: true)

    }

}



import UIKit
class AnotherViewController: UIViewController {

    var name : String!

    deinit {
        print("Deint AnotherViewController")
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        print(CFGetRetainCount(self))

        /*
            When you test please comment out or vice versa

         */

//        // Should not use unowned here. Because unowned is used where not deallocated. or gurranted object alive. If you immediate click back button app will crash here. Though there will no retain cycles
//        clouser(string: "") { [unowned self] (boolValue)  in
//            self.name = "some"
//        }
//


//
//        // There will be a retain cycle. because viewcontroller has a strong refference to this clouser and as well as clouser (self.name) has a strong refferennce to the viewcontroller. Deint AnotherViewController will not print
//        clouser(string: "") { (boolValue)  in
//            self.name = "some"
//        }
//
//


//        // no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser (self.name) has a weak refferennce to the viewcontroller. Deint AnotherViewController will  print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)
//
//        clouser(string: "") { [weak self] (boolValue)  in
//            self?.name = "some"
//        }


        // no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser nos refference to the viewcontroller. Deint AnotherViewController will  print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)

        clouser(string: "") {  (boolValue)  in
            print("some")
            print(CFGetRetainCount(self))

        }

    }


    func clouser(string: String, completion: @escaping (Bool) -> ()) {
        // some heavy task
        DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
            completion(true)
        }

    }

}

If you do not sure about [unowned self] then use [weak self]

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

I actually ended up with something like this to allow for the navbar collapse.

@media (min-width: 768px) { //set this to wherever the navbar collapse executes
  .navbar-nav > li > a{
    line-height: 7em; //set this height to the height of the logo.
  }
}

PuTTY scripting to log onto host

You can use the -i privatekeyfilelocation in case you are using a private key instead of password based.

How to read the RGB value of a given pixel in Python?

Using Pillow (which works with Python 3.X as well as Python 2.7+), you can do the following:

from PIL import Image
im = Image.open('image.jpg', 'r')
width, height = im.size
pixel_values = list(im.getdata())

Now you have all pixel values. If it is RGB or another mode can be read by im.mode. Then you can get pixel (x, y) by:

pixel_values[width*y+x]

Alternatively, you can use Numpy and reshape the array:

>>> pixel_values = numpy.array(pixel_values).reshape((width, height, 3))
>>> x, y = 0, 1
>>> pixel_values[x][y]
[ 18  18  12]

A complete, simple to use solution is

# Third party modules
import numpy
from PIL import Image


def get_image(image_path):
    """Get a numpy array of an image so that one can access values[x][y]."""
    image = Image.open(image_path, "r")
    width, height = image.size
    pixel_values = list(image.getdata())
    if image.mode == "RGB":
        channels = 3
    elif image.mode == "L":
        channels = 1
    else:
        print("Unknown mode: %s" % image.mode)
        return None
    pixel_values = numpy.array(pixel_values).reshape((width, height, channels))
    return pixel_values


image = get_image("gradient.png")

print(image[0])
print(image.shape)

Smoke testing the code

You might be uncertain about the order of width / height / channel. For this reason I've created this gradient:

enter image description here

The image has a width of 100px and a height of 26px. It has a color gradient going from #ffaa00 (yellow) to #ffffff (white). The output is:

[[255 172   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 172   5]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   4]
 [255 172   5]
 [255 171   5]
 [255 171   5]
 [255 172   5]]
(100, 26, 3)

Things to note:

  • The shape is (width, height, channels)
  • The image[0], hence the first row, has 26 triples of the same color

Matplotlib 2 Subplots, 1 Colorbar

Just place the colorbar in its own axis and use subplots_adjust to make room for it.

As a quick example:

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=2, ncols=2)
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

fig.subplots_adjust(right=0.8)
cbar_ax = fig.add_axes([0.85, 0.15, 0.05, 0.7])
fig.colorbar(im, cax=cbar_ax)

plt.show()

enter image description here

Note that the color range will be set by the last image plotted (that gave rise to im) even if the range of values is set by vmin and vmax. If another plot has, for example, a higher max value, points with higher values than the max of im will show in uniform color.

Android Studio Gradle DSL method not found: 'android()' -- Error(17,0)

For some unknown reason, Android Studio incorrectly adds the android() method in the top-level build.gradle file.

Just delete the method and it works for me.

android {
    compileSdkVersion 21
    buildToolsVersion '21.1.2'
}

ReactJS: setTimeout() not working?

Your code scope (this) will be your window object, not your react component, and that is why setTimeout(this.setState({position: 1}), 3000) will crash this way.

That comes from javascript not React, it is js closure


So, in order to bind your current react component scope, do this:

setTimeout(function(){this.setState({position: 1})}.bind(this), 3000);

Or if your browser supports es6 or your projs has support to compile es6 to es5, try arrow function as well, as arrow func is to fix 'this' issue:

setTimeout(()=>this.setState({position: 1}), 3000);

How to specify the port an ASP.NET Core application is hosted on?

In ASP.NET Core 3.1, there are 4 main ways to specify a custom port:

  • Using command line arguments, by starting your .NET application with --urls=[url]:
dotnet run --urls=http://localhost:5001/
  • Using appsettings.json, by adding a Urls node:
{
  "Urls": "http://localhost:5001"
}
  • Using environment variables, with ASPNETCORE_URLS=http://localhost:5001/.
  • Using UseUrls(), if you prefer doing it programmatically:
public static class Program
{
    public static void Main(string[] args) =>
        CreateHostBuilder(args).Build().Run();

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(builder =>
            {
                builder.UseStartup<Startup>();
                builder.UseUrls("http://localhost:5001/");
            });
}

Or, if you're still using the web host builder instead of the generic host builder:

public class Program
{
    public static void Main(string[] args) =>
        new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://localhost:5001/")
            .Build()
            .Run();
}

Android How to adjust layout in Full Screen Mode when softkeyboard is visible

I just found a simple and reliable solution if you are using the system UI approach (https://developer.android.com/training/system-ui/immersive.html).

It works in the case when you are using View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN, e.g. if you are using CoordinatorLayout.

It won't work for WindowManager.LayoutParams.FLAG_FULLSCREEN (The one you can also set in theme with android:windowFullscreen), but you can achieve similar effect with SYSTEM_UI_FLAG_LAYOUT_STABLE (which "has the same visual effect" according to the docs) and this solution should work again.

getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION /* If you want to hide navigation */
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE)

I've tested it on my device running Marshmallow.

The key is that soft keyboards are also one of the system windows (such as status bar and navigation bar), so the WindowInsets dispatched by system contains accurate and reliable information about it.

For the use case such as in DrawerLayout where we are trying to draw behind the status bar, We can create a layout that ignores only the top inset, and applies the bottom inset which accounts for the soft keyboard.

Here is my custom FrameLayout:

/**
 * Implements an effect similar to {@code android:fitsSystemWindows="true"} on Lollipop or higher,
 * except ignoring the top system window inset. {@code android:fitsSystemWindows="true"} does not
 * and should not be set on this layout.
 */
public class FitsSystemWindowsExceptTopFrameLayout extends FrameLayout {

    public FitsSystemWindowsExceptTopFrameLayout(Context context) {
        super(context);
    }

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                 int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @RequiresApi(Build.VERSION_CODES.LOLLIPOP)
    public FitsSystemWindowsExceptTopFrameLayout(Context context, AttributeSet attrs,
                                                 int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public WindowInsets onApplyWindowInsets(WindowInsets insets) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            setPadding(insets.getSystemWindowInsetLeft(), 0, insets.getSystemWindowInsetRight(),
                    insets.getSystemWindowInsetBottom());
            return insets.replaceSystemWindowInsets(0, insets.getSystemWindowInsetTop(), 0, 0);
        } else {
            return super.onApplyWindowInsets(insets);
        }
    }
}

And to use it:

<com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- Your original layout here -->
</com.example.yourapplication.FitsSystemWindowsExceptTopFrameLayout>

This should theoretically work for any device without insane modification, much better than any hack that tries to take a random 1/3 or 1/4 of screen size as reference.

(It requires API 16+, but I'm using fullscreen only on Lollipop+ for drawing behind the status bar so it's the best solution in this case.)

How to destroy JWT Tokens on logout?

You can add "issue time" to token and maintain "last logout time" for each user on the server. When you check token validity, also check "issue time" be after "last logout time".

Subclipse svn:ignore

I just figured out how to do this:

It appears that when you add a parent folder to version control, Eclipse adds all sub-folders. Once the sub-folders are added to version control, it is not possible to ignore them.

Here's how to do it:

Right click on the top level folder and add to version control Right click on the child folder you want to ignore, revert Right click on the child folder you want to ignore, svn:ignore (which will now be available)

Laravel 5 Clear Views Cache

To get all the artisan command, type...

php artisan

If you want to clear view cache, just use:

php artisan view:clear

If you don't know how to use specific artisan command, just add "help" (see below)

php artisan help view:clear

How many characters can you store with 1 byte?

Yes, 1 byte does encode a character (inc spaces etc) from the ASCII set. However in data units assigned to character encoding it can and often requires in practice up to 4 bytes. This is because English is not the only character set. And even in English documents other languages and characters are often represented. The numbers of these are very many and there are very many other encoding sets, which you may have heard of e.g. BIG-5, UTF-8, UTF-32. Most computers now allow for these uses and ensure the least amount of garbled text (which usually means a missing encoding set.) 4 bytes is enough to cover these possible encodings. I byte per character does not allow for this and in use it is larger often 4 bytes per possible character for all encodings, not just ASCII. The final character may only need a byte to function or be represented on screen, but requires 4 bytes to be located in the rather vast global encoding "works".

How do I create a message box with "Yes", "No" choices and a DialogResult?

@Mikael Svenson's answer is correct. I just wanted to add a small addition to it:

The Messagebox icon can also be included has an additional property like below:

DialogResult dialogResult = MessageBox.Show("Sure", "Please Confirm Your Action", MessageBoxButtons.YesNo, MessageBoxIcon.Question);

Correct path for img on React.js

In create-react-app relative paths for images don't seem to work. Instead, you can import an image:

import logo from './logo.png' // relative path to image 

class Nav extends Component { 
    render() { 
        return ( 
            <img src={logo} alt={"logo"}/> 
        )  
    }
}

ProcessBuilder: Forwarding stdout and stderr of started processes without blocking the main thread

Thread thread = new Thread(() -> {
      new BufferedReader(
          new InputStreamReader(inputStream, 
                                StandardCharsets.UTF_8))
              .lines().forEach(...);
    });
    thread.start();

Your custom code goes instead of the ...

How to set 24-hours format for date on java?

Use HH instead of hh in formatter string

Why did my Git repo enter a detached HEAD state?

Detached HEAD means that what's currently checked out is not a local branch.

Some scenarios that will result in a Detached HEAD state:

  • If you checkout a remote branch, say origin/master. This is a read-only branch. Thus, when creating a commit from origin/master it will be free-floating, i.e. not connected to any branch.

  • If you checkout a specific tag or commit. When doing a new commit from here, it will again be free-floating, i.e. not connected to any branch. Note that when a branch is checked out, new commits always gets automatically placed at the tip.

    When you want to go back and checkout a specific commit or tag to start working from there, you could create a new branch originating from that commit and switch to it by git checkout -b new_branch_name. This will prevent the Detached HEAD state as you now have a branch checked out and not a commit.

javac not working in windows command prompt

Try the solutions here: http://techdem.centerkey.com/2009/05/javahome-command-script.html

These are much more robust to change -- like when you upgrade the JDK or JRE, since there is no hard coded path.

The quick solution (if you don't want to read the blog) is

C:\>for /d %i in ("\Program Files\Java\jdk*") do set JAVA_HOME=%i
C:\>set PATH=%PATH%;%JAVA_HOME%

You can then add these lines to a startup/login script.

Vue.js - How to properly watch for nested data

Here's a way to write watchers for nested properties:

    new Vue({
        ...allYourOtherStuff,
        watch: {
            ['foo.bar'](newValue, oldValue) {
                // Do stuff here
            }
        }
    });

You can even use this syntax for asynchronous watchers:

    new Vue({
        ...allYourOtherStuff,
        watch: {
            async ['foo.bar'](newValue, oldValue) {
                // Do stuff here
            }
        }
    });

Count unique values in a column in Excel

Count unique with a condition. Col A is ID and using condition ID=32, Col B is Name and we are trying to count the unique names for a particular ID

=SUMPRODUCT((B2:B12<>"")*(A2:A12=32)/COUNTIF(B2:B12,B2:B12))

How to compare each item in a list with the rest, only once?

Of course this will generate each pair twice as each for loop will go through every item of the list.

You could use some itertools magic here to generate all possible combinations:

import itertools
for a, b in itertools.combinations(mylist, 2):
    compare(a, b)

itertools.combinations will pair each element with each other element in the iterable, but only once.


You could still write this using index-based item access, equivalent to what you are used to, using nested for loops:

for i in range(len(mylist)):
    for j in range(i + 1, len(mylist)):
        compare(mylist[i], mylist[j])

Of course this may not look as nice and pythonic but sometimes this is still the easiest and most comprehensible solution, so you should not shy away from solving problems like that.

How to handle static content in Spring MVC?

My way of solving this problem is placing all your actions with a specific prefix like "web" or "service" and configure that all url's with that prefix will be intercepted by the DispatcherServlet.

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)

Git diff -w ignore whitespace only at start & end of lines

For end of line use:

git diff --ignore-space-at-eol

Instead of what are you using currently:

git diff -w (--ignore-all-space)

For start of line... you are out of luck if you want a built in solution.

However, if you don't mind getting your hands dirty there's a rather old patch floating out there somewhere that adds support for "--ignore-space-at-sol".

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

How to replace a string in an existing file in Perl?

It can be done using a single line:

perl -pi.back -e 's/oldString/newString/g;' inputFileName

Pay attention that oldString is processed as a Regular Expression.
In case the string contains any of {}[]()^$.|*+? (The special characters for Regular Expression syntax) make sure to escape them unless you want it to be processed as a regular expression.
Escaping it is done by \, so \[.

reactjs giving error Uncaught TypeError: Super expression must either be null or a function, not undefined

This means that you want subclass something, which should be Class, but is undefined. The reasons might be:

  • typo in Class extends ..., so you extending undefined variable
  • typo in import ... from, so you import undefined from module
  • referenced module does not contain the value, you want import (e.g. obsolete module - case with React), so you importing non existing value (undefined)
  • typo in referenced module export ... statement, so it exports undefined variable
  • referenced module missing export statement at all, so it exports just undefined

SELECT INTO using Oracle

Use:

create table new_table_name 
as
select column_name,[more columns] from Existed_table;

Example:

create table dept
as
select empno, ename from emp;

If the table already exists:

insert into new_tablename select columns_list from Existed_table;

What's the best way to dedupe a table?

Here's the method I use if you can get your dupe criteria into a group by statement and your table has an id identity column for uniqueness:

delete t
from tablename t
inner join  
(
    select date_time, min(id) as min_id
    from tablename
    group by date_time
    having count(*) > 1
) t2 on t.date_time = t2.date_time
where t.id > t2.min_id

In this example the date_time is the grouping criteria, if you have more than one column make sure to join on all of them.

Numpy `ValueError: operands could not be broadcast together with shape ...`

If X and beta do not have the same shape as the second term in the rhs of your last line (i.e. nsample), then you will get this type of error. To add an array to a tuple of arrays, they all must be the same shape.

I would recommend looking at the numpy broadcasting rules.

Find and replace with a newline in Visual Studio Code

In version 1.1.1:

  • Ctrl+H
  • Check the regular exp icon .*
  • Search: ><
  • Replace: >\n<

Get LatLng from Zip Code - Google Maps API

Couldn't you just call the following replaceing the {zipcode} with the zip code or city and state http://maps.googleapis.com/maps/api/geocode/json?address={zipcode}

Google Geocoding

Here is a link with a How To Geocode using JavaScript: Geocode walk-thru. If you need the specific lat/lng numbers call geometry.location.lat() or geometry.location.lng() (API for google.maps.LatLng class)

EXAMPLE to get lat/lng:

    var lat = '';
    var lng = '';
    var address = {zipcode} or {city and state};
    geocoder.geocode( { 'address': address}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
         lat = results[0].geometry.location.lat();
         lng = results[0].geometry.location.lng();
        });
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
    alert('Latitude: ' + lat + ' Logitude: ' + lng);

dictionary update sequence element #0 has length 3; 2 is required

This error raised up because you trying to update dict object by using a wrong sequence (list or tuple) structure.

cash_id.create(cr, uid, lines,context=None) trying to convert lines into dict object:

(0, 0, {
    'name': l.name,
    'date': l.date,
    'amount': l.amount,
    'type': l.type,
    'statement_id': exp.statement_id.id,
    'account_id': l.account_id.id,
    'account_analytic_id': l.analytic_account_id.id,
    'ref': l.ref,
    'note': l.note,
    'company_id': l.company_id.id
})

Remove the second zero from this tuple to properly convert it into a dict object.

To test it your self, try this into python shell:

>>> l=[(0,0,{'h':88})]
>>> a={}
>>> a.update(l)

Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    a.update(l)
ValueError: dictionary update sequence element #0 has length 3; 2 is required

>>> l=[(0,{'h':88})]
>>> a.update(l)

Create a CSV File for a user in PHP

Hey It works very well....!!!! Thanks Peter Mortensen and Connor Burton

<?php
header("Content-type: application/csv");
header("Content-Disposition: attachment; filename=file.csv");
header("Pragma: no-cache");
header("Expires: 0");

ini_set('display_errors',1);
$private=1;
error_reporting(E_ALL ^ E_NOTICE);

mysql_connect("localhost", "user", "pass") or die(mysql_error());
mysql_select_db("db") or die(mysql_error());

$start = $_GET["start"];
$end = $_GET["end"];

$query = "SELECT * FROM customers WHERE created>='{$start} 00:00:00'  AND created<='{$end} 23:59:59'   ORDER BY id";
$select_c = mysql_query($query) or die(mysql_error());

while ($row = mysql_fetch_array($select_c, MYSQL_ASSOC))
{
    $result.="{$row['email']},";
    $result.="\n";
    echo $result;
}

?>

Use querystring variables in MVC controller

I had this problem while inheriting from ApiController instead of the regular Controller class. I solved it by using var container = Request.GetQueryNameValuePairs().ToLookup(x => x.Key, x => x.Value);

I followed this thread How to get Request Querystring values?

EDIT: After trying to filter through the container I was getting odd error messages. After going to my project properties and I unchecked the Optimize Code checkbox which changed so that all of a sudden the parameters in my controller where filled up from the url as I wanted.

Hopefully this will help someone with the same problem..

Fastest way to zero out a 2d array in C?

memset(array, 0, sizeof(int [n][n]));

TypeError: 'function' object is not subscriptable - Python

You have two objects both named bank_holiday -- one a list and one a function. Disambiguate the two.

bank_holiday[month] is raising an error because Python thinks bank_holiday refers to the function (the last object bound to the name bank_holiday), whereas you probably intend it to mean the list.

Declaring variables inside loops, good practice or bad practice?

Declaring variables inside or outside of a loop, It's the result of JVM specifications But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used). Declaring objects in the smallest scope improve readability. The scope of local variables should always be the smallest possible. In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.

Does it make a difference if I declare variables inside or outside a , Does it make a difference if I declare variables inside or outside a loop in Java? Is this for(int i = 0; i < 1000; i++) { int At the level of the individual variable there is no significant difference in effeciency, but if you had a function with 1000 loops and 1000 variables (never mind the bad style implied) there could be systemic differences because all the lives of all the variables would be the same instead of overlapped.

Declaring Loop Control Variables Inside the for Loop, When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) This Java Example shows how to declare multiple variables in Java For loop using declaration block.

How to modify a specified commit?

I solved this,

1) by creating new commit with changes i want..

r8gs4r commit 0

2) i know which commit i need to merge with it. which is commit 3.

so, git rebase -i HEAD~4 # 4 represents recent 4 commit (here commit 3 is in 4th place)

3) in interactive rebase recent commit will located at bottom. it will looks alike,

pick q6ade6 commit 3
pick vr43de commit 2
pick ac123d commit 1
pick r8gs4r commit 0

4) here we need to rearrange commit if you want to merge with specific one. it should be like,

parent
|_child

pick q6ade6 commit 3
f r8gs4r commit 0
pick vr43de commit 2
pick ac123d commit 1

after rearrange you need to replace p pick with f (fixup will merge without commit message) or s (squash merge with commit message can change in run time)

and then save your tree.

now merge done with existing commit.

Note: Its not preferable method unless you're maintain on your own. if you have big team size its not a acceptable method to rewrite git tree will end up in conflicts which you know other wont. if you want to maintain you tree clean with less commits can try this and if its small team otherwise its not preferable.....

Move an array element from one array position to another

I used the nice answer of @Reid, but struggled with moving an element from the end of an array one step further - to the beginning (like in a loop). E.g. ['a', 'b', 'c'] should become ['c', 'a', 'b'] by calling .move(2,3)

I achieved this by changing the case for new_index >= this.length.

Array.prototype.move = function (old_index, new_index) {
        console.log(old_index + " " + new_index);
        while (old_index < 0) {
            old_index += this.length;
        }
        while (new_index < 0) {
            new_index += this.length;
        }
        if (new_index >= this.length) {
            new_index = new_index % this.length;
        }
        this.splice(new_index, 0, this.splice(old_index, 1)[0]);
        return this; // for testing purposes
    };

How are VST Plugins made?

I realize this is a very old post, but I have had success using the JUCE library, which builds projects for the major IDE's like Xcode, VS, and Codeblocks and automatically builds VST/3, AU/v3, RTAS, and AAX.

https://www.juce.com/

Make HTML5 video poster be same size as video itself

height:500px;
min-width:100%;
-webkit-background-size: 100% 100%;
-moz-background-size: 100% 100%;
-o-background-size: 100% 100%;
background-size:100% 100%;
object-fit:cover;

-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size:cover;

Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION]

For Python2 WIN10 Users:

1.Uninstall python thoroughly ,include all folders.

2.Fetch and install the lastest python-2.7.msi (ver 2.7.15)

3.After step 2,you may find pip had been installed too.

4.Now ,if your system'env haven't been changed,you can use pip to install packages now.The "tlsv1 alert protocol version" will not appear.

Oracle date to string conversion

If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):

SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1

The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.

Can someone explain how to implement the jQuery File Upload plugin?

I was looking for a similar functionality some days back and came across a good tutorial on tutorialzine. Here is an working example. Complete tutorial can be found here.

Simple form to hold the file upload dialogue:

<form id="upload" method="post" action="upload.php" enctype="multipart/form-data">
  <input type="file" name="uploadctl" multiple />
  <ul id="fileList">
    <!-- The file list will be shown here -->
  </ul>
</form>

And here is the jQuery code to upload the files:

$('#upload').fileupload({

  // This function is called when a file is added to the queue
  add: function (e, data) {
    //This area will contain file list and progress information.
    var tpl = $('<li class="working">'+
                '<input type="text" value="0" data-width="48" data-height="48" data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />'+
                '<p></p><span></span></li>' );

    // Append the file name and file size
    tpl.find('p').text(data.files[0].name)
                 .append('<i>' + formatFileSize(data.files[0].size) + '</i>');

    // Add the HTML to the UL element
    data.context = tpl.appendTo(ul);

    // Initialize the knob plugin. This part can be ignored, if you are showing progress in some other way.
    tpl.find('input').knob();

    // Listen for clicks on the cancel icon
    tpl.find('span').click(function(){
      if(tpl.hasClass('working')){
              jqXHR.abort();
      }
      tpl.fadeOut(function(){
              tpl.remove();
      });
    });

    // Automatically upload the file once it is added to the queue
    var jqXHR = data.submit();
  },
  progress: function(e, data){

        // Calculate the completion percentage of the upload
        var progress = parseInt(data.loaded / data.total * 100, 10);

        // Update the hidden input field and trigger a change
        // so that the jQuery knob plugin knows to update the dial
        data.context.find('input').val(progress).change();

        if(progress == 100){
            data.context.removeClass('working');
        }
    }
});
//Helper function for calculation of progress
function formatFileSize(bytes) {
    if (typeof bytes !== 'number') {
        return '';
    }

    if (bytes >= 1000000000) {
        return (bytes / 1000000000).toFixed(2) + ' GB';
    }

    if (bytes >= 1000000) {
        return (bytes / 1000000).toFixed(2) + ' MB';
    }
    return (bytes / 1000).toFixed(2) + ' KB';
}

And here is the PHP code sample to process the data:

if($_POST) {
    $allowed = array('jpg', 'jpeg');

    if(isset($_FILES['uploadctl']) && $_FILES['uploadctl']['error'] == 0){

        $extension = pathinfo($_FILES['uploadctl']['name'], PATHINFO_EXTENSION);

        if(!in_array(strtolower($extension), $allowed)){
            echo '{"status":"error"}';
            exit;
        }

        if(move_uploaded_file($_FILES['uploadctl']['tmp_name'], "/yourpath/." . $extension)){
            echo '{"status":"success"}';
            exit;
        }
        echo '{"status":"error"}';
    }
    exit();
}

The above code can be added to any existing form. This program automatically uploads images, once they are added. This functionality can be changed and you can submit the image, while you are submitting your existing form.

Updated my answer with actual code. All credits to original author of the code.

Source: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/

SQL Group By with an Order By

In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:

SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20

How do I get user IP address in django?

The reason the functionality was removed from Django originally was that the header cannot ultimately be trusted. The reason is that it is easy to spoof. For example the recommended way to configure an nginx reverse proxy is to:

add_header X-Forwarded-For $proxy_add_x_forwarded_for;
add_header X-Real-Ip       $remote_addr;

When you do:

curl -H 'X-Forwarded-For: 8.8.8.8, 192.168.1.2' http://192.168.1.3/

Your nginx in myhost.com will send onwards:

X-Forwarded-For: 8.8.8.8, 192.168.1.2, 192.168.1.3

The X-Real-IP will be the IP of the first previous proxy if you follow the instructions blindly.

In case trusting who your users are is an issue, you could try something like django-xff: https://pypi.python.org/pypi/django-xff/

Deserialize JSON into C# dynamic object?

try this way!

JSON example:

  [{
            "id": 140,
            "group": 1,
            "text": "xxx",
            "creation_date": 123456,
            "created_by": "[email protected]",
            "tags": ["xxxxx"]
        }, {
            "id": 141,
            "group": 1,
            "text": "xxxx",
            "creation_date": 123456,
            "created_by": "[email protected]",
            "tags": ["xxxxx"]
        }]

C# code:

        var jsonString = (File.ReadAllText(Path.Combine(Directory.GetCurrentDirectory(),"delete_result.json")));
        var objects = JsonConvert.DeserializeObject<dynamic>(jsonString);
        foreach(var o in objects)
        {
            Console.WriteLine($"{o.id.ToString()}");
        }

Getting error: ISO C++ forbids declaration of with no type

You forgot the return types in your member function definitions:

int ttTree::ttTreeInsert(int value) { ... }
^^^               

and so on.

IndexOf function in T-SQL

I believe you want to use CHARINDEX. You can read about it here.

Xcode 5.1 - No architectures to compile for (ONLY_ACTIVE_ARCH=YES, active arch=x86_64, VALID_ARCHS=i386)

In acrhiecture - sometimes to support 6.0 and 7.0 , we exlude arm64

In architectures - > acrchitecture - select standard architecture arm64 armv7 armv7s. Just below in Valid acrchitecture make user arm64 armv7 armv7s is included. This worked for me.

ToString() function in Go

When you have own struct, you could have own convert-to-string function.

package main

import (
    "fmt"
)

type Color struct {
    Red   int `json:"red"`
    Green int `json:"green"`
    Blue  int `json:"blue"`
}

func (c Color) String() string {
    return fmt.Sprintf("[%d, %d, %d]", c.Red, c.Green, c.Blue)
}

func main() {
    c := Color{Red: 123, Green: 11, Blue: 34}
    fmt.Println(c) //[123, 11, 34]
}

HTML Script tag: type or language (or omit both)?

The type attribute is used to define the MIME type within the HTML document. Depending on what DOCTYPE you use, the type value is required in order to validate the HTML document.

The language attribute lets the browser know what language you are using (Javascript vs. VBScript) but is not necessarily essential and, IIRC, has been deprecated.

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

You can still use the textmode and force the linefeed-newline with the keyword argument newline

f = open("./foo",'w',newline='\n')

Tested with Python 3.4.2.

Edit: This does not work in Python 2.7.

How to access a DOM element in React? What is the equilvalent of document.getElementById() in React

Since React uses JSX code to create an HTML we cannot refer dom using regulation methods like documment.querySelector or getElementById.

Instead we can use React ref system to access and manipulate Dom as shown in below example:

constructor(props){

    super(props);
    this.imageRef = React.createRef(); // create react ref
}

componentDidMount(){

    **console.log(this.imageRef)** // acessing the attributes of img tag when dom loads
}


render = (props) => {

const {urls,description} = this.props.image;
    return (

            <img
             **ref = {this.imageRef} // assign the ref of img tag here**
             src = {urls.regular} 
             alt = {description}
             />

        );

}

}

Excel 2010: how to use autocomplete in validation list

=OFFSET(NameList!$A$2:$A$200,MATCH(INDIRECT("FillData!"&ADDRESS(ROW(),COLUMN(),4))&"*",NameList!$A$2:$A$200,0)-1,0,COUNTIF($A$2:$A$200,INDIRECT("FillData!"&ADDRESS(ROW(),COLUMN(),4))&"*"),1)
  1. Create sheet name as Namelist. In column A fill list of data.

  2. Create another sheet name as FillData for making data validation list as you want.

  3. Type first alphabet and select, drop down menu will appear depend on you type.