Programs & Examples On #Netduino

Netduino is an open-source electronics platform using the .NET Micro Framework.

How do I parse a URL query parameters, in Javascript?

You could get a JavaScript object containing the parameters with something like this:

var regex = /[?&]([^=#]+)=([^&#]*)/g,
    url = window.location.href,
    params = {},
    match;
while(match = regex.exec(url)) {
    params[match[1]] = match[2];
}

The regular expression could quite likely be improved. It simply looks for name-value pairs, separated by = characters, and pairs themselves separated by & characters (or an = character for the first one). For your example, the above would result in:

{v: "123", p: "hello"}

Here's a working example.

Can I get all methods of a class?

To know about all methods use this statement in console:

javap -cp jar-file.jar packagename.classname

or

javap class-file.class packagename.classname

or for example:

javap java.lang.StringBuffer

Arrays in unix shell?

The following code creates and prints an array of strings in shell:

#!/bin/bash
array=("A" "B" "ElementC" "ElementE")
for element in "${array[@]}"
do
    echo "$element"
done

echo
echo "Number of elements: ${#array[@]}"
echo
echo "${array[@]}"

Result:

A
B
ElementC
ElementE

Number of elements: 4

A B ElementC ElementE

get the value of input type file , and alert if empty

HTML Code

<input type="file" name="image" id="uploadImage" size="30" />
<input type="submit" name="upload"  class="send_upload" value="upload" />

jQuery Code using bind method

$(document).ready(function() {
    $('#upload').bind("click",function() 
    { if(!$('#uploadImage').val()){
                alert("empty");
                return false;} });  });

How to call a RESTful web service from Android?

I used OkHttpClient to call restful web service. It's very simple.

OkHttpClient httpClient = new OkHttpClient();
Request request = new Request.Builder()
                .url(url)
                .build();

Response response = httpClient.newCall(request).execute();
String body = response.body().string()

Background blur with CSS

You can use a pseudo-element to position as the background of the content with the same image as the background, but blurred with the new CSS3 filter.

You can see it in action here: http://codepen.io/jiserra/pen/JzKpx

I made that for customizing a select, but I added the blur background effect.

How to read until EOF from cin in C++

You can do it without explicit loops by using stream iterators. I'm sure that it uses some kind of loop internally.

#include <string>
#include <iostream>
#include <istream>
#include <ostream>
#include <iterator>

int main()
{
// don't skip the whitespace while reading
  std::cin >> std::noskipws;

// use stream iterators to copy the stream to a string
  std::istream_iterator<char> it(std::cin);
  std::istream_iterator<char> end;
  std::string results(it, end);

  std::cout << results;
}

Class type check in TypeScript

You can use the instanceof operator for this. From MDN:

The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.

If you don't know what prototypes and prototype chains are I highly recommend looking it up. Also here is a JS (TS works similar in this respect) example which might clarify the concept:

_x000D_
_x000D_
    class Animal {_x000D_
        name;_x000D_
    _x000D_
        constructor(name) {_x000D_
            this.name = name;_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    const animal = new Animal('fluffy');_x000D_
    _x000D_
    // true because Animal in on the prototype chain of animal_x000D_
    console.log(animal instanceof Animal); // true_x000D_
    // Proof that Animal is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(animal) === Animal.prototype); // true_x000D_
    _x000D_
    // true because Object in on the prototype chain of animal_x000D_
    console.log(animal instanceof Object); _x000D_
    // Proof that Object is on the prototype chain_x000D_
    console.log(Object.getPrototypeOf(Animal.prototype) === Object.prototype); // true_x000D_
    _x000D_
    console.log(animal instanceof Function); // false, Function not on prototype chain_x000D_
    _x000D_
    
_x000D_
_x000D_
_x000D_

The prototype chain in this example is:

animal > Animal.prototype > Object.prototype

What is the purpose of Node.js module.exports and how do you use it?

What is the purpose of a module system?

It accomplishes the following things:

  1. Keeps our files from bloating to really big sizes. Having files with e.g. 5000 lines of code in it are usually real hard to deal with during development.
  2. Enforces separation of concerns. Having our code split up into multiple files allows us to have appropriate file names for every file. This way we can easily identify what every module does and where to find it (assuming we made a logical directory structure which is still your responsibility).

Having modules makes it easier to find certain parts of code which makes our code more maintainable.

How does it work?

NodejS uses the CommomJS module system which works in the following manner:

  1. If a file wants to export something it has to declare it using module.export syntax
  2. If a file wants to import something it has to declare it using require('file') syntax

Example:

test1.js

const test2 = require('./test2');    // returns the module.exports object of a file

test2.Func1(); // logs func1
test2.Func2(); // logs func2

test2.js

module.exports.Func1 = () => {console.log('func1')};

exports.Func2 = () => {console.log('func2')};

Other useful things to know:

  1. Modules are getting cached. When you are loading the same module in 2 different files the module only has to be loaded once. The second time a require() is called on the same module the is pulled from the cache.
  2. Modules are loaded in synchronous. This behavior is required, if it was asynchronous we couldn't access the object retrieved from require() right away.

C# Public Enums in Classes

You need to define the enum outside of the class.

public enum card_suits
{
    Clubs,
    Hearts,
    Spades,
    Diamonds
}

public class Card
{
     // ...

That being said, you may also want to consider using the standard naming guidelines for Enums, which would be CardSuit instead of card_suits, since Pascal Casing is suggested, and the enum is not marked with the FlagsAttribute, suggesting multiple values are appropriate in a single variable.

Count work days between two dates

(I'm a few points shy of commenting privileges)

If you decide to forgo the +1 day in CMS's elegant solution, note that if your start date and end date are in the same weekend, you get a negative answer. Ie., 2008/10/26 to 2008/10/26 returns -1.

my rather simplistic solution:

select @Result = (..CMS's answer..)
if  (@Result < 0)
        select @Result = 0
    RETURN @Result

.. which also sets all erroneous posts with start date after end date to zero. Something you may or may not be looking for.

Determine if $.ajax error is a timeout

If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.

Per the jQuery documentation:

Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".

You can handle your error accordingly then.

I created this fiddle that demonstrates this.

$.ajax({
    url: "/ajax_json_echo/",
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(response) { alert(response); },
    error: function(xmlhttprequest, textstatus, message) {
        if(textstatus==="timeout") {
            alert("got timeout");
        } else {
            alert(textstatus);
        }
    }
});?

With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.

Hope this helps!

Access PHP variable in JavaScript

You can't, you'll have to do something like

<script type="text/javascript">
   var php_var = "<?php echo $php_var; ?>";
</script>

You can also load it with AJAX

rhino is right, the snippet lacks of a type for the sake of brevity.

Also, note that if $php_var has quotes, it will break your script. You shall use addslashes, htmlentities or a custom function.

Determining the current foreground application from a background task or service

i had to figure out the right solution the hard way. the below code is part of cyanogenmod7 (the tablet tweaks) and is tested on android 2.3.3 / gingerbread.

methods:

  • getForegroundApp - returns the foreground application.
  • getActivityForApp - returns the activity of the found app.
  • isStillActive - determines if a earlier found app is still the active app.
  • isRunningService - a helper function for getForegroundApp

this hopefully answers this issue in all extend (:

private RunningAppProcessInfo getForegroundApp() {
    RunningAppProcessInfo result=null, info=null;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <RunningAppProcessInfo> l = mActivityManager.getRunningAppProcesses();
    Iterator <RunningAppProcessInfo> i = l.iterator();
    while(i.hasNext()){
        info = i.next();
        if(info.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND
                && !isRunningService(info.processName)){
            result=info;
            break;
        }
    }
    return result;
}

private ComponentName getActivityForApp(RunningAppProcessInfo target){
    ComponentName result=null;
    ActivityManager.RunningTaskInfo info;

    if(target==null)
        return null;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <ActivityManager.RunningTaskInfo> l = mActivityManager.getRunningTasks(9999);
    Iterator <ActivityManager.RunningTaskInfo> i = l.iterator();

    while(i.hasNext()){
        info=i.next();
        if(info.baseActivity.getPackageName().equals(target.processName)){
            result=info.topActivity;
            break;
        }
    }

    return result;
}

private boolean isStillActive(RunningAppProcessInfo process, ComponentName activity)
{
    // activity can be null in cases, where one app starts another. for example, astro
    // starting rock player when a move file was clicked. we dont have an activity then,
    // but the package exits as soon as back is hit. so we can ignore the activity
    // in this case
    if(process==null)
        return false;

    RunningAppProcessInfo currentFg=getForegroundApp();
    ComponentName currentActivity=getActivityForApp(currentFg);

    if(currentFg!=null && currentFg.processName.equals(process.processName) &&
            (activity==null || currentActivity.compareTo(activity)==0))
        return true;

    Slog.i(TAG, "isStillActive returns false - CallerProcess: " + process.processName + " CurrentProcess: "
            + (currentFg==null ? "null" : currentFg.processName) + " CallerActivity:" + (activity==null ? "null" : activity.toString())
            + " CurrentActivity: " + (currentActivity==null ? "null" : currentActivity.toString()));
    return false;
}

private boolean isRunningService(String processname){
    if(processname==null || processname.isEmpty())
        return false;

    RunningServiceInfo service;

    if(mActivityManager==null)
        mActivityManager = (ActivityManager)mContext.getSystemService(Context.ACTIVITY_SERVICE);
    List <RunningServiceInfo> l = mActivityManager.getRunningServices(9999);
    Iterator <RunningServiceInfo> i = l.iterator();
    while(i.hasNext()){
        service = i.next();
        if(service.process.equals(processname))
            return true;
    }

    return false;
}

HTML - Arabic Support

i edit the html page with notepad ++ ,set encoding to utf-8 and its work

PPT to PNG with transparent background

I found a workaround.

  1. Export with a white background (or other color that will work with transparent graphics). This will be out "whitescreen" layer.
  2. Export with "bluescreen" background, or some terrible other color that will make it easy to select out the background from foreground.
  3. Open the bluescreen version as a layer on top of the white screen.
  4. Use the bluescreen layer to select out only the parts you want to use.
  5. Create a mask for the whitescreen layer with the selection made from the bluescreen layer.

This will get good results for edges and aliasing, whilst retaining a good color for the see-

Multiple separate IF conditions in SQL Server

Maybe this is a bit redundant, but no one appeared to have mentioned this as a solution.

As a beginner in SQL I find that when using a BEGIN and END SSMS usually adds a squiggly line with incorrect syntax near 'END' to END, simply because there's no content in between yet. If you're just setting up BEGIN and END to get started and add the actual query later, then simply add a bogus PRINT statement so SSMS stops bothering you.

For example:

IF (1=1)
BEGIN
  PRINT 'BOGUS'
END

The following will indeed set you on the wrong track, thinking you made a syntax error which in this case just means you still need to add content in between BEGIN and END:

IF (1=1)
BEGIN
END

How to check whether particular port is open or closed on UNIX?

netstat -ano|grep 443|grep LISTEN

will tell you whether a process is listening on port 443 (you might have to replace LISTEN with a string in your language, though, depending on your system settings).

Python: CSV write by column rather than row

Updating lines in place in a file is not supported on most file system (a line in a file is just some data that ends with newline, the next line start just after that).

As I see it you have two options:

  1. Have your data generating loops be generators, this way they won't consume a lot of memory - you'll get data for each row "just in time"
  2. Use a database (sqlite?) and update the rows there. When you're done - export to CSV

Small example for the first method:

from itertools import islice, izip, count
print list(islice(izip(count(1), count(2), count(3)), 10))

This will print

[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6), (5, 6, 7), (6, 7, 8), (7, 8, 9), (8, 9, 10), (9, 10, 11), (10, 11, 12)]

even though count generate an infinite sequence of numbers

WPF button click in C# code

The following should do the trick:

btn.Click += btn1_Click;

size of uint8, uint16 and uint32?

It's quite unclear how you are computing the size ("the size in debug mode"?").

Use printf():

printf("the size of c is %u\n", (unsigned int) sizeof c);

Normally you'd print a size_t value (which is the type sizeof returns) with %zu, but if you're using a pre-C99 compiler like Visual Studio that won't work.

You need to find the typedef statements in your code that define the custom names like uint8 and so on; those are not standard so nobody here can know how they're defined in your code.

New C code should use <stdint.h> which gives you uint8_t and so on.

reading external sql script in python

Your code already contains a beautiful way to execute all statements from a specified sql file

# Open and read the file as a single buffer
fd = open('ZooDatabase.sql', 'r')
sqlFile = fd.read()
fd.close()

# all SQL commands (split on ';')
sqlCommands = sqlFile.split(';')

# Execute every command from the input file
for command in sqlCommands:
    # This will skip and report errors
    # For example, if the tables do not yet exist, this will skip over
    # the DROP TABLE commands
    try:
        c.execute(command)
    except OperationalError, msg:
        print "Command skipped: ", msg

Wrap this in a function and you can reuse it.

def executeScriptsFromFile(filename):
    # Open and read the file as a single buffer
    fd = open(filename, 'r')
    sqlFile = fd.read()
    fd.close()

    # all SQL commands (split on ';')
    sqlCommands = sqlFile.split(';')

    # Execute every command from the input file
    for command in sqlCommands:
        # This will skip and report errors
        # For example, if the tables do not yet exist, this will skip over
        # the DROP TABLE commands
        try:
            c.execute(command)
        except OperationalError, msg:
            print "Command skipped: ", msg

To use it

executeScriptsFromFile('zookeeper.sql')

You said you were confused by

result = c.execute("SELECT * FROM %s;" % table);

In Python, you can add stuff to a string by using something called string formatting.

You have a string "Some string with %s" with %s, that's a placeholder for something else. To replace the placeholder, you add % ("what you want to replace it with") after your string

ex:

a = "Hi, my name is %s and I have a %s hat" % ("Azeirah", "cool")
print(a)
>>> Hi, my name is Azeirah and I have a Cool hat

Bit of a childish example, but it should be clear.

Now, what

result = c.execute("SELECT * FROM %s;" % table);

means, is it replaces %s with the value of the table variable.

(created in)

for table in ['ZooKeeper', 'Animal', 'Handles']:


# for loop example

for fruit in ["apple", "pear", "orange"]:
    print fruit
>>> apple
>>> pear
>>> orange

If you have any additional questions, poke me.

"Parse Error : There is a problem parsing the package" while installing Android application

In my case build 1 was installed correctly in my mobile using the signed APK (also from Google Play Store). But when I update the application with build 2 for first time, I had an issue installing it with the signed APK as I got "There was a problem parsing the package".

I tried several methods as specified above. But did not work.

After some time, I rerun the commands

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-key.keystore app-release-unsigned.apk myappkeyalias
zipalign -v 4 app-release-unsigned.apk MyApp.apk

and surprisingly, it worked.

It seems sometimes the APK built might be corrupt. So, Re-running jarsigner and zipalign commands resolved my issue.

How to bind Events on Ajax loaded Content?

For ASP.NET try this:

<script type="text/javascript">
    Sys.Application.add_load(function() { ... });
</script>

This appears to work on page load and on update panel load

Please find the full discussion here.

Javadoc link to method in other class

For the Javadoc tag @see, you don't need to use @link; Javadoc will create a link for you. Try

@see com.my.package.Class#method()

Here's more info about @see.

how to append a css class to an element by javascript?

addClass=(selector,classes)=>document.querySelector(selector).classList(...classes.split(' '));

This will add ONE class or MULTIPLE classes :

addClass('#myDiv','back-red'); // => Add "back-red" class to <div id="myDiv"/>
addClass('#myDiv','fa fa-car') //=>Add two classes to "div"

How do I pull files from remote without overwriting local files?

Well, yes, and no...

I understand that you want your local copies to "override" what's in the remote, but, oh, man, if someone has modified the files in the remote repo in some different way, and you just ignore their changes and try to "force" your own changes without even looking at possible conflicts, well, I weep for you (and your coworkers) ;-)

That said, though, it's really easy to do the "right thing..."

Step 1:

git stash

in your local repo. That will save away your local updates into the stash, then revert your modified files back to their pre-edit state.

Step 2:

git pull

to get any modified versions. Now, hopefully, that won't get any new versions of the files you're worried about. If it doesn't, then the next step will work smoothly. If it does, then you've got some work to do, and you'll be glad you did.

Step 3:

git stash pop

That will merge your modified versions that you stashed away in Step 1 with the versions you just pulled in Step 2. If everything goes smoothly, then you'll be all set!

If, on the other hand, there were real conflicts between what you pulled in Step 2 and your modifications (due to someone else editing in the interim), you'll find out and be told to resolve them. Do it.

Things will work out much better this way - it will probably keep your changes without any real work on your part, while alerting you to serious, serious issues.

how to pass parameters to query in SQL (Excel)

This post is old enough that this answer will probably be little use to the OP, but I spent forever trying to answer this same question, so I thought I would update it with my findings.

This answer assumes that you already have a working SQL query in place in your Excel document. There are plenty of tutorials to show you how to accomplish this on the web, and plenty that explain how to add a parameterized query to one, except that none seem to work for an existing, OLE DB query.

So, if you, like me, got handed a legacy Excel document with a working query, but the user wants to be able to filter the results based on one of the database fields, and if you, like me, are neither an Excel nor a SQL guru, this might be able to help you out.

Most web responses to this question seem to say that you should add a “?” in your query to get Excel to prompt you for a custom parameter, or place the prompt or the cell reference in [brackets] where the parameter should be. This may work for an ODBC query, but it does not seem to work for an OLE DB, returning “No value given for one or more required parameters” in the former instance, and “Invalid column name ‘xxxx’” or “Unknown object ‘xxxx’” in the latter two. Similarly, using the mythical “Parameters…” or “Edit Query…” buttons is also not an option as they seem to be permanently greyed out in this instance. (For reference, I am using Excel 2010, but with an Excel 97-2003 Workbook (*.xls))

What we can do, however, is add a parameter cell and a button with a simple routine to programmatically update our query text.

First, add a row above your external data table (or wherever) where you can put a parameter prompt next to an empty cell and a button (Developer->Insert->Button (Form Control) – You may need to enable the Developer tab, but you can find out how to do that elsewhere), like so:

[Picture of a cell of prompt (label) text, an empty cell, then a button.]

Next, select a cell in the External Data (blue) area, then open Data->Refresh All (dropdown)->Connection Properties… to look at your query. The code in the next section assumes that you already have a parameter in your query (Connection Properties->Definition->Command Text) in the form “WHERE (DB_TABLE_NAME.Field_Name = ‘Default Query Parameter')” (including the parentheses). Clearly “DB_TABLE_NAME.Field_Name” and “Default Query Parameter” will need to be different in your code, based on the database table name, database value field (column) name, and some default value to search for when the document is opened (if you have auto-refresh set). Make note of the “DB_TABLE_NAME.Field_Name” value as you will need it in the next section, along with the “Connection name” of your query, which can be found at the top of the dialog.

Close the Connection Properties, and hit Alt+F11 to open the VBA editor. If you are not on it already, right click on the name of the sheet containing your button in the “Project” window, and select “View Code”. Paste the following code into the code window (copying is recommended, as the single/double quotes are dicey and necessary).

Sub RefreshQuery()
 Dim queryPreText As String
 Dim queryPostText As String
 Dim valueToFilter As String
 Dim paramPosition As Integer
 valueToFilter = "DB_TABLE_NAME.Field_Name ="

 With ActiveWorkbook.Connections("Connection name").OLEDBConnection
     queryPreText = .CommandText
     paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1
     queryPreText = Left(queryPreText, paramPosition)
     queryPostText = .CommandText
     queryPostText = Right(queryPostText, Len(queryPostText) - paramPosition)
     queryPostText = Right(queryPostText, Len(queryPostText) - InStr(queryPostText, ")") + 1)
     .CommandText = queryPreText & " '" & Range("Cell reference").Value & "'" & queryPostText
 End With
 ActiveWorkbook.Connections("Connection name").Refresh
End Sub

Replace “DB_TABLE_NAME.Field_Name” and "Connection name" (in two locations) with your values (the double quotes and the space and equals sign need to be included).

Replace "Cell reference" with the cell where your parameter will go (the empty cell from the beginning) - mine was the second cell in the first row, so I put “B1” (again, the double quotes are necessary).

Save and close the VBA editor.

Enter your parameter in the appropriate cell.

Right click your button to assign the RefreshQuery sub as the macro, then click your button. The query should update and display the right data!

Notes: Using the entire filter parameter name ("DB_TABLE_NAME.Field_Name =") is only necessary if you have joins or other occurrences of equals signs in your query, otherwise just an equals sign would be sufficient, and the Len() calculation would be superfluous. If your parameter is contained in a field that is also being used to join tables, you will need to change the "paramPosition = InStr(queryPreText, valueToFilter) + Len(valueToFilter) - 1" line in the code to "paramPosition = InStr(Right(.CommandText, Len(.CommandText) - InStrRev(.CommandText, "WHERE")), valueToFilter) + Len(valueToFilter) - 1 + InStr(.CommandText, "WHERE")" so that it only looks for the valueToFilter after the "WHERE".

This answer was created with the aid of datapig’s “BaconBits” where I found the base code for the query update.

Getting pids from ps -ef |grep keyword

I use

ps -C "keyword" -o pid=

This command should give you a PID number.

How to change the timeout on a .NET WebClient object

In some cases it is necessary to add user agent to headers:

WebClient myWebClient = new WebClient();
myWebClient.DownloadFile(myStringWebResource, fileName);
myWebClient.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) (compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";

This was the solution to my case.

Credit:

http://genjurosdojo.blogspot.com/2012/10/the-remote-server-returned-error-504.html

How can I get a resource content from a static context?

In your class, where you implement the static function, you can call a private\public method from this class. The private\public method can access the getResources.

for example:

public class Text {

   public static void setColor(EditText et) {
      et.resetColor(); // it works

      // ERROR
      et.setTextColor(getResources().getColor(R.color.Black)); // ERROR
   }

   // set the color to be black when reset
   private void resetColor() {
       setTextColor(getResources().getColor(R.color.Black));
   }
}

and from other class\activity, you can call:

Text.setColor('some EditText you initialized');

ruby LoadError: cannot load such file

I created my own Gem, but I did it in a directory that is not in my load path:

$ pwd
/Users/myuser/projects
$ gem build my_gem/my_gem.gemspec

Then I ran irb and tried to load the Gem:

> require 'my_gem'
LoadError: cannot load such file -- my_gem

I used the global variable $: to inspect my load path and I realized I am using RVM. And rvm has specific directories in my load path $:. None of those directories included my ~/projects directory where I created the custom gem.

So one solution is to modify the load path itself:

$: << "/Users/myuser/projects/my_gem/lib"

Note that the lib directory is in the path, which holds the my_gem.rb file which will be required in irb:

> require 'my_gem'
 => true 

Now if you want to install the gem in RVM path, then you would need to run:

$ gem install my_gem

But it will need to be in a repository like rubygems.org.

$ gem push my_gem-0.0.0.gem
Pushing gem to RubyGems.org...
Successfully registered gem my_gem

Difference between "and" and && in Ruby?

I don't know if this is Ruby intention or if this is a bug but try this code below. This code was run on Ruby version 2.5.1 and was on a Linux system.

puts 1 > -1 and 257 < 256
# => false

puts 1 > -1 && 257 < 256
# => true

Convert date to YYYYMM format

A more efficient method, that uses integer math rather than strings/varchars, that will result in an int type rather than a string type is:

SELECT YYYYMM = (YEAR(GETDATE()) * 100) + MONTH(GETDATE())

Adds two zeros to the right side of the year and then adds the month to the added two zeros.

What is /var/www/html?

In the most shared hosts you can't set it.

On a VPS or dedicated server, you can set it, but everything has its price.

On shared hosts, in general you receive a Linux account, something such as /home/(your username)/, and the equivalent of /var/www/html turns to /home/(your username)/public_html/ (or something similar, such as /home/(your username)/www)

If you're accessing your account via FTP, you automatically has accessing the your */home/(your username)/ folder, just find the www or public_html and put your site in it.

If you're using absolute path in the code, bad news, you need to refactor it to use relative paths in the code, at least in a shared host.

How to know which version of Symfony I have?

we can find the symfony version using Kernel.php file but problem is the Location of Kernal Will changes from version to version (Better Do File Search in you Project Directory)

in symfony 3.0 : my_project\vendor\symfony\symfony\src\Symfony\Component\HttpKernel\Kernel.php

Check from Controller/ PHP File

$symfony_version = \Symfony\Component\HttpKernel\Kernel::VERSION;
echo $symfony_version; // this will return version; **o/p:3.0.4-DEV**

Reading file line by line (with space) in Unix Shell scripting - Issue

You want to read raw lines to avoid problems with backslashes in the input (use -r):

while read -r line; do
   printf "<%s>\n" "$line"
done < file.txt

This will keep whitespace within the line, but removes leading and trailing whitespace. To keep those as well, set the IFS empty, as in

while IFS= read -r line; do
   printf "%s\n" "$line"
done < file.txt

This now is an equivalent of cat < file.txt as long as file.txt ends with a newline.

Note that you must double quote "$line" in order to keep word splitting from splitting the line into separate words--thus losing multiple whitespace sequences.

Multiple github accounts on the same computer?

Simpler and Easy fix to avoid confusions..

For Windows users to use multiple or different git accounts for different projects.

Following steps: Go Control Panel and Search for Credential Manager. Then Go to Credential Manager -> Windows Credentials

Now remove the git:https//github.com node under Generic Credentials Heading

This will remove the current credentials. Now you can add any project through git pull it will ask for username and password.

When you face any issue with other account do the same process.

Thanks

refer to image

How to extract code of .apk file which is not working?

Any .apk file from market or unsigned

  1. If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.

  2. Download Dex2Jar zip from this link: SourceForge

  3. Unzip the downloaded zip file.

  4. Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.

    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)

  5. http://jd.benow.ca/ download decompiler from this link.

  6. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

Quick Sort Vs Merge Sort

Quicksort is in place. You just need to swap positions of data during the Partitioning function. Mergesort requires a lot more data copying. You need another temporary storage (typically the same size as your original data array) for the Merge function.

Google Drive as FTP Server

With google-drive-ftp-adapter I have been able to access the My Drive area of Google Drive with the FileZilla FTP client. However, I have not been able to access the Shared with me area.

You can configure which Google account credentials it uses by changing the account property in the configuration.properties file from default to the desired Google account name. See the instructions at http://www.andresoviedo.org/google-drive-ftp-adapter/

How to clear Tkinter Canvas?

Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.

How to overload __init__ method based on argument type?

You should use isinstance

isinstance(...)
    isinstance(object, class-or-type-or-tuple) -> bool

    Return whether an object is an instance of a class or of a subclass thereof.
    With a type as second argument, return whether that is the object's type.
    The form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for
    isinstance(x, A) or isinstance(x, B) or ... (etc.).

URL Encoding using C#

I have written a C# method that url-encodes ALL symbols:

    /// <summary>
    /// !#$345Hf} ? %21%23%24%33%34%35%48%66%7D
    /// </summary>
    public static string UrlEncodeExtended( string value )
    {
        char[] chars = value.ToCharArray();
        StringBuilder encodedValue = new StringBuilder();
        foreach (char c in chars)
        {
            encodedValue.Append( "%" + ( (int)c ).ToString( "X2" ) );
        }
        return encodedValue.ToString();
    }

How do I access store state in React Redux?

Import connect from react-redux and use it to connect the component with the state connect(mapStates,mapDispatch)(component)

import React from "react";
import { connect } from "react-redux";


const MyComponent = (props) => {
    return (
      <div>
        <h1>{props.title}</h1>
      </div>
    );
  }
}

Finally you need to map the states to the props to access them with this.props

const mapStateToProps = state => {
  return {
    title: state.title
  };
};
export default connect(mapStateToProps)(MyComponent);

Only the states that you map will be accessible via props

Check out this answer: https://stackoverflow.com/a/36214059/4040563

For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132

Make footer stick to bottom of page correctly

Why not using: { position: fixed; bottom: 0 } ?

jQuery Ajax POST example with PHP

Basic usage of .ajax would look something like this:

HTML:

<form id="foo">
    <label for="bar">A bar</label>
    <input id="bar" name="bar" type="text" value="" />

    <input type="submit" value="Send" />
</form>

jQuery:

// Variable to hold request
var request;

// Bind to the submit event of our form
$("#foo").submit(function(event){

    // Prevent default posting of form - put here to work in case of errors
    event.preventDefault();

    // Abort any pending request
    if (request) {
        request.abort();
    }
    // setup some local variables
    var $form = $(this);

    // Let's select and cache all the fields
    var $inputs = $form.find("input, select, button, textarea");

    // Serialize the data in the form
    var serializedData = $form.serialize();

    // Let's disable the inputs for the duration of the Ajax request.
    // Note: we disable elements AFTER the form data has been serialized.
    // Disabled form elements will not be serialized.
    $inputs.prop("disabled", true);

    // Fire off the request to /form.php
    request = $.ajax({
        url: "/form.php",
        type: "post",
        data: serializedData
    });

    // Callback handler that will be called on success
    request.done(function (response, textStatus, jqXHR){
        // Log a message to the console
        console.log("Hooray, it worked!");
    });

    // Callback handler that will be called on failure
    request.fail(function (jqXHR, textStatus, errorThrown){
        // Log the error to the console
        console.error(
            "The following error occurred: "+
            textStatus, errorThrown
        );
    });

    // Callback handler that will be called regardless
    // if the request failed or succeeded
    request.always(function () {
        // Reenable the inputs
        $inputs.prop("disabled", false);
    });

});

Note: Since jQuery 1.8, .success(), .error() and .complete() are deprecated in favor of .done(), .fail() and .always().

Note: Remember that the above snippet has to be done after DOM ready, so you should put it inside a $(document).ready() handler (or use the $() shorthand).

Tip: You can chain the callback handlers like this: $.ajax().done().fail().always();

PHP (that is, form.php):

// You can access the values posted by jQuery.ajax
// through the global variable $_POST, like this:
$bar = isset($_POST['bar']) ? $_POST['bar'] : null;

Note: Always sanitize posted data, to prevent injections and other malicious code.

You could also use the shorthand .post in place of .ajax in the above JavaScript code:

$.post('/form.php', serializedData, function(response) {
    // Log the response to the console
    console.log("Response: "+response);
});

Note: The above JavaScript code is made to work with jQuery 1.8 and later, but it should work with previous versions down to jQuery 1.5.

How can I clear event subscriptions in C#?

Conceptual extended boring comment.

I rather use the word "event handler" instead of "event" or "delegate". And used the word "event" for other stuff. In some programming languages (VB.NET, Object Pascal, Objective-C), "event" is called a "message" or "signal", and even have a "message" keyword, and specific sugar syntax.

const
  WM_Paint = 998;  // <-- "question" can be done by several talkers
  WM_Clear = 546;

type
  MyWindowClass = class(Window)
    procedure NotEventHandlerMethod_1;
    procedure NotEventHandlerMethod_17;

    procedure DoPaintEventHandler; message WM_Paint; // <-- "answer" by this listener
    procedure DoClearEventHandler; message WM_Clear;
  end;

And, in order to respond to that "message", a "event handler" respond, whether is a single delegate or multiple delegates.

Summary: "Event" is the "question", "event handler (s)" are the answer (s).

How do I get the path of the assembly the code is in?

I believe this would work for any kind of application:

AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory

CodeIgniter 404 Page Not Found, but why?

The cause of the problem was that the server was running PHP using FastCGI.

After changing the config.php to

$config['uri_protocol'] = "REQUEST_URI";

everything worked.

Spring Data JPA - "No Property Found for Type" Exception

it looks like your custom JpaRepository method name does not match any Variable in your entity classs. Make sure your method name matches a variable in your entity class

for example: you got a variable name called "active" and your custom JpaRepository method says "findByActiveStatus" and since there is no variable called "activeStatus" it will throw"PropertyReferenceException"

Create auto-numbering on images/figures in MS Word

Office 2007

Right click the figure, select Insert Caption, Select Numbering, check box next to 'Include chapter number', select OK, Select OK again, then you figure identifier should be updated.

How do I find out which DOM element has the focus?

With dojo, you can use dijit.getFocus()

How to use a dot "." to access members of dictionary?

Use SimpleNamespace:

>>> from types import SimpleNamespace   
>>> d = dict(x=[1, 2], y=['a', 'b'])
>>> ns = SimpleNamespace(**d)
>>> ns.x
[1, 2]
>>> ns
namespace(x=[1, 2], y=['a', 'b'])

Error retrieving parent for item: No resource found that matches the given name after upgrading to AppCompat v23

You need to set compileSdkVersion to 23.

Since API 23 Android removed the deprecated Apache Http packages, so if you use them for server requests, you'll need to add useLibrary 'org.apache.http.legacy' to build.gradle as stated in this link:

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"
    ...

    //only if you use Apache packages
    useLibrary 'org.apache.http.legacy'
}

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>

How to escape indicator characters (i.e. : or - ) in YAML

According to the YAML spec, neither the : nor the - should be a problem. : is only a key separator with a space after it, and - is only an array indicator at the start of a line with a space after it.

But if your YAML implementation has a problem with it, you potentially have lots of options:

- url: 'http://www.example-site.com/'
- url: "http://www.example-site.com/"
- url:
    http://www.example-site.com/
- url: >-
    http://www.example-site.com/
- url: |-
    http://www.example-site.com/

There is explicitly no form of escaping possible in "plain style", however.

What is Linux’s native GUI API?

To aid in what has already been mentioned there is a very good overview of the Linux graphics stack at this blog: http://blog.mecheye.net/2012/06/the-linux-graphics-stack/

This explains X11/Wayland etc and how it all fits together. In addition to what has already been mentioned I think it's worth adding a bit about the following API's you can use for graphics in Linux:

Mesa - "Mesa is many things, but one of the major things it provides that it is most famous for is its OpenGL implementation. It is an open-source implementation of the OpenGL API."

Cairo - "cairo is a drawing library used either by applications like Firefox directly, or through libraries like GTK+, to draw vector shapes."

DRM (Direct Rendering Manager) - I understand this the least but its basically the kernel drivers that let you write graphics directly to framebuffer without going through X

Python Dictionary Comprehension

Consider this example of counting the occurrence of words in a list using dictionary comprehension

my_list = ['hello', 'hi', 'hello', 'today', 'morning', 'again', 'hello']
my_dict = {k:my_list.count(k) for k in my_list}
print(my_dict)

And the result is

{'again': 1, 'hi': 1, 'hello': 3, 'today': 1, 'morning': 1}

Convert String into a Class Object

You might want to do it with json.
Convert your bean(*) to json an then back.
this proccess is known as serialisation and deserialisation
read about it here

(*) Dont use just members as the data source, build getters and setters for each member in your object.

Pass correct "this" context to setTimeout callback?

NOTE: This won't work in IE

var ob = {
    p: "ob.p"
}

var p = "window.p";

setTimeout(function(){
    console.log(this.p); // will print "window.p"
},1000); 

setTimeout(function(){
    console.log(this.p); // will print "ob.p"
}.bind(ob),1000);

How to detect a remote side socket close?

Since the answers deviate I decided to test this and post the result - including the test example.

The server here just writes data to a client and does not expect any input.

The server:

ServerSocket serverSocket = new ServerSocket(4444);
Socket clientSocket = serverSocket.accept();
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
while (true) {
  out.println("output");
  if (out.checkError()) System.out.println("ERROR writing data to socket !!!");
  System.out.println(clientSocket.isConnected());
  System.out.println(clientSocket.getInputStream().read());
        // thread sleep ...
  // break condition , close sockets and the like ...
}
  • clientSocket.isConnected() returns always true once the client connects (and even after the disconnect) weird !!
  • getInputStream().read()
    • makes the thread wait for input as long as the client is connected and therefore makes your program not do anything - except if you get some input
    • returns -1 if the client disconnected
  • out.checkError() is true as soon as the client is disconnected so I recommend this

How to find Oracle Service Name

Found here, no DBA : Checking oracle sid and database name

select * from global_name;

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

MySQL (and subsequently SQLite) also support the REPLACE INTO syntax:

REPLACE INTO my_table (pk_id, col1) VALUES (5, '123');

This automatically identifies the primary key and finds a matching row to update, inserting a new one if none is found.

Getting Data from Android Play Store

Disclaimer: I am from 42matters, who provides this data already on https://42matters.com/api , feel free to check it out or drop us a line.

As lenik mentioned there are open-source libraries that already help with obtaining some data from GPlay. If you want to build one yourself you can try to parse the Google Play App page, but you should pay attention to the following:

  • Make sure the URL you are trying to parse is not blocked in robots.txt - e.g. https://play.google.com/robots.txt
  • Make sure that you are not doing it too often, Google will throttle and potentially blacklist you if you are doing it too much.
  • Send a correct User-Agent header to actually show you are a bot
  • The page of an app is big - make sure you accept gzip and request the mobile version
  • GPlay website is not an API, it doesn't care that you parse it so it will change over time. Make sure you handle changes - e.g. by having test to make sure you get what you expected.

So that in mind getting one page metadata is a matter of fetching the page html and parsing it properly. With JSoup you can try:

      HttpClient httpClient = HttpClientBuilder.create().build();
      HttpGet request = new HttpGet(crawlUrl);
      HttpResponse rsp = httpClient.execute(request);

      int statusCode = rsp.getStatusLine().getStatusCode();

      if (statusCode == 200) {
           String content = EntityUtils.toString(rsp.getEntity());    
           Document doc = Jsoup.parse(content);
           //parse content, whatever you need
           Element price = doc.select("[itemprop=price]").first();
      }      

For that very simple use case that should get you started. However, the moment you want to do more interesting stuff, things get complicated:

  • Search is forbidden in robots.
  • Keeping app metadata up-to-date is hard to do. There are more than 2.2m apps, if you want to refresh their metadata daily there are 2.2 requests/day, which will 1) get blocked immediately, 2) costs a lot of money - pessimistic 220gb data transfer per day if one app is 100k
  • How do you discover new apps
  • How do you get pricing in each country, translations of each language

The list goes on. If you don't want to do all this by yourself, you can consider 42matters API, which supports lookup and search, top google charts, advanced queries and filters. And this for 35 languages and more than 50 countries.

[2]:

How to draw text using only OpenGL methods?

This article describes how to render text in OpenGL using various techniques.

With only using opengl, there are several ways:

  • using glBitmap
  • using textures
  • using display lists

starting file download with JavaScript

A agree with the methods mentioned by maxnk, however you may want to reconsider trying to automatically force the browser to download the URL. It may work fine for binary files but for other types of files (text, PDF, images, video), the browser may want to render it in the window (or IFRAME) rather than saving to disk.

If you really do need to make an Ajax call to get the final download links, what about using DHTML to dynamically write out the download link (from the ajax response) into the page? That way the user could either click on it to download (if binary) or view in their browser - or select "Save As" on the link to save to disk. It's an extra click, but the user has more control.

How to correctly write async method?

To get the behavior you want you need to wait for the process to finish before you exit Main(). To be able to tell when your process is done you need to return a Task instead of a void from your function, you should never return void from a async function unless you are working with events.

A re-written version of your program that works correctly would be

class Program {     static void Main(string[] args)     {         Debug.WriteLine("Calling DoDownload");         var downloadTask = DoDownloadAsync();         Debug.WriteLine("DoDownload done");         downloadTask.Wait(); //Waits for the background task to complete before finishing.      }      private static async Task DoDownloadAsync()     {         WebClient w = new WebClient();          string txt = await w.DownloadStringTaskAsync("http://www.google.com/");         Debug.WriteLine(txt);     } } 

Because you can not await in Main() I had to do the Wait() function instead. If this was a application that had a SynchronizationContext I would do await downloadTask; instead and make the function this was being called from async.

CertificateException: No name matching ssl.someUrl.de found

The server name should be same as the first/last name which you give while create a certificate

need to test if sql query was successful

This is the simplest way you could test

$query = $DB->query("UPDATE exp_members SET group_id = '$group_id' WHERE member_id = '$member_id'");

if($query) // will return true if succefull else it will return false
{
// code here
}

When does Git refresh the list of remote branches?

Use git fetch to fetch all latest created branches.

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

Well I don't even understand the culprit of this problem. But in my case the problem is totally different. I've tried running netstat -o or netstat -ab, both show that there is not any app currently listening on port 62434 which is the one my app tries to listen on. So it's really confusing to me.

I just tried thinking of what I had made so that it stopped working (it did work before). Well then I thought of the Internet sharing I made on my Ethernet adapter with a private virtual LAN (using Hyper-v in Windows 10). I just needed to turn off the sharing and it worked just fine again.

Hope this helps someone else having the same issue. And of course if someone could explain this, please add more detail in your own answer or maybe as some comment to my answer.

MySQL: How to allow remote connection to mysql

All process for remote login. Remote login is off by default.You need to open it manually for all ip..to give access all ip

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password';

Specific Ip

GRANT ALL PRIVILEGES ON *.* TO 'root'@'your_desire_ip' IDENTIFIED BY 'password';

then

flush privileges;

You can check your User Host & Password

SELECT host,user,authentication_string FROM mysql.user;

Now your duty is to change this

bind-address = 127.0.0.1

You can find this on

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

if you not find this on there then try this

sudo nano /etc/mysql/my.cnf

comment in this

#bind-address = 127.0.0.1

Then restart Mysql

sudo service mysql restart

Now enjoy remote login

What's an easy way to read random line from a file in Unix command line?

sort --random-sort $FILE | head -n 1

(I like the shuf approach above even better though - I didn't even know that existed and I would have never found that tool on my own)

Javascript Uncaught TypeError: Cannot read property '0' of undefined

The error is here:

hasLetter("a",words[]);

You are passing the first item of words, instead of the array.

Instead, pass the array to the function:

hasLetter("a",words);

Problem solved!


Here's a breakdown of what the problem was:

I'm guessing in your browser (chrome throws a different error), words[] == words[0], so when you call hasLetter("a",words[]);, you are actually calling hasLetter("a",words[0]);. So, in essence, you are passing the first item of words to your function, not the array as a whole.

Of course, because words is just an empty array, words[0] is undefined. Therefore, your function call is actually:

hasLetter("a", undefined);

which means that, when you try to access d[ascii], you are actually trying to access undefined[0], hence the error.

How to grant permission to users for a directory using command line in Windows?

in windows 10 working without "c:>" and ">"

For example:

F = Full Control
/e : Edit permission and kept old permission
/p : Set new permission

cacls "file or folder path" /e /p UserName:F

(also this fixes error 2502 and 2503)

cacls "C:\Windows\Temp" /e /p UserName:F

Send HTML in email via PHP

Simplest way is probably to just use Zend Framework or any of the other frameworks like CakePHP or Symphony.

You can do it with the standard mail function too, but you'll need a bit more knowledge on how to attach pictures.

Alternatively, just host the images on a server instead of attaching them. Sending HTML mail is documented in the mail function documentation.

How to convert a string to utf-8 in Python

  • First, str in Python is represented in Unicode.
  • Second, UTF-8 is an encoding standard to encode Unicode string to bytes. There are many encoding standards out there (e.g. UTF-16, ASCII, SHIFT-JIS, etc.).

When the client sends data to your server and they are using UTF-8, they are sending a bunch of bytes not str.

You received a str because the "library" or "framework" that you are using, has implicitly converted some random bytes to str.

Under the hood, there is just a bunch of bytes. You just need ask the "library" to give you the request content in bytes and you will handle the decoding yourself (if library can't give you then it is trying to do black magic then you shouldn't use it).

  • Decode UTF-8 encoded bytes to str: bs.decode('utf-8')
  • Encode str to UTF-8 bytes: s.encode('utf-8')

CSS Printing: Avoiding cut-in-half DIVs between pages?

Using break-inside should work:

@media print {
  div {
    break-inside: avoid;
  }
}

It works on all major browsers:

  • Chrome 50+
  • Edge 12+
  • Firefox 65+
  • Opera 37+
  • Safari 10+

Using page-break-inside: avoid; instead should work too, but has been exactly deprecated by break-inside: avoid.

Changing the selected option of an HTML Select element

After a lot of searching I tried @kzh on select list where I only know option inner text not value attribute, this code based on select answer I used it to change select option according to current page urlon this format http://www.example.com/index.php?u=Steve

<select id="sel">
    <option>Joe</option>
    <option>Steve</option>
    <option>Jack</option>
</select>
<script>
    var val = window.location.href.split('u=')[1]; // to filter ?u= query 
    var sel = document.getElementById('sel');
    var opts = sel.options;
    for(var opt, j = 0; opt = opts[j]; j++) {
        // search are based on text inside option Attr
        if(opt.text == val) {
            sel.selectedIndex = j;
            break;
        }
    }
</script>

This will keeps url parameters shown as selected to make it more user friendly and the visitor knows what page or profile he is currently viewing .

How to stick table header(thead) on top while scrolling down the table rows with fixed header(navbar) in bootstrap 3?

If you want to have an affix on your header you can use this tricks, add position: relative on your th and change the position in eventListener('scroll')

I have created an example: https://codesandbox.io/s/rl1jjx0o

I use vue.js but you can use this, without vue.js

Checking if an object is a number in C#

Take advantage of the IsPrimitive property to make a handy extension method:

public static bool IsNumber(this object obj)
{
    if (Equals(obj, null))
    {
        return false;
    }

    Type objType = obj.GetType();
    objType = Nullable.GetUnderlyingType(objType) ?? objType;

    if (objType.IsPrimitive)
    {
        return objType != typeof(bool) && 
            objType != typeof(char) && 
            objType != typeof(IntPtr) && 
            objType != typeof(UIntPtr);
    }

    return objType == typeof(decimal);
}

EDIT: Fixed as per comments. The generics were removed since .GetType() boxes value types. Also included fix for nullable values.

How do I implement __getattribute__ without an infinite recursion error?

Actually, I believe you want to use the __getattr__ special method instead.

Quote from the Python docs:

__getattr__( self, name)

Called when an attribute lookup has not found the attribute in the usual places (i.e. it is not an instance attribute nor is it found in the class tree for self). name is the attribute name. This method should return the (computed) attribute value or raise an AttributeError exception.
Note that if the attribute is found through the normal mechanism, __getattr__() is not called. (This is an intentional asymmetry between __getattr__() and __setattr__().) This is done both for efficiency reasons and because otherwise __setattr__() would have no way to access other attributes of the instance. Note that at least for instance variables, you can fake total control by not inserting any values in the instance attribute dictionary (but instead inserting them in another object). See the __getattribute__() method below for a way to actually get total control in new-style classes.

Note: for this to work, the instance should not have a test attribute, so the line self.test=20 should be removed.

How do I reference a cell range from one worksheet to another using excel formulas?

I rewrote the code provided by Ninja2k because I didn't like that it looped through cells. For future reference here's a version using arrays instead which works noticeably faster over lots of ranges but has the same result:

Function concat2(useThis As Range, Optional delim As String) As String
    Dim tempValues
    Dim tempString
    Dim numValues As Long
    Dim i As Long, j As Long
    tempValues = useThis
    numValues = UBound(tempValues) * UBound(tempValues, 2)
    ReDim values(1 To numValues)
    For i = UBound(tempValues) To LBound(tempValues) Step -1
        For j = UBound(tempValues, 2) To LBound(tempValues, 2) Step -1
            values(numValues) = tempValues(i, j)
            numValues = numValues - 1
        Next j
    Next i
    concat2 = Join(values, delim)
End Function

I can't help but think there's definitely a better way...

Here are steps to do it manually without VBA which only works with 1d arrays and makes static values instead of retaining the references:

  1. Update cell formula to something like =Sheet2!A1:A15
  2. Hit F9
  3. Remove the curly braces { and }
  4. Place CONCATENATE( at the front of the formula after the = sign and ) at the end of the formula.
  5. Hit enter.

CSS Outside Border

IsisCode gives you a good solution. Another one is to position border div inside parent div. Check this example http://jsfiddle.net/A2tu9/

UPD: You can also use pseudo element :after (:before), in this case HTML will not be polluted with extra markup:

.my-div {
    position: relative;
    padding: 4px;
    ...
}
.my-div:after {
    content: '';
    position: absolute;
    top: -3px;
    left: -3px;
    bottom: -3px;
    right: -3px;
    border: 1px #888 solid;
}

Demo: http://jsfiddle.net/A2tu9/191/

Twitter Bootstrap Multilevel Dropdown Menu

I just added class="span2" to the <li> for the dropdown items and that worked.

Nested routes with react router v4 / v5

A complete answer for React Router v6 or version 6 just in case needed.

import Dashboard from "./dashboard/Dashboard";
import DashboardDefaultContent from "./dashboard/dashboard-default-content";
import { Route, Routes } from "react-router";
import { useRoutes } from "react-router-dom";

/*Routes is used to be Switch*/
const Router = () => {

  return (
    <Routes>
      <Route path="/" element={<LandingPage />} />
      <Route path="games" element={<Games />} />
      <Route path="game-details/:id" element={<GameDetails />} />
      <Route path="dashboard" element={<Dashboard />}>
        <Route path="/" element={<DashboardDefaultContent />} />
        <Route path="inbox" element={<Inbox />} />
        <Route path="settings-and-privacy" element={<SettingsAndPrivacy />} />
        <Route path="*" element={<NotFound />} />
      </Route>
      <Route path="*" element={<NotFound />} />
    </Routes>
  );
};
export default Router;
import DashboardSidebarNavigation from "./dashboard-sidebar-navigation";
import { Grid } from "@material-ui/core";
import { Outlet } from "react-router";

const Dashboard = () => {
  return (
    <Grid
      container
      direction="row"
      justify="flex-start"
      alignItems="flex-start"
    >
      <DashboardSidebarNavigation />
      <Outlet />
    </Grid>
  );
};

export default Dashboard;

Github repo is here. https://github.com/webmasterdevlin/react-router-6-demo

How to use if-else option in JSTL

In addition with skaffman answer, simple if-else you can use ternary operator like this

<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>

Converting XDocument to XmlDocument and vice versa

There is a discussion on http://blogs.msdn.com/marcelolr/archive/2009/03/13/fast-way-to-convert-xmldocument-into-xdocument.aspx

It seems that reading an XDocument via an XmlNodeReader is the fastest method. See the blog for more details.

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Insert variable into Header Location PHP

Try using double quotes and keeping the L in location lowercase...

header("location: http://linkhere.com/HERE_I_WANT_THE_VARIABLE");

or for example

header("location: http://linkhere.com/$variable");

No need to concatenate here to insert variables.

jQuery.inArray(), how to use it right?

Just no one use $ instead of jQuery:

if ($.inArray(nearest.node.name, array)>=0){
   console.log("is in array");
}else{
   console.log("is not in array");
}

How do I run Python code from Sublime Text 2?

I had the same problem. You probably haven't saved the file yet. Make sure to save your code with .py extension and it should work.

How do I create a GUI for a windows application using C++?

A simple "window" with some text and a button is just a MessageBox. You can create them with a single function call; you don't need any library whatsoever.

Bundler: Command not found

My solution was to make sure I selected a version of Ruby for that repo.

Example: chruby 2.2.2 or rvm use 2.2.2

? bundle install
zsh: command not found: bundle

? ruby -v
ruby 1.9.3p484 (2013-11-22 revision 43786) [x86_64-linux]

### Notice the system Ruby version isn't included in chruby

? chruby
  ruby-1.9.3-p551
  ruby-2.1.2
  ruby-2.2.1

### Select a version via your version manager

? chruby 1.9.3

### Ensure your version manager properly selects a version (*)

? chruby
 * ruby-1.9.3-p551
   ruby-2.1.2
   ruby-2.2.1

? bundle install
Fetching gem metadata from https://rubygems.org/.........

How to restore/reset npm configuration to default values?

For what it's worth, you can reset to default the value of a config entry with npm config delete <key> (or npm config rm <key>, but the usage of npm config rm is not mentioned in npm help config).

Example:

# set registry value
npm config set registry "https://skimdb.npmjs.com/registry"
# revert change back to default
npm config delete registry

Spring Boot @Value Properties

Your problem is that you need a static PropertySourcesPlaceholderConfigurer Bean definition in your configuration. I say static with emphasis, because I had a non-static one and it didn't work.

@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}

AngularJS Error: Cross origin requests are only supported for protocol schemes: http, data, chrome-extension, https

The operation is not allowed in chrome. You can either use a HTTP server(Tomcat) or you use Firefox instead.

How do I set 'semi-bold' font via CSS? Font-weight of 600 doesn't make it look like the semi-bold I see in my Photoshop file

By mid-2016 the Chromium engine (v53) supports just 3 emphasis styles:

Plain text, bold, and super-bold...

 <div style="font:normal 400 14px Arial;">Testing</div>

 <div style="font:normal 700 14px Arial;">Testing</div>

 <div style="font:normal 800 14px Arial;">Testing</div>

Pandas read_csv from url

url = "https://github.com/cs109/2014_data/blob/master/countries.csv"
c = pd.read_csv(url, sep = "\t")

How To Execute SSH Commands Via PHP

For those using the Symfony framework, the phpseclib can also be used to connect via SSH. It can be installed using composer:

composer require phpseclib/phpseclib

Next, simply use it as follows:

use phpseclib\Net\SSH2;

// Within a controller for example:
$ssh = new SSH2('hostname or ip');
if (!$ssh->login('username', 'password')) {
    // Login failed, do something
}

$return_value = $ssh->exec('command');

Why doesn't java.io.File have a close method?

Say suppose, you have

File f  = new File("SomeFile");
f.length();

You need not close the Files, because its just the representation of a path.

You should always consider to close only reader/writers and in fact streams.

Hex transparency in colors

I always keep coming here to check for int/hex alpha value. So, end up creating a simple method in my java utils class. This method will convert the percentage to hex value and append to the color code string value.

 public static String setColorAlpha(int percentage, String colorCode){
    double decValue = ((double)percentage / 100) * 255;
    String rawHexColor = colorCode.replace("#","");
    StringBuilder str = new StringBuilder(rawHexColor);

    if(Integer.toHexString((int)decValue).length() == 1)
        str.insert(0, "#0" + Integer.toHexString((int)decValue));
    else
        str.insert(0, "#" + Integer.toHexString((int)decValue));
    return str.toString();
}

So, Utils.setColorAlpha(30, "#000000") will give you #4c000000

Extract substring in Bash

Given test.txt is a file containing "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

cut -b19-20 test.txt > test1.txt # This will extract chars 19 & 20 "ST" 
while read -r; do;
> x=$REPLY
> done < test1.txt
echo $x
ST

Making a PowerShell POST request if a body param starts with '@'

You should be able to do the following:

$params = @{"@type"="login";
 "username"="[email protected]";
 "password"="yyy";
}

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body $params

This will send the post as the body. However - if you want to post this as a Json you might want to be explicit. To post this as a JSON you can specify the ContentType and convert the body to Json by using

Invoke-WebRequest -Uri http://foobar.com/endpoint -Method POST -Body ($params|ConvertTo-Json) -ContentType "application/json"

Extra: You can also use the Invoke-RestMethod for dealing with JSON and REST apis (which will save you some extra lines for de-serializing)

HTML.HiddenFor value set

It is just Value, not @value.. Try it. I'm not sure about @Model.title, maybe it's just Model.title

text-align: right on <select> or <option>

You could try using the "dir" attribute, but I'm not sure that would produce the desired effect?

<select dir="rtl">
    <option>Foo</option>    
    <option>bar</option>
    <option>to the right</option>
</select>

Demo here: http://jsfiddle.net/fparent/YSJU7/

Output data from all columns in a dataframe in pandas

you can use sequence slicing syntax i.e

paramdata[:5] # first five records
paramdata[-5:] # last five records
paramdata[:] # all records

sometimes the dataframe might not fit in the screen buffer in which case you are probably better off either printing a small subset or exporting it to something else, plot or (csv again)

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

If you are looking for a way to make this work without recompiling your Any CPU application, here is another potential workaround:

  1. Locate your COM object GUID under the HKey_Classes_Root\Wow6432Node\CLSID\{GUID}
  2. Once located add a new REG_SZ (string) Value. Name should be AppID and data should be the same COM object GUID you have just searched for
  3. Add a new key under HKey_Classes_Root\Wow6432Node\AppID. The new key should be called the same as the COM object GUID.
  4. Under the new key you just added, add a new String Value, and call it DllSurrogate. Leave the value empty.
  5. Create a new Key under HKey_Local_Machine\Software\Classes\AppID\ Again the new key should be called the same as the COM object’s GUID. No values are necessary to be added under this key.

I take no credit for the solution, but it worked for us. Check the source link for more information and other comments.

Source: https://techtalk.gfi.com/32bit-object-64bit-environment/

Check for special characters in string

_x000D_
_x000D_
var specialChars = "<>@!#$%^&*()_+[]{}?:;|'\"\\,./~`-=";_x000D_
var checkForSpecialChar = function(string){_x000D_
 for(i = 0; i < specialChars.length;i++){_x000D_
   if(string.indexOf(specialChars[i]) > -1){_x000D_
       return true_x000D_
    }_x000D_
 }_x000D_
 return false;_x000D_
}_x000D_
_x000D_
var str = "YourText";_x000D_
if(checkForSpecialChar(str)){_x000D_
  alert("Not Valid");_x000D_
} else {_x000D_
    alert("Valid");_x000D_
}
_x000D_
_x000D_
_x000D_

Finding smallest value in an array most efficiently

                //smalest number in the array//
    double small = x[0];
    for(t=0;t<x[t];t++)
    {
         if(x[t]<small)
             {
                small=x[t];
            }
    }
    printf("\nThe smallest number is  %0.2lf  \n",small);

Bootstrap 3 Multi-column within a single ul not floating properly

you are thinking too much... Take a look at this [i think this is what you wanted - if not let me know]

http://www.bootply.com/118886

css

.even{background: red; color:white;}
.odd{background: darkred; color:white;}

html

<div class="container">
  <ul class="list-unstyled">
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 even">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
    <li class="col-md-6 odd">Dumby Content</li>
  </ul>
</div>

How to tackle daylight savings using TimeZone in Java

As per this answer:

TimeZone tz = TimeZone.getTimeZone("EST");
boolean inDs = tz.inDaylightTime(new Date());

How to escape the % (percent) sign in C's printf?

The double '%' works also in ".Format(…). Example (with iDrawApertureMask == 87, fCornerRadMask == 0.05): csCurrentLine.Format("\%ADD%2d%C,%6.4f*\%",iDrawApertureMask,fCornerRadMask) ; gives the desired and expected value of (string contents in) csCurrentLine; "%ADD87C, 0.0500*%"

Rails :include vs. :joins

'joins' just used to join tables and when you called associations on joins then it will again fire query (it mean many query will fire)

lets suppose you have tow model, User and Organisation
User has_many organisations
suppose you have 10 organisation for a user 
@records= User.joins(:organisations).where("organisations.user_id = 1")
QUERY will be 
 select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1

it will return all records of organisation related to user
and @records.map{|u|u.organisation.name}
it run QUERY like 
select * from organisations where organisations.id = x then time(hwo many organisation you have)

total number of SQL is 11 in this case

But with 'includes' will eager load the included associations and add them in memory(load all associations on first load) and not fire query again

when you get records with includes like @records= User.includes(:organisations).where("organisations.user_id = 1") then query will be

select * from users INNER JOIN organisations ON organisations.user_id = users.id where organisations.user_id = 1
and 


 select * from organisations where organisations.id IN(IDS of organisation(1, to 10)) if 10 organisation
and when you run this 

@records.map{|u|u.organisation.name} no query will fire

jquery <a> tag click event

<a href="javascript:void(0)" class="aaf" id="users_id">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
  var usersid =  $(this).attr("id");
  //post code
})

//other method is to use the data attribute

<a href="javascript:void(0)" class="aaf" data-id="102" data-username="sample_username">add as a friend</a>

on jquery

$('.aaf').on("click",function(){
    var usersid =  $(this).data("id");
    var username = $(this).data("username");
})

Trying to SSH into an Amazon Ec2 instance - permission error

Well, looking at your post description I feel there were 2 mistakes done by you:-

  1. Set correct permissions for the private key. Below command should help you to set correct file permision.

    chmod 0600 mykey.pem

  2. Wrong ec2 user you are trying to login.

    Looking at your debug log I think you have spawned an Amazon linux instance. The default user for that instance type is ec2-user . If the instance would have been ubuntu then your default user would have been ubuntu .

    ssh -i privatekey.pem default_ssh_user@server_ip

Note:
   For an Amazon Linux AMI, the default user name is ec2-user.

   For a Centos AMI, the default user name is centos.

   For a Debian AMI, the default user name is admin or root.

   For a Fedora AMI, the default user name is ec2-user or fedora.

   For a RHEL AMI, the default user name is ec2-user or root.

   For a SUSE AMI, the default user name is ec2-user or root.

   For an Ubuntu AMI, the default user name is ubuntu.

   Otherwise, if ec2-user and root don't work, check with the AMI provider.

source: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html

Best practice for partial updates in a RESTful service

It doesn't matter. In terms of REST, you can't do a GET, because it's not cacheable, but it doesn't matter if you use POST or PATCH or PUT or whatever, and it doesn't matter what the URL looks like. If you're doing REST, what matters is that when you get a representation of your resource from the server, that representation is able give the client state transition options.

If your GET response had state transitions, the client just needs to know how to read them, and the server can change them if needed. Here an update is done using POST, but if it was changed to PATCH, or if the URL changes, the client still knows how to make an update:

{
  "customer" :
  {
  },
  "operations":
  [
    "update" : 
    {
      "method": "POST",
      "href": "https://server/customer/123/"
    }]
}

You could go as far as to list required/optional parameters for the client to give back to you. It depends on the application.

As far as business operations, that might be a different resource linked to from the customer resource. If you want to send an email to the customer, maybe that service is it's own resource that you can POST to, so you might include the following operation in the customer resource:

"email":
{
  "method": "POST",
  "href": "http://server/emailservice/send?customer=1234"
}

Some good videos, and example of the presenter's REST architecture are these. Stormpath only uses GET/POST/DELETE, which is fine since REST has nothing to do with what operations you use or how URLs should look (except GETs should be cacheable):

https://www.youtube.com/watch?v=pspy1H6A3FM,
https://www.youtube.com/watch?v=5WXYw4J4QOU,
http://docs.stormpath.com/rest/quickstart/

SelectedValue vs SelectedItem.Value of DropDownList

They are both different. SelectedValue property gives you the actual value of the item in selection whereas SelectedItem.Text gives you the display text. For example: you drop down may have an itme like

<asp:ListItem Text="German" Value="de"></asp:ListItem>

So, in this case SelectedValue would be de and SelectedItem.Text would give 'German'

EDIT:

In that case, they aare both same ... Cause SelectedValue will give you the value stored for current selected item in your dropdown and SelectedItem.Value will be Value of the currently selected item.

So they both would give you the same result.

What is a Java String's default initial value?

Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.

Can you use if/else conditions in CSS?

As far as i know, there is no if/then/else in css. Alternatively, you can use javascript function to alter the background-position property of an element.

How can I see the specific value of the sql_mode?

It's only blank for you because you have not set the sql_mode. If you set it, then that query will show you the details:

mysql> SELECT @@sql_mode;
+------------+
| @@sql_mode |
+------------+
|            |
+------------+
1 row in set (0.00 sec)

mysql> set sql_mode=ORACLE;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT @@sql_mode;
+----------------------------------------------------------------------------------------------------------------------+
| @@sql_mode                                                                                                           |
+----------------------------------------------------------------------------------------------------------------------+
| PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE,ORACLE,NO_KEY_OPTIONS,NO_TABLE_OPTIONS,NO_FIELD_OPTIONS,NO_AUTO_CREATE_USER |
+----------------------------------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

"Input string was not in a correct format."

You have not mentioned if your textbox have values in design time or now. When form initializes text box may not hae value if you have not put it in textbox when during form design. you can put int value in form design by setting text property in desgin and this should work.

Environment variables in Eclipse

I've created an eclipse plugin for this, because I had the same problem. Feel free to download it and contribute to it.

It's still in early development, but it does its job already for me.

https://github.com/JorisAerts/Eclipse-Environment-Variables

enter image description here

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

Getting an error "fopen': This function or variable may be unsafe." when compling

This is not an error, it is a warning from your Microsoft compiler.

Select your project and click "Properties" in the context menu.

In the dialog, chose Configuration Properties -> C/C++ -> Preprocessor

In the field PreprocessorDefinitions add ;_CRT_SECURE_NO_WARNINGS to turn those warnings off.

How can I set the opacity or transparency of a Panel in WinForms?

Don't forget to bring your Panel to the Front when dynamically creating it in the form constructor. Example of transparent panel overlay of tab control.

panel1 = new TransparentPanel();
panel1.BackColor = System.Drawing.Color.Transparent;
panel1.Location = new System.Drawing.Point(0, 0);
panel1.Name = "panel1";
panel1.Size = new System.Drawing.Size(717, 92);
panel1.TabIndex = 0;
tab2.Controls.Add(panel1);
panel1.BringToFront(); 

// <== otherwise the other controls paint over top of the transparent panel

A process crashed in windows .. Crash dump location

On Windows 2008 R2, I have seen application crash dumps under either

C:\Users\[Some User]\Microsoft\Windows\WER\ReportArchive

or

C:\ProgramData\Microsoft\Windows\WER\ReportArchive

I don't know how Windows decides which directory to use.

No connection could be made because the target machine actively refused it 127.0.0.1

There is a firewall blocking the connection or the process that is hosting the service is not listening on that port. Or it is listening on a different port.

What is TypeScript and why would I use it in place of JavaScript?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Five years later, this is an OK overview, but look at Lodewijk's answer below for more depth

1000ft view...

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

To get an idea of what I mean, watch Microsoft's introductory video on the language.

For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.

Are there other technologies like it?

There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)

Example

As an example, here's some TypeScript (you can play with this in the TypeScript Playground)

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}  

And here's the JavaScript it would produce

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet() method returns a string.

Debugging TypeScript

Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio

Want to know more?

I originally wrote this answer when TypeScript was still hot-off-the-presses. Check out Lodewijk's answer to this question for some more current detail.

Using .NET, how can you find the mime type of a file based on the file signature not the extension

Edit: Just use Mime Detective

I use byte array sequences to determine the correct MIME type of a given file. The advantage of this over just looking at the file extension of the file name is that if a user were to rename a file to bypass certain file type upload restrictions, the file name extension would fail to catch this. On the other hand, getting the file signature via byte array will stop this mischievous behavior from happening.

Here is an example in C#:

public class MimeType
{
    private static readonly byte[] BMP = { 66, 77 };
    private static readonly byte[] DOC = { 208, 207, 17, 224, 161, 177, 26, 225 };
    private static readonly byte[] EXE_DLL = { 77, 90 };
    private static readonly byte[] GIF = { 71, 73, 70, 56 };
    private static readonly byte[] ICO = { 0, 0, 1, 0 };
    private static readonly byte[] JPG = { 255, 216, 255 };
    private static readonly byte[] MP3 = { 255, 251, 48 };
    private static readonly byte[] OGG = { 79, 103, 103, 83, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0 };
    private static readonly byte[] PDF = { 37, 80, 68, 70, 45, 49, 46 };
    private static readonly byte[] PNG = { 137, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13, 73, 72, 68, 82 };
    private static readonly byte[] RAR = { 82, 97, 114, 33, 26, 7, 0 };
    private static readonly byte[] SWF = { 70, 87, 83 };
    private static readonly byte[] TIFF = { 73, 73, 42, 0 };
    private static readonly byte[] TORRENT = { 100, 56, 58, 97, 110, 110, 111, 117, 110, 99, 101 };
    private static readonly byte[] TTF = { 0, 1, 0, 0, 0 };
    private static readonly byte[] WAV_AVI = { 82, 73, 70, 70 };
    private static readonly byte[] WMV_WMA = { 48, 38, 178, 117, 142, 102, 207, 17, 166, 217, 0, 170, 0, 98, 206, 108 };
    private static readonly byte[] ZIP_DOCX = { 80, 75, 3, 4 };

    public static string GetMimeType(byte[] file, string fileName)
    {

        string mime = "application/octet-stream"; //DEFAULT UNKNOWN MIME TYPE

        //Ensure that the filename isn't empty or null
        if (string.IsNullOrWhiteSpace(fileName))
        {
            return mime;
        }

        //Get the file extension
        string extension = Path.GetExtension(fileName) == null
                               ? string.Empty
                               : Path.GetExtension(fileName).ToUpper();

        //Get the MIME Type
        if (file.Take(2).SequenceEqual(BMP))
        {
            mime = "image/bmp";
        }
        else if (file.Take(8).SequenceEqual(DOC))
        {
            mime = "application/msword";
        }
        else if (file.Take(2).SequenceEqual(EXE_DLL))
        {
            mime = "application/x-msdownload"; //both use same mime type
        }
        else if (file.Take(4).SequenceEqual(GIF))
        {
            mime = "image/gif";
        }
        else if (file.Take(4).SequenceEqual(ICO))
        {
            mime = "image/x-icon";
        }
        else if (file.Take(3).SequenceEqual(JPG))
        {
            mime = "image/jpeg";
        }
        else if (file.Take(3).SequenceEqual(MP3))
        {
            mime = "audio/mpeg";
        }
        else if (file.Take(14).SequenceEqual(OGG))
        {
            if (extension == ".OGX")
            {
                mime = "application/ogg";
            }
            else if (extension == ".OGA")
            {
                mime = "audio/ogg";
            }
            else
            {
                mime = "video/ogg";
            }
        }
        else if (file.Take(7).SequenceEqual(PDF))
        {
            mime = "application/pdf";
        }
        else if (file.Take(16).SequenceEqual(PNG))
        {
            mime = "image/png";
        }
        else if (file.Take(7).SequenceEqual(RAR))
        {
            mime = "application/x-rar-compressed";
        }
        else if (file.Take(3).SequenceEqual(SWF))
        {
            mime = "application/x-shockwave-flash";
        }
        else if (file.Take(4).SequenceEqual(TIFF))
        {
            mime = "image/tiff";
        }
        else if (file.Take(11).SequenceEqual(TORRENT))
        {
            mime = "application/x-bittorrent";
        }
        else if (file.Take(5).SequenceEqual(TTF))
        {
            mime = "application/x-font-ttf";
        }
        else if (file.Take(4).SequenceEqual(WAV_AVI))
        {
            mime = extension == ".AVI" ? "video/x-msvideo" : "audio/x-wav";
        }
        else if (file.Take(16).SequenceEqual(WMV_WMA))
        {
            mime = extension == ".WMA" ? "audio/x-ms-wma" : "video/x-ms-wmv";
        }
        else if (file.Take(4).SequenceEqual(ZIP_DOCX))
        {
            mime = extension == ".DOCX" ? "application/vnd.openxmlformats-officedocument.wordprocessingml.document" : "application/x-zip-compressed";
        }

        return mime;
    }


}

Notice I handled DOCX file types differently since DOCX is really just a ZIP file. In this scenario, I simply check the file extension once I verified that it has that sequence. This example is far from complete for some people, but you can easily add your own.

If you want to add more MIME types, you can get the byte array sequences of many different file types from here. Also, here is another good resource concerning file signatures.

What I do a lot of times if all else fails is step through several files of a particular type that I am looking for and look for a pattern in the byte sequence of the files. In the end, this is still basic verification and cannot be used for 100% proof of determining file types.

Server is already running in Rails

On Windows Rails 5.2, delete this file

c:/Sites/<your_folder>/tmp/pids/server.pid

and run

rails s

again.

What does HTTP/1.1 302 mean exactly?

According to RFC 1945/Hypertext Transfer Protocol - HTTP / 1.0:

   302 Moved Temporarily

   The requested resource resides temporarily under a different URL.
   Since the redirection may be altered on occasion, the client should
   continue to use the Request-URI for future requests.

   The URL must be given by the Location field in the response. Unless
   it was a HEAD request, the Entity-Body of the response should
   contain a short note with a hyperlink to the new URI(s).

   If the 302 status code is received in response to a request using
   the POST method, the user agent must not automatically redirect the
   request unless it can be confirmed by the user, since this might
   change the conditions under which the request was issued.

       Note: When automatically redirecting a POST request after
       receiving a 302 status code, some existing user agents will
       erroneously change it into a GET request.

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

var newTH = document.createElement('th');
newTH.onclick = function() {
      //Your code here
}

Java Delegates?

It doesn't have an explicit delegate keyword as C#, but you can achieve similar in Java 8 by using a functional interface (i.e. any interface with exactly one method) and lambda:

private interface SingleFunc {
    void printMe();
}

public static void main(String[] args) {
    SingleFunc sf = () -> {
        System.out.println("Hello, I am a simple single func.");
    };
    SingleFunc sfComplex = () -> {
        System.out.println("Hello, I am a COMPLEX single func.");
    };
    delegate(sf);
    delegate(sfComplex);
}

private static void delegate(SingleFunc f) {
    f.printMe();
}

Every new object of type SingleFunc must implement printMe(), so it is safe to pass it to another method (e.g. delegate(SingleFunc)) to call the printMe() method.

How to configure XAMPP to send mail from localhost?

I tried many ways to send a mail from XAMPP Localhost, but since XAMPP hasn't SSL Certificate, my email request blocked by Gmail or similar SMTP Service providers.

Then I used MailHog for local smtp server, what you need to do is just run it. localhost:1025 is for smtp server, localhost:8025 is for mail server, where you can check the emails you sent.

here is my code:

    require_once "src/PHPMailer.php";
    require_once "src/SMTP.php";
    require_once "src/Exception.php";

    $mail = new PHPMailer\PHPMailer\PHPMailer();

      //Server settings
    $mail->SMTPDebug = 3;                      // Enable verbose debug output
    $mail->isSMTP();                                            // Send using SMTP
    $mail->Host       = 'localhost';                    // Set the SMTP server to send through
    $mail->Port       = 1025;                                    // TCP port to connect to
    // $mail->Username   = '';                     // SMTP username
    // $mail->Password   = '';                               // SMTP password
    // $mail->SMTPAuth   = true;                                   // Enable SMTP authentication
    // $mail->SMTPSecure = 'tls';         // Enable TLS encryption; `PHPMailer::ENCRYPTION_SMTPS` also accepted

    //Recipients
    $mail->setFrom('[email protected]', 'Mailer');
    $mail->addAddress('[email protected]', 'Joe User');     // Add a recipient

    // Content
    $mail->isHTML(true);                                  // Set email format to HTML
    $mail->Subject = 'Here is the subject';
    $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
    $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

    if(!$mail->Send()) {
        echo "Mailer Error: " . $mail->ErrorInfo;
    } else {
        echo "Message sent!";
    }

MailHog Github Repository link

In Python, how do I iterate over a dictionary in sorted key order?

Greg's answer is right. Note that in Python 3.0 you'll have to do

sorted(dict.items())

as iteritems will be gone.

How to validate email id in angularJs using ng-pattern

According to the answer of @scx ,I created a validation for GUI

app.directive('validateEmail', function() {
  var EMAIL_REGEXP = /^[_a-z0-9]+(\.[_a-z0-9]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$/;
  return {
    link: function(scope, elm) {
      elm.on("keyup",function(){
            var isMatchRegex = EMAIL_REGEXP.test(elm.val());
            if( isMatchRegex&& elm.hasClass('warning') || elm.val() == ''){
              elm.removeClass('warning');
            }else if(isMatchRegex == false && !elm.hasClass('warning')){
              elm.addClass('warning');
            }
      });
    }
  }
});

And simply add :

css

.warning{
   border:1px solid red;
 }

html

<input type='email' validate-email name='email' id='email' ng-model='email' required>

How can I use Html.Action?

You should look at the documentation for the Action method; it's explained well. For your case, this should work:

@Html.Action("GetOptions", new { pk="00", rk="00" });

The controllerName parameter will default to the controller from which Html.Action is being invoked. So if you're trying to invoke an action from another controller, you'll have to specify the controller name like so:

@Html.Action("GetOptions", "ControllerName", new { pk="00", rk="00" });

How do I clear my Jenkins/Hudson build history?

Using Script Console.

In case the jobs are grouped it's possible to either give it a full name with forward slashes:

getItemByFullName("folder_name/job_name") 
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()

or traverse the hierarchy like this:

def folder = Jenkins.instance.getItem("folder_name")
def job = folder.getItem("job_name")
job.getBuilds().each { it.delete() }
job.nextBuildNumber = 1
job.save()

Call static methods from regular ES6 class methods

I stumbled over this thread searching for answer to similar case. Basically all answers are found, but it's still hard to extract the essentials from them.

Kinds of Access

Assume a class Foo probably derived from some other class(es) with probably more classes derived from it.

Then accessing

  • from static method/getter of Foo
    • some probably overridden static method/getter:
      • this.method()
      • this.property
    • some probably overridden instance method/getter:
      • impossible by design
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • impossible by design
  • from instance method/getter of Foo
    • some probably overridden static method/getter:
      • this.constructor.method()
      • this.constructor.property
    • some probably overridden instance method/getter:
      • this.method()
      • this.property
    • own non-overridden static method/getter:
      • Foo.method()
      • Foo.property
    • own non-overridden instance method/getter:
      • not possible by intention unless using some workaround:
        • Foo.prototype.method.call( this )
        • Object.getOwnPropertyDescriptor( Foo.prototype,"property" ).get.call(this);

Keep in mind that using this isn't working this way when using arrow functions or invoking methods/getters explicitly bound to custom value.

Background

  • When in context of an instance's method or getter
    • this is referring to current instance.
    • super is basically referring to same instance, but somewhat addressing methods and getters written in context of some class current one is extending (by using the prototype of Foo's prototype).
    • definition of instance's class used on creating it is available per this.constructor.
  • When in context of a static method or getter there is no "current instance" by intention and so
    • this is available to refer to the definition of current class directly.
    • super is not referring to some instance either, but to static methods and getters written in context of some class current one is extending.

Conclusion

Try this code:

_x000D_
_x000D_
class A {_x000D_
  constructor( input ) {_x000D_
    this.loose = this.constructor.getResult( input );_x000D_
    this.tight = A.getResult( input );_x000D_
    console.log( this.scaledProperty, Object.getOwnPropertyDescriptor( A.prototype, "scaledProperty" ).get.call( this ) );_x000D_
  }_x000D_
_x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 100;_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return input * this.scale;_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 2;_x000D_
  }_x000D_
}_x000D_
_x000D_
class B extends A {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
    this.tight = B.getResult( input ) + " (of B)";_x000D_
  }_x000D_
  _x000D_
  get scaledProperty() {_x000D_
    return parseInt( this.loose ) * 10000;_x000D_
  }_x000D_
_x000D_
  static get scale() {_x000D_
    return 4;_x000D_
  }_x000D_
}_x000D_
_x000D_
class C extends B {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 5;_x000D_
  }_x000D_
}_x000D_
_x000D_
class D extends C {_x000D_
  constructor( input ) {_x000D_
    super( input );_x000D_
  }_x000D_
  _x000D_
  static getResult( input ) {_x000D_
    return super.getResult( input ) + " (overridden)";_x000D_
  }_x000D_
  _x000D_
  static get scale() {_x000D_
    return 10;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
let instanceA = new A( 4 );_x000D_
console.log( "A.loose", instanceA.loose );_x000D_
console.log( "A.tight", instanceA.tight );_x000D_
_x000D_
let instanceB = new B( 4 );_x000D_
console.log( "B.loose", instanceB.loose );_x000D_
console.log( "B.tight", instanceB.tight );_x000D_
_x000D_
let instanceC = new C( 4 );_x000D_
console.log( "C.loose", instanceC.loose );_x000D_
console.log( "C.tight", instanceC.tight );_x000D_
_x000D_
let instanceD = new D( 4 );_x000D_
console.log( "D.loose", instanceD.loose );_x000D_
console.log( "D.tight", instanceD.tight );
_x000D_
_x000D_
_x000D_

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

How about just using a containing div which has overflow set to hidden and some padding at the bottom? This seems like much the simplest solution.

Sorry to say I didn't think of this myself but saw it somewhere else.

Using an element to wrap the element getting the box-shadow and a overflow: hidden on the wrapper you could make the extra box-shadow disappear and still have a usable border. This also fixes the problem where the element is smaller as it seems, because of the spread.

Like this:

#wrapper { padding-bottom: 10px; overflow: hidden; }
#elem { box-shadow: 0 0 10px black; }

Content goes here

Still a clever solution when it has to be done in pure CSS!

As said by Jorgen Evens.

How to put sshpass command inside a bash script?

Do which sshpass in your command line to get the absolute path to sshpass and replace it in the bash script.

You should also probably do the same with the command you are trying to run.

The problem might be that it is not finding it.

What's the net::ERR_HTTP2_PROTOCOL_ERROR about?

This error is currently being fixed: https://chromium-review.googlesource.com/c/chromium/src/+/2001234

But it helped me, changing nginx settings:

  • turning on gzip;
  • add_header 'Cache-Control' 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0';
  • expires off;

In my case, Nginx acts as a reverse proxy for Node.js application.

Can you require two form fields to match with HTML5?

Not exactly with HTML5 validation but a little JavaScript can resolve the issue, follow the example below:

<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
    function check(input) {
        if (input.value != document.getElementById('password').value) {
            input.setCustomValidity('Password Must be Matching.');
        } else {
            // input is valid -- reset the error message
            input.setCustomValidity('');
        }
    }
</script>
<br /><br />
<input type="submit" />

Where should I put the log4j.properties file?

I've spent a great deal of time to figure out why the log4j.properties file is not seen.
Then I noticed it was visible for the project only when it was in both MyProject/target/classes/ and MyProject/src/main/resources folders.
Hope it'll be useful to somebody.
PS: The project was maven-based.

How to execute a bash command stored as a string with quotes and asterisk

try this

$ cmd='mysql AMORE -u root --password="password" -h localhost -e "select host from amoreconfig"'
$ eval $cmd

Is there a MySQL option/feature to track history of changes to records?

The direct way of doing this is to create triggers on tables. Set some conditions or mapping methods. When update or delete occurs, it will insert into 'change' table automatically.

But the biggest part is what if we got lots columns and lots of table. We have to type every column's name of every table. Obviously, It's waste of time.

To handle this more gorgeously, we can create some procedures or functions to retrieve name of columns.

We can also use 3rd-part tool simply to do this. Here, I write a java program Mysql Tracker

Remove object from a list of objects in python

You could try this to dynamically remove an object from an array without looping through it? Where e and t are just random objects.

>>> e = {'b':1, 'w': 2}
>>> t = {'b':1, 'w': 3}
>>> p = [e,t]
>>> p
[{'b': 1, 'w': 2}, {'b': 1, 'w': 3}]
>>>
>>> p.pop(p.index({'b':1, 'w': 3}))
{'b': 1, 'w': 3}
>>> p
[{'b': 1, 'w': 2}]
>>>

How to multi-line "Replace in files..." in Notepad++

Actually it's way easier to use ToolBucket plugin for Notepad++ to multiline replace.

To activate it just go to N++ menu:

Plugins > Plugin Manager > Show Plugin Manager > Check ToolBucket > Install.

Restart N++ and press ALT + SHIFT + F to multiline edit.

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

You actually need 3 meta tags to support Android, iPhone and Windows Phone

<!-- Chrome, Firefox OS and Opera -->
<meta name="theme-color" content="#4285f4">
<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-status-bar-style" content="#4285f4">

mvn command not found in OSX Mavrerick

I followed brain storm's instructions and still wasn't getting different results - any new terminal windows would not recognize the mvn command. I don't know why, but breaking out the declarations in smaller chunks .bash_profile worked. As far as I can tell, I'm essentially doing the same thing he did. Here's what looks different in my .bash_profile:

JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home
export PATH JAVA_HOME
J2=$JAVA_HOME/bin
export PATH J2
M2_HOME=/usr/local/apache-maven/apache-maven-2.2.1
export PATH M2_HOME
M2=$M2_HOME/bin
export PATH M2

How to center a button within a div?

Responsive way to center your button in a div:

<div 
    style="display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 2rem;">
    <button type="button" style="height: 10%; width: 20%;">hello</button>
</div>

How to remove focus from single editText

check this question and the selected answer: Stop EditText from gaining focus at Activity startup It's ugly but it works, and as far as I know there's no better solution.

Close Current Tab

Use this:

window.open('', '_self');

This only works in chrome; it is a bug. It will be fixed in the future, so use this hacky solution with this in mind.

HTML Image not displaying, while the src url works

In your angular.json folder structure should be like this

"assets": [             
  "src/assets",
  "src/favicon.ico"
],

not this

"assets": [     
  "src/favicon.ico",
  "src/assets",
],

This solved my problem.

Why do we need C Unions?

Unions are often used to convert between the binary representations of integers and floats:

union
{
  int i;
  float f;
} u;

// Convert floating-point bits to integer:
u.f = 3.14159f;
printf("As integer: %08x\n", u.i);

Although this is technically undefined behavior according to the C standard (you're only supposed to read the field which was most recently written), it will act in a well-defined manner in virtually any compiler.

Unions are also sometimes used to implement pseudo-polymorphism in C, by giving a structure some tag indicating what type of object it contains, and then unioning the possible types together:

enum Type { INTS, FLOATS, DOUBLE };
struct S
{
  Type s_type;
  union
  {
    int s_ints[2];
    float s_floats[2];
    double s_double;
  };
};

void do_something(struct S *s)
{
  switch(s->s_type)
  {
    case INTS:  // do something with s->s_ints
      break;

    case FLOATS:  // do something with s->s_floats
      break;

    case DOUBLE:  // do something with s->s_double
      break;
  }
}

This allows the size of struct S to be only 12 bytes, instead of 28.

Bootstrap Element 100% Width

Sometimes it's not possible to close the content container. The solution we are using is a bit different but prevent a overflow because of the firefox scrollbar size!

.full-width {
 margin-top: 15px;
 margin-bottom: 15px;
 position: relative;
 width: calc(100vw - 10px);
 margin-left: calc(-50vw + 5px);
 left: 50%;
}

Here is a example: https://jsfiddle.net/RubbelDeKatz/wvt9253q

GROUP BY without aggregate function

You're experiencing a strict requirement of the GROUP BY clause. Every column not in the group-by clause must have a function applied to reduce all records for the matching "group" to a single record (sum, max, min, etc).

If you list all queried (selected) columns in the GROUP BY clause, you are essentially requesting that duplicate records be excluded from the result set. That gives the same effect as SELECT DISTINCT which also eliminates duplicate rows from the result set.

What is the 'open' keyword in Swift?

open is only for another module for example: cocoa pods, or unit test, we can inherit or override

MetadataException when using Entity Framework Entity Connection

I had the same error message, and the problem was also the metadata part of the connection string, but I had to dig a little deeper to solve it and wanted to share this little nugget:

The metadata string is made up of three sections that each look like this:

res://
      (assembly)/
      (model name).(ext)

Where ext is "csdl", "ssdl", and "msl".

For most people, assembly can probably be "*", which seems to indicate that all loaded assemblies will be searched (I haven't done a huge amount of testing of this). This part wasn't an issue for me, so I can't comment on whether you need the assembly name or file name (i.e., with or without ".dll"), though I have seen both suggested.

The model name part should be the name and namespace of your .edmx file, relative to your assembly. So if you have a My.DataAccess assembly and you create DataModels.edmx in a Models folder, its full name is My.DataAccess.Models.DataModels. In this case, you would have "Models.DataModels.(ext)" in your metadata.

If you ever move or rename your .edmx file, you will need to update your metadata string manually (in my experience), and remembering to change the relative namespace will save a few headaches.

How to Convert Int to Unsigned Byte and Back

The solution works fine (thanks!), but if you want to avoid casting and leave the low level work to the JDK, you can use a DataOutputStream to write your int's and a DataInputStream to read them back in. They are automatically treated as unsigned bytes then:

For converting int's to binary bytes;

ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(bos);
int val = 250;
dos.write(byteVal);
...
dos.flush();

Reading them back in:

// important to use a (non-Unicode!) encoding like US_ASCII or ISO-8859-1,
// i.e., one that uses one byte per character
ByteArrayInputStream bis = new ByteArrayInputStream(
   bos.toString("ISO-8859-1").getBytes("ISO-8859-1"));
DataInputStream dis = new DataInputStream(bis);
int byteVal = dis.readUnsignedByte();

Esp. useful for handling binary data formats (e.g. flat message formats, etc.)

How can I check whether a radio button is selected with JavaScript?

The scripts in this page helped me come up with the script below, which I think is more complete and universal. Basically it will validate any number of radio buttons in a form, meaning that it will make sure that a radio option has been selected for each one of the different radio groups within the form. e.g in the test form below:

   <form id="FormID">

    Yes <input type="radio" name="test1" value="Yes">
    No <input type="radio" name="test1" value="No">

    <br><br>

    Yes <input type="radio" name="test2" value="Yes">
    No <input type="radio" name="test2" value="No">

   <input type="submit" onclick="return RadioValidator();">

The RadioValidator script will make sure that an answer has been given for both 'test1' and 'test2' before it submits. You can have as many radio groups in the form, and it will ignore any other form elements. All missing radio answers will show inside a single alert popup. Here it goes, I hope it helps people. Any bug fixings or helpful modifications welcome :)

<SCRIPT LANGUAGE="JAVASCRIPT">
function RadioValidator()
{
    var ShowAlert = '';
    var AllFormElements = window.document.getElementById("FormID").elements;
    for (i = 0; i < AllFormElements.length; i++) 
    {
        if (AllFormElements[i].type == 'radio') 
        {
            var ThisRadio = AllFormElements[i].name;
            var ThisChecked = 'No';
            var AllRadioOptions = document.getElementsByName(ThisRadio);
            for (x = 0; x < AllRadioOptions.length; x++)
            {
                 if (AllRadioOptions[x].checked && ThisChecked == 'No')
                 {
                     ThisChecked = 'Yes';
                     break;
                 } 
            }   
            var AlreadySearched = ShowAlert.indexOf(ThisRadio);
            if (ThisChecked == 'No' && AlreadySearched == -1)
            {
            ShowAlert = ShowAlert + ThisRadio + ' radio button must be answered\n';
            }     
        }
    }
    if (ShowAlert != '')
    {
    alert(ShowAlert);
    return false;
    }
    else
    {
    return true;
    }
}
</SCRIPT>

Save string to the NSUserDefaults?

Something like this:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// saving an NSString
[prefs setObject:@"TextToSave" forKey:@"keyToLookupString"];

Then to retrieve:

NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];

// getting an NSString
NSString *myString = [prefs stringForKey:@"keyToLookupString"];

You should really check out Apple's NSUserDefaults Class Reference and also maybe this tutorial: iPhone Programming Tutorial – Saving/Retrieving Data Using NSUserDefaults

Remove the newline character in a list read from a file

You want the String.strip(s[, chars]) function, which will strip out whitespace characters or whatever characters (such as '\n') you specify in the chars argument.

See http://docs.python.org/release/2.3/lib/module-string.html

What is the best method of handling currency/money?

You can pass some options to number_to_currency (a standard Rails 4 view helper):

number_to_currency(12.0, :precision => 2)
# => "$12.00"

As posted by Dylan Markow

How to use performSelector:withObject:afterDelay: with primitive types in Cocoa?

I find that the quickest (but somewhat dirty) way to do this is by invoking objc_msgSend directly. However, it's dangerous to invoke it directly because you need to read the documentation and make sure that you're using the correct variant for the type of return value and because objc_msgSend is defined as vararg for compiler convenience but is actually implemented as fast assembly glue. Here's some code used to call a delegate method -[delegate integerDidChange:] that takes a single integer argument.

#import <objc/message.h>


SEL theSelector = @selector(integerDidChange:);
if ([self.delegate respondsToSelector:theSelector])
{
    typedef void (*IntegerDidChangeFuncPtrType)(id, SEL, NSInteger);
    IntegerDidChangeFuncPtrType MyFunction = (IntegerDidChangeFuncPtrType)objc_msgSend;
    MyFunction(self.delegate, theSelector, theIntegerThatChanged);
}

This first saves the selector since we're going to refer to it multiple times and it would be easy to create a typo. It then verifies that the delegate actually responds to the selector - it might be an optional protocol. It then creates a function pointer type that specifies the actual signature of the selector. Keep in mind that all Objective-C messages have two hidden first arguments, the object being messaged and the selector being sent. Then we create a function pointer of the appropriate type and set it to point to the underlying objc_msgSend function. Keep in mind that if the return value is a float or struct, you need to use a different variant of objc_msgSend. Finally, send the message using the same machinery that Objective-C uses under the sheets.

Laravel - display a PDF file in storage without forcing download?

Ben Swinburne answer was so helpful.

The code below is for those who have their PDF file in database like me.

$pdf = DB::table('exportfiles')->select('pdf')->where('user_id', $user_id)->first();

return Response::make(base64_decode( $pdf->pdf), 200, [
    'Content-Type' => 'application/pdf',
    'Content-Disposition' => 'inline; filename="'.$filename.'"',
]);

Where $pdf->pdf is the file column in database.

How to resolve "The requested URL was rejected. Please consult with your administrator." error?

I found the issue. This is a firewall message and an error was occurring in the VB script due to wrong data in database, but the error was not logged/caught properly.

What is the difference between "::" "." and "->" in c++

The three operators have related but different meanings, despite the misleading note from the IDE.

The :: operator is known as the scope resolution operator, and it is used to get from a namespace or class to one of its members.

The . and -> operators are for accessing an object instance's members, and only comes into play after creating an object instance. You use . if you have an actual object (or a reference to the object, declared with & in the declared type), and you use -> if you have a pointer to an object (declared with * in the declared type).

The this object is always a pointer to the current instance, hence why the -> operator is the only one that works.

Examples:

// In a header file
namespace Namespace {
    class Class {
        private:
            int x;
        public:
            Class() : x(4) {}
            void incrementX();
    };
}

// In an implementation file
namespace Namespace {
    void Class::incrementX() {    // Using scope resolution to get to the class member when we aren't using an instance
        ++(this->x);              // this is a pointer, so using ->. Equivalent to ++((*this).x)
    }
}

// In a separate file lies your main method
int main() {
    Namespace::Class myInstance;   // instantiates an instance. Note the scope resolution
    Namespace::Class *myPointer = new Namespace::Class;
    myInstance.incrementX();       // Calling a function on an object instance.
    myPointer->incrementX();       // Calling a function on an object pointer.
    (*myPointer).incrementX();     // Calling a function on an object pointer by dereferencing first

    return 0;
}

Div width 100% minus fixed amount of pixels

New way I've just stumbled upon: css calc():

.calculated-width {
    width: -webkit-calc(100% - 100px);
    width:    -moz-calc(100% - 100px);
    width:         calc(100% - 100px);
}?

Source: css width 100% minus 100px

Spring Boot yaml configuration for a list of strings

In my case this was a syntax issue in the .yml file. I had:

@Value("${spring.kafka.bootstrap-servers}")
public List<String> BOOTSTRAP_SERVERS_LIST;

and the list in my .yml file:

bootstrap-servers:
  - s1.company.com:9092
  - s2.company.com:9092
  - s3.company.com:9092

was not reading into the @Value-annotated field. When I changed the syntax in the .yml file to:

bootstrap-servers >
  s1.company.com:9092
  s2.company.com:9092
  s3.company.com:9092

it worked fine.

Run ScrollTop with offset of element by ID

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top;   
if (!isNaN(top)) {
$("#app_scroler").click(function () {   
$('html, body').animate({
            scrollTop: top
        }, 100);
    });
}

if you want to scroll a little above or below from specific div that add value to the top like this.....like I add 800

var top = ($(".apps_intro_wrapper_inner").offset() || { "top": NaN }).top + 800;

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

Building a fat jar using maven

You can use the onejar-maven-plugin for packaging. Basically, it assembles your project and its dependencies in as one jar, including not just your project jar file, but also all external dependencies as a "jar of jars", e.g.

<build>
    <plugins>
        <plugin>
            <groupId>com.jolira</groupId>
            <artifactId>onejar-maven-plugin</artifactId>
                <version>1.4.4</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>one-jar</goal>
                        </goals>
                    </execution>
                </executions>
        </plugin>
    </plugins>
</build>

Note 1: Configuration options is available at the project home page.

Note 2: For one reason or the other, the onejar-maven-plugin project is not published at Maven Central. However jolira.com tracks the original project and publishes it to with the groupId com.jolira.

Android sqlite how to check if a record exists

because of possible data leaks best solution via cursor:

 Cursor cursor = null;
    try {
          cursor =  .... some query (raw or not your choice)
          return cursor.moveToNext();
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }

1) From API KITKAT u can use resources try()

try (cursor = ...some query)

2) if u query against VARCHAR TYPE use '...' eg. COLUMN_NAME='string_to_search'

3) dont use moveToFirst() is used when you need to start iterating from beggining

4) avoid getCount() is expensive - it iterates over many records to count them. It doesn't return a stored variable. There may be some caching on a second call, but the first call doesn't know the answer until it is counted.

Add column to SQL query results

Manually add it when you build the query:

SELECT 'Site1' AS SiteName, t1.column, t1.column2
FROM t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column, t2.column2
FROM t2

UNION ALL
...

EXAMPLE:

DECLARE @t1 TABLE (column1 int, column2 nvarchar(1))
DECLARE @t2 TABLE (column1 int, column2 nvarchar(1))

INSERT INTO @t1
SELECT 1, 'a'
UNION SELECT 2, 'b'

INSERT INTO @t2
SELECT 3, 'c'
UNION SELECT 4, 'd'


SELECT 'Site1' AS SiteName, t1.column1, t1.column2
FROM @t1 t1

UNION ALL
SELECT 'Site2' AS SiteName, t2.column1, t2.column2
FROM @t2 t2

RESULT:

SiteName  column1  column2
Site1       1      a
Site1       2      b
Site2       3      c
Site2       4      d

How to upload and parse a CSV file in php

Although you could easily find a tutorial how to handle file uploads with php, and there are functions (manual) to handle CSVs, I will post some code because just a few days ago I worked on a project, including a bit of code you could use...

HTML:

<table width="600">
<form action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="post" enctype="multipart/form-data">

<tr>
<td width="20%">Select file</td>
<td width="80%"><input type="file" name="file" id="file" /></td>
</tr>

<tr>
<td>Submit</td>
<td><input type="submit" name="submit" /></td>
</tr>

</form>
</table>

PHP:

if ( isset($_POST["submit"]) ) {

   if ( isset($_FILES["file"])) {

            //if there was an error uploading the file
        if ($_FILES["file"]["error"] > 0) {
            echo "Return Code: " . $_FILES["file"]["error"] . "<br />";

        }
        else {
                 //Print file details
             echo "Upload: " . $_FILES["file"]["name"] . "<br />";
             echo "Type: " . $_FILES["file"]["type"] . "<br />";
             echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
             echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";

                 //if file already exists
             if (file_exists("upload/" . $_FILES["file"]["name"])) {
            echo $_FILES["file"]["name"] . " already exists. ";
             }
             else {
                    //Store file in directory "upload" with the name of "uploaded_file.txt"
            $storagename = "uploaded_file.txt";
            move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $storagename);
            echo "Stored in: " . "upload/" . $_FILES["file"]["name"] . "<br />";
            }
        }
     } else {
             echo "No file selected <br />";
     }
}

I know there must be an easier way to do this, but I read the CSV file and store the single cells of every record in an two dimensional array.

if ( isset($storagename) && $file = fopen( "upload/" . $storagename , r ) ) {

    echo "File opened.<br />";

    $firstline = fgets ($file, 4096 );
        //Gets the number of fields, in CSV-files the names of the fields are mostly given in the first line
    $num = strlen($firstline) - strlen(str_replace(";", "", $firstline));

        //save the different fields of the firstline in an array called fields
    $fields = array();
    $fields = explode( ";", $firstline, ($num+1) );

    $line = array();
    $i = 0;

        //CSV: one line is one record and the cells/fields are seperated by ";"
        //so $dsatz is an two dimensional array saving the records like this: $dsatz[number of record][number of cell]
    while ( $line[$i] = fgets ($file, 4096) ) {

        $dsatz[$i] = array();
        $dsatz[$i] = explode( ";", $line[$i], ($num+1) );

        $i++;
    }

        echo "<table>";
        echo "<tr>";
    for ( $k = 0; $k != ($num+1); $k++ ) {
        echo "<td>" . $fields[$k] . "</td>";
    }
        echo "</tr>";

    foreach ($dsatz as $key => $number) {
                //new table row for every record
        echo "<tr>";
        foreach ($number as $k => $content) {
                        //new table cell for every field of the record
            echo "<td>" . $content . "</td>";
        }
    }

    echo "</table>";
}

So I hope this will help, it is just a small snippet of code and I have not tested it, because I used it slightly different. The comments should explain everything.

Get the first element of each tuple in a list in Python

Use a list comprehension:

res_list = [x[0] for x in rows]

Below is a demonstration:

>>> rows = [(1, 2), (3, 4), (5, 6)]
>>> [x[0] for x in rows]
[1, 3, 5]
>>>

Alternately, you could use unpacking instead of x[0]:

res_list = [x for x,_ in rows]

Below is a demonstration:

>>> lst = [(1, 2), (3, 4), (5, 6)]
>>> [x for x,_ in lst]
[1, 3, 5]
>>>

Both methods practically do the same thing, so you can choose whichever you like.

Java String encoding (UTF-8)

This could be complicated way of doing

String newString = new String(oldString);

This shortens the String is the underlying char[] used is much longer.

However more specifically it will be checking that every character can be UTF-8 encoded.

There are some "characters" you can have in a String which cannot be encoded and these would be turned into ?

Any character between \uD800 and \uDFFF cannot be encoded and will be turned into '?'

String oldString = "\uD800";
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8");
System.out.println(newString.equals(oldString));

prints

false

Where does Android emulator store SQLite database?

In Android Studio 3.4.1, you can use the search feature of Android Studio to find "Device File Explorer" and then go to the /data/data/package_name/database directory of your emulator.

@try - catch block in Objective-C

All work perfectly :)

 NSString *test = @"test";
 unichar a;
 int index = 5;
    
 @try {
    a = [test characterAtIndex:index];
 }
 @catch (NSException *exception) {
    NSLog(@"%@", exception.reason);
    NSLog(@"Char at index %d cannot be found", index);
    NSLog(@"Max index is: %lu", [test length] - 1);
 }
 @finally {
    NSLog(@"Finally condition");
 }

Log:

[__NSCFConstantString characterAtIndex:]: Range or index out of bounds

Char at index 5 cannot be found

Max index is: 3

Finally condition

PHP code to remove everything but numbers

This is for future developers, you can also try this. Simple too

echo preg_replace('/\D/', '', '604-619-5135');

How do I install a Python package with a .whl file?

In-case if you unable to install specific package directly using PIP.

You can download a specific .whl (wheel) package from - https://www.lfd.uci.edu/~gohlke/pythonlibs/

CD (Change directory) to that downloaded package and install it manually by -
pip install PACKAGENAME.whl
ex:
pip install ad3-2.1-cp27-cp27m-win32.whl

What does the fpermissive flag do?

Right from the docs:

-fpermissive
Downgrade some diagnostics about nonconformant code from errors to warnings. Thus, using -fpermissive will allow some nonconforming code to compile.

Bottom line: don't use it unless you know what you are doing!

Left padding a String with Zeros

    int number = -1;
    int holdingDigits = 7;
    System.out.println(String.format("%0"+ holdingDigits +"d", number));

Just asked this in an interview........

My answer below but this (mentioned above) is much nicer->

String.format("%05d", num);

My answer is:

static String leadingZeros(int num, int digitSize) {
    //test for capacity being too small.

    if (digitSize < String.valueOf(num).length()) {
        return "Error : you number  " + num + " is higher than the decimal system specified capacity of " + digitSize + " zeros.";

        //test for capacity will exactly hold the number.
    } else if (digitSize == String.valueOf(num).length()) {
        return String.valueOf(num);

        //else do something here to calculate if the digitSize will over flow the StringBuilder buffer java.lang.OutOfMemoryError 

        //else calculate and return string
    } else {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < digitSize; i++) {
            sb.append("0");
        }
        sb.append(String.valueOf(num));
        return sb.substring(sb.length() - digitSize, sb.length());
    }
}

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

This feature will never be part of Sass. One major reason is import order. In CSS, the files imported last can override the styles stated before. If you import a directory, how can you determine import order? There's no way that doesn't introduce some new level of complexity. By keeping a list of imports (as you did in your example), you're being explicit with import order. This is essential if you want to be able to confidently override styles that are defined in another file or write mixins in one file and use them in another.

For a more thorough discussion, view this closed feature request here:

How do you synchronise projects to GitHub with Android Studio?

In the version of Android Studio I have (0.3.2), it was as easy as using the menu.

VCS Menu > Git > Share on GitHub.

It will then ask you for your credentials, and then a name for your new repo, and that's it!

Print a list in reverse order with range()?

for i in range(8, 0, -1)

will solve this problem. It will output 8 to 1, and -1 means a reversed list

What do .c and .h file extensions mean to C?

Of course, there is nothing that says the extension of a header file must be .h and the extension of a C source file must be .c. These are useful conventions.

E:\Temp> type my.interface
#ifndef MY_INTERFACE_INCLUDED
#define MYBUFFERSIZE 8
#define MY_INTERFACE_INCLUDED
#endif

E:\Temp> type my.source
#include <stdio.h>

#include "my.interface"

int main(void) {
    char x[MYBUFFERSIZE] = {0};
    x[0] = 'a';
    puts(x);
    return 0;
}

E:\Temp> gcc -x c my.source -o my.exe

E:\Temp> my
a

Can I set text box to readonly when using Html.TextBoxFor?

<%= Html.TextBoxFor(m => Model.Events.Subscribed[i].Action, new { @readonly = true })%>

How to display items side-by-side without using tables?

these days div is the new norm

<div style="float:left"><img.. ></div>
<div style="float:right">text</div>
<div style="clear:both"/>

How to select label for="XYZ" in CSS?

The selector would be label[for=email], so in CSS:

label[for=email]
{
    /* ...definitions here... */
}

...or in JavaScript using the DOM:

var element = document.querySelector("label[for=email]");

...or in JavaScript using jQuery:

var element = $("label[for=email]");

It's an attribute selector. Note that some browsers (versions of IE < 8, for instance) may not support attribute selectors, but more recent ones do. To support older browsers like IE6 and IE7, you'd have to use a class (well, or some other structural way), sadly.

(I'm assuming that the template {t _your_email} will fill in a field with id="email". If not, use a class instead.)

Note that if the value of the attribute you're selecting doesn't fit the rules for a CSS identifier (for instance, if it has spaces or brackets in it, or starts with a digit, etc.), you need quotes around the value:

label[for="field[]"]
{
    /* ...definitions here... */
}

They can be single or double quotes.

How do you revert to a specific tag in Git?

Use git reset:

git reset --hard "Version 1.0 Revision 1.5"

(assuming that the specified string is the tag).

Add space between two particular <td>s

my choice was to add a td between the two td tags and set the width to 25px. It can be more or less to your liking. This may be cheesy but it is simple and it works.

Invoking a static method using reflection

String methodName= "...";
String[] args = {};

Method[] methods = clazz.getMethods();
for (Method m : methods) {
    if (methodName.equals(m.getName())) {
        // for static methods we can use null as instance of class
        m.invoke(null, new Object[] {args});
        break;
    }
}

Batch File: ( was unexpected at this time

Oh, dear. A few little problems...

As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.

Two other matters of which you should be aware:

First, set/p will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:

 set "var="
 set /p var=

That is, of course, if you don't WANT enter to repeat the existing value.
Another useful form is

 set "var=default"
 set /p var=

or

 set "var=default"
 set /p "var=[%var%]"

(which prompts with the default value; !var! if in a block statement with delayedexpansion)

Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment (which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)

No mapping found for HTTP request with URI.... in DispatcherServlet with name

addition of <mvc:annotation-driven/> worked for me. Add it before line <context:component-scan ............/>