Programs & Examples On #Rich client platform

What's a redirect URI? how does it apply to iOS app for OAuth2.0?

Read this:

http://www.quora.com/OAuth-2-0/How-does-OAuth-2-0-work

or an even simpler but quick explanation:

http://agileanswer.blogspot.se/2012/08/oauth-20-for-my-ninth-grader.html

The redirect URI is the callback entry point of the app. Think about how OAuth for Facebook works - after end user accepts permissions, "something" has to be called by Facebook to get back to the app, and that "something" is the redirect URI. Furthermore, the redirect URI should be different than the initial entry point of the app.

The other key point to this puzzle is that you could launch your app from a URL given to a webview. To do this, i simply followed the guide on here:

http://iosdevelopertips.com/cocoa/launching-your-own-application-via-a-custom-url-scheme.html

and

http://inchoo.net/mobile-development/iphone-development/launching-application-via-url-scheme/

note: on those last 2 links, "http://" works in opening mobile safari but "tel://" doesn't work in simulator

in the first app, I call

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"secondApp://"]];

In my second app, I register "secondApp" (and NOT "secondApp://") as the name of URL Scheme, with my company as the URL identifier.

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

How to handle query parameters in angular 2

In Angular 6, I found this simpler way:

navigate(["/yourpage", { "someParamName": "paramValue"}]);

Then in the constructor or in ngInit you can directly use:

let value = this.route.snapshot.params.someParamName;

Fixing broken UTF-8 encoding

The way is to convert to binary and then to correct encoding

If (Array.Length == 0)

check if the array is null first so you would avoid a null pointer exception

logic in any language: if array is null or is empty :do ....

How do I add a newline to a TextView in Android?

Try:

android:lines="2"

\n should work.

How can I roll back my last delete command in MySQL?

In MySQL:

start transaction;

savepoint sp1;

delete from customer where ID=1;

savepoint sp2;

delete from customer where ID=2;

rollback to sp2;

rollback to sp1;

"Unknown class <MyClass> in Interface Builder file" error at runtime

I fixed this by copying the text from my class.h and .m, deleting those class files from the project, and creating new class.h and .m files with the same name using "Add File". Then I pasted the code back into the new files, and everything worked great. Somehow the files weren't linked correctly when they were created. I didn't need to use any linker flags after that.

not-null property references a null or transient value

I resolved by removing @Basic(optional = false) property or just update boolean @Basic(optional = true)

Using regular expression in css?

Try my generic CSS regular expression

(([a-z]{5,6}.*?\))|([\d.+-]?)(?![a-z\s#.()%])(\d?\.?\d?)?[a-z\d%]+)|(url\([/"'][a-z:/.]*['")]\))|(rgb|hsl)a?\(\d+%?,?\s?\d+%?,?\s?\d+%?(,\s?\d+\.?\d?)?\)|(#(\w|[\d]){3,8})|([\w]{3,8}(?=.*-))

Demo https://regexr.com/4a22i

How to split CSV files as per number of rows specified?

This should do it for you - all your files will end up called Part1-Part500.

#!/bin/bash
FILENAME=10000.csv
HDR=$(head -1 $FILENAME)   # Pick up CSV header line to apply to each file
split -l 20 $FILENAME xyz  # Split the file into chunks of 20 lines each
n=1
for f in xyz*              # Go through all newly created chunks
do
   echo $HDR > Part${n}    # Write out header to new file called "Part(n)"
   cat $f >> Part${n}      # Add in the 20 lines from the "split" command
   rm $f                   # Remove temporary file
   ((n++))                 # Increment name of output part
done

Remove Trailing Spaces and Update in Columns in SQL Server

update MyTable set CompanyName = rtrim(CompanyName)

What happens if you don't commit a transaction to a database (say, SQL Server)?

The behaviour is not defined, so you must explicit set a commit or a rollback:

http://docs.oracle.com/cd/B10500_01/java.920/a96654/basic.htm#1003303

"If auto-commit mode is disabled and you close the connection without explicitly committing or rolling back your last changes, then an implicit COMMIT operation is executed."

Hsqldb makes a rollback

con.setAutoCommit(false);
stmt.executeUpdate("insert into USER values ('" +  insertedUserId + "','Anton','Alaf')");
con.close();

result is

2011-11-14 14:20:22,519 main INFO [SqlAutoCommitExample:55] [AutoCommit enabled = false] 2011-11-14 14:20:22,546 main INFO [SqlAutoCommitExample:65] [Found 0# users in database]

BAT file: Open new cmd window and execute a command in there

You may already find your answer because it was some time ago you asked. But I tried to do something similar when coding ror. I wanted to run "rails server" in a new cmd window so I don't have to open a new cmd and then find my path again.

What I found out was to use the K switch like this:

start cmd /k echo Hello, World!

start before "cmd" will open the application in a new window and "/K" will execute "echo Hello, World!" after the new cmd is up.

You can also use the /C switch for something similar.

start cmd /C pause

This will then execute "pause" but close the window when the command is done. In this case after you pressed a button. I found this useful for "rails server", then when I shutdown my dev server I don't have to close the window after.


Use the following in your batch file:

start cmd.exe /c "more-batch-commands-here"

or

start cmd.exe /k "more-batch-commands-here"

/c Carries out the command specified by string and then terminates

/k Carries out the command specified by string but remains

The /c and /k options controls what happens once your command finishes running. With /c the terminal window will close automatically, leaving your desktop clean. With /k the terminal window will remain open. It's a good option if you want to run more commands manually afterwards.

Consult the cmd.exe documentation using cmd /? for more details.

Escaping Commands with White Spaces

The proper formatting of the command string becomes more complicated when using arguments with spaces. See the examples below. Note the nested double quotes in some examples.

Examples:

Run a program and pass a filename parameter:
CMD /c write.exe c:\docs\sample.txt

Run a program and pass a filename which contains whitespace:
CMD /c write.exe "c:\sample documents\sample.txt"

Spaces in program path:
CMD /c ""c:\Program Files\Microsoft Office\Office\Winword.exe""

Spaces in program path + parameters:
CMD /c ""c:\Program Files\demo.cmd"" Parameter1 Param2
CMD /k ""c:\batch files\demo.cmd" "Parameter 1 with space" "Parameter2 with space""

Launch demo1 and demo2:
CMD /c ""c:\Program Files\demo1.cmd" & "c:\Program Files\demo2.cmd""

Source: http://ss64.com/nt/cmd.html

default select option as blank

Maybe this will be helpful

<select>
    <option disabled selected value> -- select an option -- </option>
    <option>Option 1</option>
    <option>Option 2</option>
    <option>Option 3</option>
</select>

-- select an option -- Will be displayed by default. But if you choose an option,you will not be able select it back.

You can also hide it using by adding an empty option

<option style="display:none">

so it won't show up in the list anymore.

Option 2

If you don't want to write CSS and expect the same behaviour of the solution above, just use:

<option hidden disabled selected value> -- select an option -- </option>

Using CMake to generate Visual Studio C++ project files

We moved our department's build chain to CMake, and we had a few internal roadbumps since other departments where using our project files and where accustomed to just importing them into their solutions. We also had some complaints about CMake not being fully integrated into the Visual Studio project/solution manager, so files had to be added manually to CMakeLists.txt; this was a major break in the workflow people were used to.

But in general, it was a quite smooth transition. We're very happy since we don't have to deal with project files anymore.

The concrete workflow for adding a new file to a project is really simple:

  1. Create the file, make sure it is in the correct place.
  2. Add the file to CMakeLists.txt.
  3. Build.

CMake 2.6 automatically reruns itself if any CMakeLists.txt files have changed (and (semi-)automatically reloads the solution/projects).

Remember that if you're doing out-of-source builds, you need to be careful not to create the source file in the build directory (since Visual Studio only knows about the build directory).

powershell - list local users and their groups

try this one :),

Get-LocalGroup | %{ $groups = "$(Get-LocalGroupMember -Group $_.Name | %{ $_.Name } | Out-String)"; Write-Output "$($_.Name)>`r`n$($groups)`r`n" }

How to search for a part of a word with ElasticSearch

I am using this and got I worked

"query": {
        "query_string" : {
            "query" : "*test*",
            "fields" : ["field1","field2"],
            "analyze_wildcard" : true,
            "allow_leading_wildcard": true
        }
    }

How to style an asp.net menu with CSS

I remember the StaticSelectedStyle-CssClass attribute used to work in ASP.NET 2.0. And in .NET 4.0 if you change the Menu control's RenderingMode attribute "Table" (thus making it render the menu as s and sub-s like it did back '05) it will at least write your specified StaticSelectedStyle-CssClass into the proper html element.

That may be enough for you page to work like you want. However my work-around for the selected menu item in ASP 4.0 (when leaving RenderingMode to its default), is to mimic the control's generated "selected" CSS class but give mine the "!important" CSS declaration so my styles take precedence where needed.

For instance by default the Menu control renders an "li" element and child "a" for each menu item and the selected menu item's "a" element will contain class="selected" (among other control generated CSS class names including "static" if its a static menu item), therefore I add my own selector to the page (or in a separate stylesheet file) for "static" and "selected" "a" tags like so:

a.selected.static
{
background-color: #f5f5f5 !important;
border-top: Red 1px solid !important;
border-left: Red 1px solid !important;
border-right: Red 1px solid !important;
} 

How do I trim() a string in angularjs?

I insert this code in my tag and it works correctly:

ng-show="!Contract.BuyerName.trim()" >

Any way of using frames in HTML5?

Frames were not deprecated in HTML5, but were deprecated in XHTML 1.1 Strict and 2.0, but remained in XHTML Transitional and returned in HTML5. Also here is an interesting article on using CSS to mimic frames without frames. I just tested it in IE 8, FF 3, Opera 11, Safari 5, Chrome 8. I love frames, but they do have their problems, particularly with search engines, bookmarks and printing and with CSS you can create print or display only content. I'm hoping to upgrade Alex's XHTML/CSS frame without frames solution to HTML5/CSS3.

SQL Server datetime LIKE select?

You can use CONVERT to get the date in text form. If you convert it to a varchar(10), you can use = instead of like:

select *
from record
where CONVERT(VARCHAR(10),register_date,120) = '2009-10-10'

Or you can use an upper and lower boundary date, with the added advantage that it could make use of an index:

select *
from record
where '2009-10-10' <= register_date
and register_date < '2009-10-11'

Where to install Android SDK on Mac OS X?

brew install android-sdk --cask 

How to get the list of all installed color schemes in Vim?

Another simpler way is while you are editing a file - tabe ~/.vim/colors/ ENTER Will open all the themes in a new tab within vim window.

You may come back to the file you were editing using - CTRL + W + W ENTER

Note: Above will work ONLY IF YOU HAVE a .vim/colors directory within your home directory for current $USER (I have 70+ themes)

[user@host ~]$ ls -l ~/.vim/colors | wc -l

72

CSS: How to remove pseudo elements (after, before,...)?

had a same problem few minutes ago and just content:none; did not do work but adding content:none !important; and display:none !important; worked for me

ListBox vs. ListView - how to choose for data binding

A ListView is a specialized ListBox (that is, it inherits from ListBox). It allows you to specify different views rather than a straight list. You can either roll your own view, or use GridView (think explorer-like "details view"). It's basically the multi-column listbox, the cousin of windows form's listview.

If you don't need the additional capabilities of ListView, you can certainly use ListBox if you're simply showing a list of items (Even if the template is complex).

Draw an X in CSS

This is an adaptable version of the amazing solution provided by @Gildas.Tambo elsewhere in this page. Simply change the values of the variables at the top to change the size of the "X".

Credit for the solution itself goes to Gildas. All I've done is given it adaptable math.

_x000D_
_x000D_
:root {
  /* Width and height of the box containing the "X" */
  --BUTTON_W:             40px;
  /* This is the length of either of the 2 lines which form the "X", as a
  percentage of the width of the button. */
  --CLOSE_X_W:            95%;
  /* Thickness of the lines of the "X" */
  --CLOSE_X_THICKNESS:    4px;
}
  

body{
    background:blue;
}

div{
    width:           var(--BUTTON_W);
    height:          var(--BUTTON_W);
    background-color:red;
    position:        relative;
    border-radius:   6px;
    box-shadow:      2px 2px 4px 0 white;
}

/* The "X" in the button. "before" and "after" each represent one of the two lines of the "X" */
div:before,div:after{
    content:         '';
    position:        absolute;
    width:           var(--CLOSE_X_W);
    height:          var(--CLOSE_X_THICKNESS);
    background-color:white;
    border-radius:   2px;
    top:             calc(50% - var(--CLOSE_X_THICKNESS) / 2);
    box-shadow:      0 0 2px 0 #ccc;
}
/* One line of the "X" */
div:before{
    -webkit-transform:rotate(45deg);
    -moz-transform:   rotate(45deg);
    transform:        rotate(45deg);
    left:             calc((100% - var(--CLOSE_X_W)) / 2);
}
/* The other line of the "X" */
div:after{
    -webkit-transform:rotate(-45deg);
    -moz-transform:   rotate(-45deg);
    transform:        rotate(-45deg);
    right:            calc((100% - var(--CLOSE_X_W)) / 2);
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

How to write data to a JSON file using Javascript

You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

Printing the last column of a line in a file

One way using awk:

tail -f file.txt | awk '/A1/ { print $NF }'

System.BadImageFormatException: Could not load file or assembly

I had the same exception installing using correct framework.

My solution was running cmd as administrator .... then it worked fine.

When should I use GC.SuppressFinalize()?

SuppressFinalize should only be called by a class that has a finalizer. It's informing the Garbage Collector (GC) that this object was cleaned up fully.

The recommended IDisposable pattern when you have a finalizer is:

public class MyClass : IDisposable
{
    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
        if (!disposed)
        {
            if (disposing)
            {
                // called via myClass.Dispose(). 
                // OK to use any private object references
            }
            // Release unmanaged resources.
            // Set large fields to null.                
            disposed = true;
        }
    }

    public void Dispose() // Implement IDisposable
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~MyClass() // the finalizer
    {
        Dispose(false);
    }
}

Normally, the CLR keeps tabs on objects with a finalizer when they are created (making them more expensive to create). SuppressFinalize tells the GC that the object was cleaned up properly and doesn't need to go onto the finalizer queue. It looks like a C++ destructor, but doesn't act anything like one.

The SuppressFinalize optimization is not trivial, as your objects can live a long time waiting on the finalizer queue. Don't be tempted to call SuppressFinalize on other objects mind you. That's a serious defect waiting to happen.

Design guidelines inform us that a finalizer isn't necessary if your object implements IDisposable, but if you have a finalizer you should implement IDisposable to allow deterministic cleanup of your class.

Most of the time you should be able to get away with IDisposable to clean up resources. You should only need a finalizer when your object holds onto unmanaged resources and you need to guarantee those resources are cleaned up.

Note: Sometimes coders will add a finalizer to debug builds of their own IDisposable classes in order to test that code has disposed their IDisposable object properly.

public void Dispose() // Implement IDisposable
{
    Dispose(true);
#if DEBUG
    GC.SuppressFinalize(this);
#endif
}

#if DEBUG
~MyClass() // the finalizer
{
    Dispose(false);
}
#endif

use mysql SUM() in a WHERE clause

You can only use aggregates for comparison in the HAVING clause:

GROUP BY ...
  HAVING SUM(cash) > 500

The HAVING clause requires you to define a GROUP BY clause.

To get the first row where the sum of all the previous cash is greater than a certain value, use:

SELECT y.id, y.cash
  FROM (SELECT t.id,
               t.cash,
               (SELECT SUM(x.cash)
                  FROM TABLE x
                 WHERE x.id <= t.id) AS running_total
         FROM TABLE t
     ORDER BY t.id) y
 WHERE y.running_total > 500
ORDER BY y.id
   LIMIT 1

Because the aggregate function occurs in a subquery, the column alias for it can be referenced in the WHERE clause.

MySQL: Insert record if not exists in table

To overcome a similar problem, I have modified the table to have a unique column. Using your example, on creation I would have something like:

name VARCHAR(20),
UNIQUE (name)

and then use the following query when inserting into it:

INSERT IGNORE INTO train
set table_listnames='Rupert'

Edit and Continue: "Changes are not allowed when..."

I had the same problem. I even re-installed VS 2008 but the problem did not go away. However, when I deleted all the break points then it started to work.

Debug->Delete All Breakpoints

I think it was happening because I had deleted an aspx page that had break points in its code, and then I created another page with the same name. This probably confused the VS 2008.

Execution time of C program

ANSI C only specifies second precision time functions. However, if you are running in a POSIX environment you can use the gettimeofday() function that provides microseconds resolution of time passed since the UNIX Epoch.

As a side note, I wouldn't recommend using clock() since it is badly implemented on many(if not all?) systems and not accurate, besides the fact that it only refers to how long your program has spent on the CPU and not the total lifetime of the program, which according to your question is what I assume you would like to measure.

moving changed files to another branch for check-in

Sadly this happens to me quite regularly as well and I use git stash if I realized my mistake before git commit and use git cherry-pick otherwise, both commands are explained pretty well in other answers

I want to add a clarification for git checkout targetBranch: this command will only preserve your working directory and staged snapshot if targetBranch has the same history as your current branch

If you haven't already committed your changes, just use git checkout to move to the new branch and then commit them normally

@Amber's statement is not false, when you move to a newBranch,git checkout -b newBranch, a new pointer is created and it is pointing to the exact same commit as your current branch.
In fact, if you happened to have an another branch that shares history with your current branch (both point at the same commit) you can "move your changes" by git checkout targetBranch

However, usually different branches means different history, and Git will not allow you to switch between these branches with a dirty working directory or staging area. in which case you can either do git checkout -f targetBranch (clean and throwaway changes) or git stage + git checkout targetBranch (clean and save changes), simply running git checkout targetBranch will give an error:

error: Your local changes to the following files would be overwritten by checkout: ... Please commit your changes or stash them before you switch branches. Aborting

Run Stored Procedure in SQL Developer?

var out_para_name refcursor; 
execute package_name.procedure_name(inpu_para_val1,input_para_val2,... ,:out_para_name);
print :out_para_name;

How to retrieve available RAM from Windows command line?

Just in case you need this functionality in a Java program, you might want to look at the sigar API: http://www.hyperic.com/products/sigar

Actually, this is no answer to the question, I know, but a hint so you don't have to reinvent the wheel.

Android studio - Failed to find target android-18

You can solve the problem changing the compileSdkVersion in the Grandle.build file from 18 to wtever SDK is installed ..... BUTTTTT

  1. If you are trying to goin back in SDK versions like 18 to 17 ,You can not use the feature available in 18 or 18+

  2. If you are migrating your project (Eclipse to Android Studio ) Then off course you Don't have build.gradle file in your Existed Eclipse project

So, the only solution is to ensure the SDK version installed or not, you are targeting to , If not then install.

Error:Cause: failed to find target with hash string 'android-19' in: C:\Users\setia\AppData\Local\Android\sdk

How can I recover the return value of a function passed to multiprocessing.Process?

For some reason, I couldn't find a general example of how to do this with Queue anywhere (even Python's doc examples don't spawn multiple processes), so here's what I got working after like 10 tries:

def add_helper(queue, arg1, arg2): # the func called in child processes
    ret = arg1 + arg2
    queue.put(ret)

def multi_add(): # spawns child processes
    q = Queue()
    processes = []
    rets = []
    for _ in range(0, 100):
        p = Process(target=add_helper, args=(q, 1, 2))
        processes.append(p)
        p.start()
    for p in processes:
        ret = q.get() # will block
        rets.append(ret)
    for p in processes:
        p.join()
    return rets

Queue is a blocking, thread-safe queue that you can use to store the return values from the child processes. So you have to pass the queue to each process. Something less obvious here is that you have to get() from the queue before you join the Processes or else the queue fills up and blocks everything.

Update for those who are object-oriented (tested in Python 3.4):

from multiprocessing import Process, Queue

class Multiprocessor():

    def __init__(self):
        self.processes = []
        self.queue = Queue()

    @staticmethod
    def _wrapper(func, queue, args, kwargs):
        ret = func(*args, **kwargs)
        queue.put(ret)

    def run(self, func, *args, **kwargs):
        args2 = [func, self.queue, args, kwargs]
        p = Process(target=self._wrapper, args=args2)
        self.processes.append(p)
        p.start()

    def wait(self):
        rets = []
        for p in self.processes:
            ret = self.queue.get()
            rets.append(ret)
        for p in self.processes:
            p.join()
        return rets

# tester
if __name__ == "__main__":
    mp = Multiprocessor()
    num_proc = 64
    for _ in range(num_proc): # queue up multiple tasks running `sum`
        mp.run(sum, [1, 2, 3, 4, 5])
    ret = mp.wait() # get all results
    print(ret)
    assert len(ret) == num_proc and all(r == 15 for r in ret)

AppSettings get value from .config file

The answer that dtsg gave works:

string filePath = ConfigurationManager.AppSettings["ClientsFilePath"];

BUT, you need to add an assembly reference to

System.Configuration

Go to your Solution Explorer and right click on References and select Add reference. Select the Assemblies tab and search for Configuration.

Reference manager

Here is an example of my App.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <appSettings>
    <add key="AdminName" value="My Name"/>
    <add key="AdminEMail" value="MyEMailAddress"/>
  </appSettings>
</configuration>

Which you can get in the following way:

string adminName = ConfigurationManager.AppSettings["AdminName"];

How do I get interactive plots again in Spyder/IPython/matplotlib?

This is actually pretty easy to fix and doesn't take any coding:

1.Click on the Plots tab above the console. 2.Then at the top right corner of the plots screen click on the options button. 3.Lastly uncheck the "Mute inline plotting" button

Now re-run your script and your graphs should show up in the console.

Cheers.

Docker is installed but Docker Compose is not ? why?

I'm installing on a Raspberry Pi 3, with Raspbian 8. The curl method failed for me (got a line 1: Not: command not found error upon asking for docker-compose --version) and the solution of @sunapi386 seemed a little out-dated, so I tried this which worked:

First clean things up from previous efforts:

sudo rm /usr/local/bin/docker-compose
sudo pip uninstall docker-compose

Then follow this guidance re docker-compose on Rpi:

sudo apt-get -y install python-pip
sudo pip install docker-compose

For me (on 1 Nov 2017) this results in the following response to docker-compose --version:

docker-compose version 1.16.1, build 6d1ac219

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

clear() will go through the underlying Array and set each entry to null;

removeAll(collection) will go through the ArrayList checking for collection and remove(Object) it if it exists.

I would imagine that clear() is way faster then removeAll because it's not comparing, etc.

How to get the text of the selected value of a dropdown list?

$("#select_id").find("option:selected").text();

It is helpful if your control is on Server side. In .NET it looks like:

$('#<%= dropdownID.ClientID %>').find("option:selected").text();

Array initializing in Scala

scala> val arr = Array("Hello","World")
arr: Array[java.lang.String] = Array(Hello, World)

Open directory dialog

The best way to achieve what you want is to create your own wpf based control , or use a one that was made by other people
why ? because there will be a noticeable performance impact when using the winforms dialog in a wpf application (for some reason)
i recommend this project
https://opendialog.codeplex.com/
or Nuget :

PM> Install-Package OpenDialog

it's very MVVM friendly and it isn't wraping the winforms dialog

Android ADB commands to get the device properties

adb shell getprop ro.build.version.sdk

If you want to see the whole list of parameters just type:

adb shell getprop

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

What does "\r" do in the following script?

Actually, this has nothing to do with the usual Windows / Unix \r\n vs \n issue. The TELNET procotol itself defines \r\n as the end-of-line sequence, independently of the operating system. See RFC854.

How to open an Excel file in C#?

You need to have installed Microsoft Visual Studio Tools for Office (VSTO).

VSTO can be selected in the Visual Studio installer under Workloads > Web & Cloud > Office/SharePoint Development.

After that create common .NET project and add the reference to Microsoft.Office.Interop.Excel via 'Add Reference... > Assemblies' dialog.

Application excel = new Application();
Workbook wb = excel.Workbooks.Open(path);

Missing.Value is a special reflection struct for unnecessary parameters replacement


In newer versions, the assembly reference required is called Microsoft Excel 16.0 Object Library. If you do not have the latest version installed you might have Microsoft Excel 15.0 Object Library, or an older version, but it is the same process to include.

enter image description here

How can I truncate a double to only two decimal places in Java?

If you want that for display purposes, use java.text.DecimalFormat:

 new DecimalFormat("#.##").format(dblVar);

If you need it for calculations, use java.lang.Math:

 Math.floor(value * 100) / 100;

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Update for mid 2016:

The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!

Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!

Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!

Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot

  • Webpack
  • NPM as a build tool (no Gulp, Grunt or Bower)
  • React with Redux
  • ESLint
  • the list is long. Go and explore!

Your questions:

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

  • Everything belongs in package.json now

  • Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev (--save-dev updates your package.json by adding an entry to devDependencies)

  • Dependencies required for your application during runtime are in "dependencies" i.e. npm install lodash --save (--save updates your package.json by adding an entry to dependencies)

If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?

Always. Just because of comfort. When you add a flag (--save-dev or --save) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name is npm i -D package-name and shortcut for npm install --save package-name is npm i -S package-name

How to determine if one array contains all elements of another array

If there are are no duplicate elements or you don't care about them, then you can use the Set class:

a1 = Set.new [5, 1, 6, 14, 2, 8]
a2 = Set.new [2, 6, 15]
a1.subset?(a2)
=> false

Behind the scenes this uses

all? { |o| set.include?(o) }

How to unapply a migration in ASP.NET Core with EF Core

In general if you are using the Package Manager Console the right way to remove a specific Migration is by referencing the name of the migration

Update-Database -Migration {Name of Migration} -Context {context}

Another way to remove the last migration you have applied according to the docs is by using the command:

dotnet ef migrations remove

This command should be executed from the developer command prompt (how to open command prompt) inside your solution directory.

For example if your application is inside name "Application" and is in the folder c:\Projects. Then your path should be:

C:\Projects\Application

How to set JAVA_HOME in Mac permanently?

To set your Java path on mac:

  1. Open terminal on mac, change path to the root cd ~
  2. vi .bash_profile (This opens the bash_profile file)
  3. Click I to insert text and use the following text to set JAVA_HOME and PATH

    • export JAVA_HOME='/Library/Java/JavaVirtualMachines/jdk1.8.0_181.jdk/Contents/Home'
    • export PATH=$JAVA_HOME/bin:$PATH

      1. Type :wq to save and exit the file.
      2. Type source .bash_profile to execute the .bash_profile file.
      3. You can type echo $JAVA_HOME or echo $PATH

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

As in Swift 3.x for upload image with parameter we can use below alamofire upload method-

static func uploadImageData(inputUrl:String,parameters:[String:Any],imageName: String,imageFile : UIImage,completion:@escaping(_:Any)->Void) {

        let imageData = UIImageJPEGRepresentation(imageFile , 0.5)

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(imageData!, withName: imageName, fileName: "swift_file\(arc4random_uniform(100)).jpeg", mimeType: "image/jpeg")

            for key in parameters.keys{
                let name = String(key)
                if let val = parameters[name!] as? String{
                    multipartFormData.append(val.data(using: .utf8)!, withName: name!)
                }
            }
        }, to:inputUrl)
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (Progress) in
                })

                upload.responseJSON { response in

                    if let JSON = response.result.value {
                        completion(JSON)
                    }else{
                        completion(nilValue)
                    }
                }

            case .failure(let encodingError):
                completion(nilValue)
            }

        }

    }

Note: Additionally if our parameter is array of key-pairs then we can use

 var arrayOfKeyPairs = [[String:Any]]()
 let json = try? JSONSerialization.data(withJSONObject: arrayOfKeyPairs, options: [.prettyPrinted])
 let jsonPresentation = String(data: json!, encoding: .utf8)

How to create a secure random AES key in Java?

Using KeyGenerator would be the preferred method. As Duncan indicated, I would certainly give the key size during initialization. KeyFactory is a method that should be used for pre-existing keys.

OK, so lets get to the nitty-gritty of this. In principle AES keys can have any value. There are no "weak keys" as in (3)DES. Nor are there any bits that have a specific meaning as in (3)DES parity bits. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec around it.

But there are still advantages to the method you are using: the KeyGenerator is specifically created to generate keys. This means that the code may be optimized for this generation. This could have efficiency and security benefits. It might be programmed to avoid a timing side channel attacks that would expose the key, for instance. Note that it may already be a good idea to clear any byte[] that hold key information as they may be leaked into a swap file (this may be the case anyway though).

Furthermore, as said, not all algorithms are using fully random keys. So using KeyGenerator would make it easier to switch to other algorithms. More modern ciphers will only accept fully random keys though; this is seen as a major benefit over e.g. DES.

Finally, and in my case the most important reason, it that the KeyGenerator method is the only valid way of handling AES keys within a secure token (smart card, TPM, USB token or HSM). If you create the byte[] with the SecretKeySpec then the key must come from memory. That means that the key may be put in the secure token, but that the key is exposed in memory regardless. Normally, secure tokens only work with keys that are either generated in the secure token or are injected by e.g. a smart card or a key ceremony. A KeyGenerator can be supplied with a provider so that the key is directly generated within the secure token.

As indicated in Duncan's answer: always specify the key size (and any other parameters) explicitly. Do not rely on provider defaults as this will make it unclear what your application is doing, and each provider may have its own defaults.

Import functions from another js file. Javascript

The following works for me in Firefox and Chrome. In Firefox it even works from file:///

models/course.js

export function Course() {
    this.id = '';
    this.name = '';
};

models/student.js

import { Course } from './course.js';

export function Student() {
    this.firstName = '';
    this.lastName = '';
    this.course = new Course();
};

index.html

<div id="myDiv">
</div>
<script type="module">
    import { Student } from './models/student.js';

    window.onload = function () {
        var x = new Student();
        x.course.id = 1;
        document.getElementById('myDiv').innerHTML = x.course.id;
    }
</script>

Adding click event handler to iframe

You can use closures to pass parameters:

iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);

However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):

document.getElementById("myFrame").contentDocument.addEventListener(...);

How to Alter a table for Identity Specification is identity SQL Server

You can't alter the existing columns for identity.

You have 2 options,

Create a new table with identity & drop the existing table

Create a new column with identity & drop the existing column

Approach 1. (New table) Here you can retain the existing data values on the newly created identity column.

CREATE TABLE dbo.Tmp_Names
    (
      Id int NOT NULL
             IDENTITY(1, 1),
      Name varchar(50) NULL
    )
ON  [PRIMARY]
go

SET IDENTITY_INSERT dbo.Tmp_Names ON
go

IF EXISTS ( SELECT  *
            FROM    dbo.Names ) 
    INSERT  INTO dbo.Tmp_Names ( Id, Name )
            SELECT  Id,
                    Name
            FROM    dbo.Names TABLOCKX
go

SET IDENTITY_INSERT dbo.Tmp_Names OFF
go

DROP TABLE dbo.Names
go

Exec sp_rename 'Tmp_Names', 'Names'

Approach 2 (New column) You can’t retain the existing data values on the newly created identity column, The identity column will hold the sequence of number.

Alter Table Names
Add Id_new Int Identity(1, 1)
Go

Alter Table Names Drop Column ID
Go

Exec sp_rename 'Names.Id_new', 'ID', 'Column'

See the following Microsoft SQL Server Forum post for more details:

http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/04d69ee6-d4f5-4f8f-a115-d89f7bcbc032

Why can't I inherit static classes?

You can do something that will look like static inheritance.

Here is the trick:

public abstract class StaticBase<TSuccessor>
    where TSuccessor : StaticBase<TSuccessor>, new()
{
    protected static readonly TSuccessor Instance = new TSuccessor();
}

Then you can do this:

public class Base : StaticBase<Base>
{
    public Base()
    {
    }

    public void MethodA()
    {
    }
}

public class Inherited : Base
{
    private Inherited()
    {
    }

    public new static void MethodA()
    {
        Instance.MethodA();
    }
}

The Inherited class is not static itself, but we don't allow to create it. It actually has inherited static constructor which builds Base, and all properties and methods of Base available as static. Now the only thing left to do make static wrappers for each method and property you need to expose to your static context.

There are downsides like the need for manual creation of static wrapper methods and new keyword. But this approach helps support something that is really similar to static inheritance.

P.S. We used this for creating compiled queries, and this actually can be replaced with ConcurrentDictionary, but a static read-only field with its thread safety was good enough.

The name 'controlname' does not exist in the current context

exclude any other pages that reference the same code-behind file, for example an older page that you copied and pasted.

How to delete an object by id with entity framework

dwkd's answer mostly worked for me in Entity Framework core, except when I saw this exception:

InvalidOperationException: The instance of entity type 'Customer' cannot be tracked because another instance with the same key value for {'Id'} is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached. Consider using 'DbContextOptionsBuilder.EnableSensitiveDataLogging' to see the conflicting key values.

To avoid the exception, I updated the code:

Customer customer = context.Customers.Local.First(c => c.Id == id);
if (customer == null) {
    customer = new Customer () { Id = id };
    context.Customers.Attach(customer);
}
context.Customers.Remove(customer);
context.SaveChanges();

Python's time.clock() vs. time.time() accuracy?

As of 3.3, time.clock() is deprecated, and it's suggested to use time.process_time() or time.perf_counter() instead.

Previously in 2.7, according to the time module docs:

time.clock()

On Unix, return the current processor time as a floating point number expressed in seconds. The precision, and in fact the very definition of the meaning of “processor time”, depends on that of the C function of the same name, but in any case, this is the function to use for benchmarking Python or timing algorithms.

On Windows, this function returns wall-clock seconds elapsed since the first call to this function, as a floating point number, based on the Win32 function QueryPerformanceCounter(). The resolution is typically better than one microsecond.

Additionally, there is the timeit module for benchmarking code snippets.

Python virtualenv questions

on Windows I have python 3.7 installed and I still couldn't activate virtualenv from Gitbash with ./Scripts/activate although it worked from Powershell after running Set-ExecutionPolicy Unrestricted in Powershell and changing the setting to "Yes To All".

I don't like Powershell and I like to use Gitbash, so to activate virtualenv in Gitbash first navigate to your project folder, use ls to list the contents of the folder and be sure you see "Scripts". Change directory to "Scripts" using cd Scripts, once you're in the "Scripts" path use . activate to activate virtualenv. Don't forget the space after the dot.

How to get the bluetooth devices as a list?

I tried the below code,

main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
<TextView 
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />
<Button
    android:id="@+id/listpaireddevices" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"
    android:text="List Paired Devices" 
    android:enabled="false"
    /> 
<TextView
    android:id="@+id/bluetoothstate" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    />

ListPairedDevicesActivity.java

import java.util.Set;

import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class ListPairedDevicesActivity extends ListActivity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

  ArrayAdapter<String> btArrayAdapter 
    = new ArrayAdapter<String>(this,
             android.R.layout.simple_list_item_1);

  BluetoothAdapter bluetoothAdapter 
   = BluetoothAdapter.getDefaultAdapter();
  Set<BluetoothDevice> pairedDevices 
   = bluetoothAdapter.getBondedDevices();

  if (pairedDevices.size() > 0) {
      for (BluetoothDevice device : pairedDevices) {
       String deviceBTName = device.getName();
       String deviceBTMajorClass 
        = getBTMajorDeviceClass(device
          .getBluetoothClass()
          .getMajorDeviceClass());
       btArrayAdapter.add(deviceBTName + "\n" 
         + deviceBTMajorClass);
      }
  }
  setListAdapter(btArrayAdapter);

 }

 private String getBTMajorDeviceClass(int major){
  switch(major){ 
  case BluetoothClass.Device.Major.AUDIO_VIDEO:
   return "AUDIO_VIDEO";
  case BluetoothClass.Device.Major.COMPUTER:
   return "COMPUTER";
  case BluetoothClass.Device.Major.HEALTH:
   return "HEALTH";
  case BluetoothClass.Device.Major.IMAGING:
   return "IMAGING"; 
  case BluetoothClass.Device.Major.MISC:
   return "MISC";
  case BluetoothClass.Device.Major.NETWORKING:
   return "NETWORKING"; 
  case BluetoothClass.Device.Major.PERIPHERAL:
   return "PERIPHERAL";
  case BluetoothClass.Device.Major.PHONE:
   return "PHONE";
  case BluetoothClass.Device.Major.TOY:
   return "TOY";
  case BluetoothClass.Device.Major.UNCATEGORIZED:
   return "UNCATEGORIZED";
  case BluetoothClass.Device.Major.WEARABLE:
   return "AUDIO_VIDEO";
  default: return "unknown!";
  }
 }

 @Override
 protected void onListItemClick(ListView l, View v, int position, long id) {
  // TODO Auto-generated method stub
  super.onListItemClick(l, v, position, id);

     Intent intent = new Intent();
     setResult(RESULT_OK, intent);
     finish();
 }

}

AndroidBluetooth.java

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AndroidBluetooth extends Activity {

 private static final int REQUEST_ENABLE_BT = 1;
 private static final int REQUEST_PAIRED_DEVICE = 2;

    /** Called when the activity is first created. */
 Button btnListPairedDevices;
 TextView stateBluetooth;
 BluetoothAdapter bluetoothAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        btnListPairedDevices = (Button)findViewById(R.id.listpaireddevices);

        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        CheckBlueToothState();

        btnListPairedDevices.setOnClickListener(btnListPairedDevicesOnClickListener);
    }

    private void CheckBlueToothState(){
     if (bluetoothAdapter == null){
         stateBluetooth.setText("Bluetooth NOT support");
        }else{
         if (bluetoothAdapter.isEnabled()){
          if(bluetoothAdapter.isDiscovering()){
           stateBluetooth.setText("Bluetooth is currently in device discovery process.");
          }else{
           stateBluetooth.setText("Bluetooth is Enabled.");
           btnListPairedDevices.setEnabled(true);
          }
         }else{
          stateBluetooth.setText("Bluetooth is NOT Enabled!");
          Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
             startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
         }
        }
    }

    private Button.OnClickListener btnListPairedDevicesOnClickListener
    = new Button.OnClickListener(){

  @Override
  public void onClick(View arg0) {
   // TODO Auto-generated method stub
   Intent intent = new Intent();
   intent.setClass(AndroidBluetooth.this, ListPairedDevicesActivity.class);
   startActivityForResult(intent, REQUEST_PAIRED_DEVICE); 
  }};

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
  // TODO Auto-generated method stub
  if(requestCode == REQUEST_ENABLE_BT){
   CheckBlueToothState();
  }if (requestCode == REQUEST_PAIRED_DEVICE){
   if(resultCode == RESULT_OK){

   }
  } 
 }   
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.test.AndroidBluetooth"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="7" />
    <uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AndroidBluetooth"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
  <activity android:name=".ListPairedDevicesActivity" 
      android:label="AndroidBluetooth: List of Paired Devices"/>
    </application>
</manifest>

Getting a list item by index

.NET List data structure is an Array in a "mutable shell".

So you can use indexes for accessing to it's elements like:

var firstElement = myList[0];
var secondElement = myList[1];

Starting with C# 8.0 you can use Index and Range classes for accessing elements. They provides accessing from the end of sequence or just access a specific part of sequence:

var lastElement = myList[^1]; // Using Index
var fiveElements = myList[2..7]; // Using Range, note that 7 is exclusive

You can combine indexes and ranges together:

var elementsFromThirdToEnd = myList[2..^0]; // Index and Range together

Also you can use LINQ ElementAt method but for 99% of cases this is really not necessary and just slow performance solution.

Efficient way to rotate a list in python

Jon Bentley in Programming Pearls (Column 2) describes an elegant and efficient algorithm for rotating an n-element vector x left by i positions:

Let's view the problem as transforming the array ab into the array ba, but let's also assume that we have a function that reverses the elements in a specified portion of the array. Starting with ab, we reverse a to get arb, reverse b to get arbr, and then reverse the whole thing to get (arbr)r, which is exactly ba. This results in the following code for rotation:

reverse(0, i-1)
reverse(i, n-1)
reverse(0, n-1)

This can be translated to Python as follows:

def rotate(x, i):
    i %= len(x)
    x[:i] = reversed(x[:i])
    x[i:] = reversed(x[i:])
    x[:] = reversed(x)
    return x

Demo:

>>> def rotate(x, i):
...     i %= len(x)
...     x[:i] = reversed(x[:i])
...     x[i:] = reversed(x[i:])
...     x[:] = reversed(x)
...     return x
... 
>>> rotate(list('abcdefgh'), 1)
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'a']
>>> rotate(list('abcdefgh'), 3)
['d', 'e', 'f', 'g', 'h', 'a', 'b', 'c']
>>> rotate(list('abcdefgh'), 8)
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']
>>> rotate(list('abcdefgh'), 9)
['b', 'c', 'd', 'e', 'f', 'g', 'h', 'a']

Laravel form html with PUT method for PUT routes

You CAN add css clases, and any type of attributes you need to blade template, try this:

{{ Form::open(array('url' => '/', 'method' => 'PUT', 'class'=>'col-md-12')) }}
.... wathever code here
{{ Form::close() }}

If you dont want to go the blade way you can add a hidden input. This is the form Laravel does, any way:

Note: Since HTML forms only support POST and GET, PUT and DELETE methods will be spoofed by automatically adding a _method hidden field to your form. (Laravel docs)

<form class="col-md-12" action="<?php echo URL::to('/');?>/post/<?=$post->postID?>" method="POST">

    <!-- Rendered blade HTML form use this hidden. Dont forget to put the form method to POST -->

    <input name="_method" type="hidden" value="PUT">

    <div class="form-group">
        <textarea type="text" class="form-control input-lg" placeholder="Text Here" name="post"><?=$post->post?></textarea>
    </div>

    <div class="form-group">
        <button class="btn btn-primary btn-lg btn-block" type="submit" value="Edit">Edit</button>
    </div>
</form>

Function for Factorial in Python

For performance reasons, please do not use recursion. It would be disastrous.

def fact(n, total=1):
    while True:
        if n == 1:
            return total
        n, total = n - 1, total * n

Check running results

cProfile.run('fact(126000)')

4 function calls in 5.164 seconds

Using the stack is convenient(like recursive call), but it comes at a cost: storing detailed information can take up a lot of memory.

If the stack is high, it means that the computer stores a lot of information about function calls.

The method only takes up constant memory(like iteration).

Or Using for loop

def fact(n):
    result = 1
    for i in range(2, n + 1):
        result *= i
    return result

Check running results

cProfile.run('fact(126000)')

4 function calls in 4.708 seconds

Or Using builtin function math

def fact(n):
    return math.factorial(n)

Check running results

cProfile.run('fact(126000)')

5 function calls in 0.272 seconds

How to show an alert box in PHP?

use this code

echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';

The problem was:

  1. you missed "
  2. It should be alert not alery

Open local folder from link

Local Explorer - File Manager on web browser extention can solve for chrome

but still some encoding problems

Why does Node.js' fs.readFile() return a buffer instead of string?

Try:

    fs.readFile("test.txt", "utf8", function(err, data) {...});

Basically, you need to specify the encoding.

Get number of digits with JavaScript

Here's a mathematical answer (also works for negative numbers):

function numDigits(x) {
  return Math.max(Math.floor(Math.log10(Math.abs(x))), 0) + 1;
}

And an optimized version of the above (more efficient bitwise operations):

function numDigits(x) {
  return (Math.log10((x ^ (x >> 31)) - (x >> 31)) | 0) + 1;
}

Essentially, we start by getting the absolute value of the input to allow negatives values to work correctly. Then we run the through the log10 operation to give us what power of 10 the input is (if you were working in another base, you would use the logarithm for that base), which is the number of digits. Then we floor the output to only grab the integer part of that. Finally, we use the max function to fix decimal values (any fractional value between 0 and 1 just returns 1, instead of a negative number), and add 1 to the final output to get the count.

The above assumes (based on your example input) that you wish to count the number of digits in integers (so 12345 = 5, and thus 12345.678 = 5 as well). If you would like to count the total number of digits in the value (so 12345.678 = 8), then add this before the 'return' in either function above:

x = Number(String(x).replace(/[^0-9]/g, ''));

Java 32-bit vs 64-bit compatibility

Yes, Java bytecode (and source code) is platform independent, assuming you use platform independent libraries. 32 vs. 64 bit shouldn't matter.

DateTime.Today.ToString("dd/mm/yyyy") returns invalid DateTime Value

There are only minor error.Use MM instead of mm ,so it will be effective write as below:

 @DateTime.Now.ToString("dd/MM/yyy")

String replace method is not replacing characters

Strings are immutable, meaning their contents cannot change. When you call replace(this,that) you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that) or a new reference as seen below:

public class Test{

    public static void main(String[] args) {

        String sentence = "Define, Measure, Analyze, Design and Verify";

        String replaced = sentence.replace("and", "");
        System.out.println(replaced);

    }
}

As an aside, note that I've removed the contains() check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.

When can I use a forward declaration?

As well as pointers and references to incomplete types, you can also declare function prototypes that specify parameters and/or return values that are incomplete types. However, you cannot define a function having a parameter or return type that is incomplete, unless it is a pointer or reference.

Examples:

struct X;              // Forward declaration of X

void f1(X* px) {}      // Legal: can always use a pointer
void f2(X&  x) {}      // Legal: can always use a reference
X f3(int);             // Legal: return value in function prototype
void f4(X);            // Legal: parameter in function prototype
void f5(X) {}          // ILLEGAL: *definitions* require complete types

Display a table/list data dynamically in MVC3/Razor from a JsonResult?

The normal way of doing it is:

  • You get the users from the database in controller.
  • You send a collection of users to the View
  • In the view to loop the list of users building the list.

You don't need a JsonResult or jQuery for this.

Can I call a constructor from another constructor (do constructor chaining) in C++?

Would be more easy to test, than decide :) Try this:

#include <iostream>

class A {
public:
    A( int a) : m_a(a) {
        std::cout << "A::Ctor" << std::endl;    
    }
    ~A() {
        std::cout << "A::dtor" << std::endl;    
    }
public:
    int m_a;
};

class B : public A {
public:
    B( int a, int b) : m_b(b), A(a) {}
public:
    int m_b;
};

int main() {
    B b(9, 6);
    std::cout << "Test constructor delegation a = " << b.m_a << "; b = " << b.m_b << std::endl;    
    return 0;
}

and compile it with 98 std: g++ main.cpp -std=c++98 -o test_1

you will see:

A::Ctor
Test constructor delegation a = 9; b = 6
A::dtor

so :)

How can I split a shell command over multiple lines when using an IF statement?

The line-continuation will fail if you have whitespace (spaces or tab characters[1]) after the backslash and before the newline. With no such whitespace, your example works fine for me:

$ cat test.sh
if ! fab --fabfile=.deploy/fabfile.py \
   --forward-agent \
   --disable-known-hosts deploy:$target; then
     echo failed
else
     echo succeeded
fi

$ alias fab=true; . ./test.sh
succeeded
$ alias fab=false; . ./test.sh
failed

Some detail promoted from the comments: the line-continuation backslash in the shell is not really a special case; it is simply an instance of the general rule that a backslash "quotes" the immediately-following character, preventing any special treatment it would normally be subject to. In this case, the next character is a newline, and the special treatment being prevented is terminating the command. Normally, a quoted character winds up included literally in the command; a backslashed newline is instead deleted entirely. But otherwise, the mechanism is the same. Most importantly, the backslash only quotes the immediately-following character; if that character is a space or tab, you just get a literal space or tab, and any subsequent newline remains unquoted.

[1] or carriage returns, for that matter, as Czechnology points out. Bash does not get along with Windows-formatted text files, not even in WSL. Or Cygwin, but at least their Bash port has added a set -o igncr option that you can set to make it carriage-return-tolerant.

How do I get the full path to a Perl script that is executing?

Are you looking for this?:

my $thisfile = $1 if $0 =~
/\\([^\\]*)$|\/([^\/]*)$/;

print "You are running $thisfile
now.\n";

The output will look like this:

You are running MyFileName.pl now.

It works on both Windows and Unix.

Simplest two-way encryption using PHP

IMPORTANT this answer is valid only for PHP 5, in PHP 7 use built-in cryptographic functions.

Here is simple but secure enough implementation:

  • AES-256 encryption in CBC mode
  • PBKDF2 to create encryption key out of plain-text password
  • HMAC to authenticate the encrypted message.

Code and examples are here: https://stackoverflow.com/a/19445173/1387163

How eliminate the tab space in the column in SQL Server 2008

UPDATE Table SET Column = REPLACE(Column, char(9), '')

Decimal number regular expression, where digit after decimal is optional

/\d+\.?\d*/

One or more digits (\d+), optional period (\.?), zero or more digits (\d*).

Depending on your usage or regex engine you may need to add start/end line anchors:

/^\d+\.?\d*$/

Regular expression visualization

Debuggex Demo

Writing to a TextBox from another thread?

Have a look at Control.BeginInvoke method. The point is to never update UI controls from another thread. BeginInvoke will dispatch the call to the UI thread of the control (in your case, the Form).

To grab the form, remove the static modifier from the sample function and use this.BeginInvoke() as shown in the examples from MSDN.

How to get JSON from URL in JavaScript?

Define a function like:

fetchRestaurants(callback) {
    fetch(`http://www.restaurants.com`)
       .then(response => response.json())
       .then(json => callback(null, json.restaurants))
       .catch(error => callback(error, null))
}

Then use it like this:

fetchRestaurants((error, restaurants) => {
    if (error) 
        console.log(error)
    else 
        console.log(restaurants[0])

});

What is simplest way to read a file into String?

From Java 7 (API Description) onwards you can do:

new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8);

Where filePath is a String representing the file you want to load.

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

Standing on the shoulders of boxxar, I like this:

sed -n '<first line>,$p;<last line>q' input

e.g.

sed -n '16224,$p;16482q' input

The $ means "last line", so the first command makes sed print all lines starting with line 16224 and the second command makes sed quit after printing line 16428. (Adding 1 for the q-range in boxxar's solution does not seem to be necessary.)

I like this variant because I don't need to specify the ending line number twice. And I measured that using $ does not have detrimental effects on performance.

Passing a 2D array to a C++ function

A modification to shengy's first suggestion, you can use templates to make the function accept a multi-dimensional array variable (instead of storing an array of pointers that have to be managed and deleted):

template <size_t size_x, size_t size_y>
void func(double (&arr)[size_x][size_y])
{
    printf("%p\n", &arr);
}

int main()
{
    double a1[10][10];
    double a2[5][5];

    printf("%p\n%p\n\n", &a1, &a2);
    func(a1);
    func(a2);

    return 0;
}

The print statements are there to show that the arrays are getting passed by reference (by displaying the variables' addresses)

Can typescript export a function?

It's hard to tell what you're going for in that example. exports = is about exporting from external modules, but the code sample you linked is an internal module.

Rule of thumb: If you write module foo { ... }, you're writing an internal module; if you write export something something at top-level in a file, you're writing an external module. It's somewhat rare that you'd actually write export module foo at top-level (since then you'd be double-nesting the name), and it's even rarer that you'd write module foo in a file that had a top-level export (since foo would not be externally visible).

The following things make sense (each scenario delineated by a horizontal rule):


// An internal module named SayHi with an exported function 'foo'
module SayHi {
    export function foo() {
       console.log("Hi");
    }

    export class bar { }
}

// N.B. this line could be in another file that has a
// <reference> tag to the file that has 'module SayHi' in it
SayHi.foo();
var b = new SayHi.bar();

file1.ts

// This *file* is an external module because it has a top-level 'export'
export function foo() {
    console.log('hi');
}

export class bar { }

file2.ts

// This file is also an external module because it has an 'import' declaration
import f1 = module('file1');
f1.foo();
var b = new f1.bar();

file1.ts

// This will only work in 0.9.0+. This file is an external
// module because it has a top-level 'export'
function f() { }
function g() { }
export = { alpha: f, beta: g };

file2.ts

// This file is also an external module because it has an 'import' declaration
import f1 = require('file1');
f1.alpha(); // invokes f
f1.beta(); // invokes g

Excel VBA Run-time Error '32809' - Trying to Understand it

Ok, this might be weird. Anyway one of my colleagues had this error and we tried the edit VBA compile whatever. But the thing is, just copy the excel file to the desktop. And it worked. The Excel file was originally in a network drive. This worked, this is my answer to this issue.

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

set column width of a gridview in asp.net

There are two steps:

  1. You must set an appropriate width for GridView like this: Width="2000px".
  2. You can set width of Colum by setting [ItemStyle-Width] Like this: ItemStyle-Width="300px".

** You can set width by setting fixed Pixels like "150 px" or by percentage like"10%".

How to link to part of the same document in Markdown?

There is no such directive in the Markdown spec. Sorry.

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

Based on the current user's latitude, longitude and the distance you wants to find,the sql query is given below.

SELECT * FROM(
    SELECT *,(((acos(sin((@latitude*pi()/180)) * sin((Latitude*pi()/180))+cos((@latitude*pi()/180)) * cos((Latitude*pi()/180)) * cos(((@longitude - Longitude)*pi()/180))))*180/pi())*60*1.1515*1.609344) as distance FROM Distances) t
WHERE distance <= @distance

@latitude and @longitude are the latitude and longitude of the point. Latitude and longitude are the columns of distances table. Value of pi is 22/7

Blurry text after using CSS transform: scale(); in Chrome

In my case following code caused blurry font:

-webkit-transform: translate(-50%,-50%);
transform: translate(-50%,-50%);

and just adding zoom property fixed it for me. Play around with zoom, following worked for me:

zoom: 97%;   

Entity Framework Code First - two Foreign Keys from same table

It's also possible to specify the ForeignKey() attribute on the navigation property:

[ForeignKey("HomeTeamID")]
public virtual Team HomeTeam { get; set; }
[ForeignKey("GuestTeamID")]
public virtual Team GuestTeam { get; set; }

That way you don't need to add any code to the OnModelCreate method

How to replace url parameter with javascript/jquery?

In addition to @stenix, this worked perfectly to me

 url =  window.location.href;
    paramName = 'myparam';
        paramValue = $(this).val();
        var pattern = new RegExp('('+paramName+'=).*?(&|$)') 
        var newUrl = url.replace(pattern,'$1' + paramValue + '$2');
        var n=url.indexOf(paramName);
        alert(n)
        if(n == -1){
            newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue 
        }
        window.location.href = newUrl;

Here no need to save the "url" variable, just replace in current url

How to initialise a string from NSData in Swift

This is how you should initialize the NSString:

Swift 2.X or older

let datastring = NSString(data: fooData, encoding: NSUTF8StringEncoding)

Swift 3 or newer:

let datastring = NSString(data: fooData, encoding: String.Encoding.utf8.rawValue)

This doc explains the syntax.

Leaflet changing Marker color

In R, use the addAwesomeMarkers() function. Sample code producing red marker:

leaflet() %>%
addTiles() %>%
addAwesomeMarkers(lng = -77.03654, lat = 38.8973, icon = awesomeIcons(icon = 'ion-ionic', library = 'ion', markerColor = 'red'))

Link for ion icons: http://ionicons.com/

How do I check if a C++ std::string starts with a certain string, and convert a substring to an int?

Using STL this could look like:

std::string prefix = "--foo=";
std::string arg = argv[1];
if (prefix.size()<=arg.size() && std::equal(prefix.begin(), prefix.end(), arg.begin())) {
  std::istringstream iss(arg.substr(prefix.size()));
  iss >> foo_value;
}

How to activate a specific worksheet in Excel?

An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.

How to create a GUID in Excel?

ESP:

=CONCATENAR(
    DEC.A.HEX(ALEATORIO.ENTRE(0;4294967295);8);"-"; 
    DEC.A.HEX(ALEATORIO.ENTRE(0;42949);4);"-"; 
    DEC.A.HEX(ALEATORIO.ENTRE(0;42949);4);"-"; 
    DEC.A.HEX(ALEATORIO.ENTRE(0;42949);4);"-"; 
    DEC.A.HEX(ALEATORIO.ENTRE(0;4294967295);8); 
    DEC.A.HEX(ALEATORIO.ENTRE(0;42949);4)
)

Read Content from Files which are inside Zip file

Sample code you can use to let Tika take care of container files for you. http://wiki.apache.org/tika/RecursiveMetadata

Form what I can tell, the accepted solution will not work for cases where there are nested zip files. Tika, however will take care of such situations as well.

How to find specified name and its value in JSON-string from Java?

Gson allows for one of the simplest possible solutions. Compared to similar APIs like Jackson or svenson, Gson by default doesn't even need the unused JSON elements to have bindings available in the Java structure. Specific to the question asked, here's a working solution.

import com.google.gson.Gson;

public class Foo
{
  static String jsonInput = 
    "{" + 
      "\"name\":\"John\"," + 
      "\"age\":\"20\"," + 
      "\"address\":\"some address\"," + 
      "\"someobject\":" +
      "{" + 
        "\"field\":\"value\"" + 
      "}" + 
    "}";

  String age;

  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    Foo thing = gson.fromJson(jsonInput, Foo.class);
    if (thing.age != null)
    {
      System.out.println("age is " + thing.age);
    }
    else
    {
      System.out.println("age element not present or value is null");
    }
  }
}

Angular @ViewChild() error: Expected 2 arguments, but got 1

Regex for replacing all via IDEA (tested with Webstorm)

Find: \@ViewChild\('(.*)'\)

Replace: \@ViewChild\('$1', \{static: true\}\)

How do I create a ListView with rounded corners in Android?

Although that did work, it took out the entire background colour as well. I was looking for a way to do just the border and just replace that XML layout code with this one and I was good to go!

<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="4dp" android:color="#FF00FF00" />
    <padding android:left="7dp" android:top="7dp"
            android:right="7dp" android:bottom="7dp" />
    <corners android:radius="4dp" />
</shape> 

Bootstrap - dropdown menu not working?

I had a similar problem. The version of bootstrap.js that visual studio seems to be hosed. I just pointed to this URL instead:

    <link id="active_style" rel="stylesheet" href="//netdna.bootstrapcdn.com/bootswatch/3.1.1/cosmo/bootstrap.min.css">

For completeness, here's the HTML and javascript

<ul class="nav navbar-nav navbar-right">
                    <li id="theme_selector" class="dropdown">
                        <a href="#" class="dropdown-toggle" data-toggle="dropdown">Theme <b class="caret"></b></a>
                        <ul id="theme" class="dropdown-menu" role="menu">
                            <li><a href="#">Amelia</a></li>
                            <li><a href="#">Cerulean</a></li>
                            <li><a href="#">Cyborg</a></li>
                            <li><a href="#">Cosmo</a></li>
                            <li><a href="#">Darkly</a></li>
                            <li><a href="#">Flatly</a></li>
                            <li><a href="#">Lumen</a></li>
                            <li><a href="#">Simplex</a></li>
                            <li><a href="#">Slate</a></li>
                            <li><a href="#">Spacelab</a></li>
                            <li><a href="#">Superhero</a></li>
                            <li><a href="#">United</a></li>
                            <li><a href="#">Yeti</a></li>
                        </ul>
                    </li>
                </ul>

Javascript

$('#theme li').click(function () {
        //alert('item: ' + $(this).text());
        switch_style($(this).text());
    });

Hope it helps someone

Copy file from source directory to binary directory using CMake

The suggested configure_file is probably the easiest solution. However, it will not rerun the copy command to if you manually deleted the file from the build directory. To also handle this case, the following works for me:

add_custom_target(copy-test-makefile ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/input.txt)
add_custom_command(OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/input.txt
                   COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_CURRENT_SOURCE_DIR}/input.txt
                                                    ${CMAKE_CURRENT_BINARY_DIR}/input.txt
                   DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/input.txt)

Exception: There is already an open DataReader associated with this Connection which must be closed first

You are trying to to an Insert (with ExecuteNonQuery()) on a SQL connection that is used by this reader already:

while (myReader.Read())

Either read all the values in a list first, close the reader and then do the insert, or use a new SQL connection.

Can anybody tell me details about hs_err_pid.log file generated when Tomcat crashes?

A very very good document regarding this topic is Troubleshooting Guide for Java from (originally) Sun. See the chapter "Troubleshooting System Crashes" for information about hs_err_pid* Files.

See Appendix C - Fatal Error Log

Per the guide, by default the file will be created in the working directory of the process if possible, or in the system temporary directory otherwise. A specific location can be chosen by passing in the -XX:ErrorFile product flag. It says:

If the -XX:ErrorFile= file flag is not specified, the system attempts to create the file in the working directory of the process. In the event that the file cannot be created in the working directory (insufficient space, permission problem, or other issue), the file is created in the temporary directory for the operating system.

T-SQL get SELECTed value of stored procedure

there are three ways you can use: the RETURN value, and OUTPUT parameter and a result set

ALSO, watch out if you use the pattern: SELECT @Variable=column FROM table ...

if there are multiple rows returned from the query, your @Variable will only contain the value from the last row returned by the query.

RETURN VALUE
since your query returns an int field, at least based on how you named it. you can use this trick:

CREATE PROCEDURE GetMyInt
( @Param int)
AS
DECLARE @ReturnValue int

SELECT @ReturnValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN @ReturnValue
GO

and now call your procedure like:

DECLARE @SelectedValue int
       ,@Param         int
SET @Param=1
EXEC @SelectedValue = GetMyInt @Param
PRINT @SelectedValue

this will only work for INTs, because RETURN can only return a single int value and nulls are converted to a zero.

OUTPUT PARAMETER
you can use an output parameter:

CREATE PROCEDURE GetMyInt
( @Param     int
 ,@OutValue  int OUTPUT)
AS
SELECT @OutValue=MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO

and now call your procedure like:

DECLARE @SelectedValue int
       ,@Param         int
SET @Param=1
EXEC GetMyInt @Param, @SelectedValue OUTPUT
PRINT @SelectedValue 

Output parameters can only return one value, but can be any data type

RESULT SET for a result set make the procedure like:

CREATE PROCEDURE GetMyInt
( @Param     int)
AS
SELECT MyIntField FROM MyTable WHERE MyPrimaryKeyField = @Param
RETURN 0
GO

use it like:

DECLARE @ResultSet table (SelectedValue int)
DECLARE @Param int
SET @Param=1
INSERT INTO @ResultSet (SelectedValue)
    EXEC GetMyInt @Param
SELECT * FROM @ResultSet 

result sets can have many rows and many columns of any data type

How do I convert from stringstream to string in C++?

Use the .str()-method:

Manages the contents of the underlying string object.

1) Returns a copy of the underlying string as if by calling rdbuf()->str().

2) Replaces the contents of the underlying string as if by calling rdbuf()->str(new_str)...

Notes

The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling c_str() on the result of str() (for example in auto *ptr = out.str().c_str();) results in a dangling pointer...

Trying to include a library, but keep getting 'undefined reference to' messages

The trick here is to put the library AFTER the module you are compiling. The problem is a reference thing. The linker resolves references in order, so when the library is BEFORE the module being compiled, the linker gets confused and does not think that any of the functions in the library are needed. By putting the library AFTER the module, the references to the library in the module are resolved by the linker.

Why functional languages?

Most applications are simple enough to be solved in normal OO ways

  1. OO ways have not always been "normal." This decade's standard was last decade's marginalized concept.

  2. Functional programming is math. Paul Graham on Lisp (substitute functional programming for Lisp):

So the short explanation of why this 1950s language is not obsolete is that it was not technology but math, and math doesn’t get stale. The right thing to compare Lisp to is not 1950s hardware, but, say, the Quicksort algorithm, which was discovered in 1960 and is still the fastest general-purpose sort.

What is the difference between .NET Core and .NET Standard Class Library project types?

.NET and .NET Core are two different implementations of the .NET runtime. Both Core and Framework (but especially Framework) have different profiles that include larger or smaller (or just plain different) selections of the many APIs and assemblies Microsoft has created for .NET, depending on where they are installed and in what profile.

For example, there are some different APIs available in Universal Windows apps than in the "normal" Windows profile. Even on Windows, you might have the "Client" profile vs. the "Full" profile. Additionally, and there are other implementations (like Mono) that have their own sets of libraries.

.NET Standard is a specification for which sets of API libraries and assemblies must be available. An app written for .NET Standard 1.0 should be able to compile and run with any version of Framework, Core, Mono, etc., that advertises support for the .NET Standard 1.0 collection of libraries. Similar is true for .NET Standard 1.1, 1.5, 1.6, 2.0, etc. As long as the runtime provides support for the version of Standard targeted by your program, your program should run there.

A project targeted at a version of Standard will not be able to make use of features that are not included in that revision of the standard. This doesn't mean you can't take dependencies on other assemblies, or APIs published by other vendors (i.e.: items on NuGet). But it does mean that any dependencies you take must also include support for your version of .NET Standard. .NET Standard is evolving quickly, but it's still new enough, and cares enough about some of the smaller runtime profiles, that this limitation can feel stifling. (Note a year and a half later: this is starting to change, and recent .NET Standard versions are much nicer and more full-featured).

On the other hand, an app targeted at Standard should be able to be used in more deployment situations, since in theory it can run with Core, Framework, Mono, etc. For a class library project looking for wide distribution, that's an attractive promise. For a class library project used mainly for internal purposes, it may not be as much of a concern.

.NET Standard can also be useful in situations where the system administrator team is wanting to move from ASP.NET on Windows to ASP.NET for .NET Core on Linux for philosophical or cost reasons, but the Development team wants to continue working against .NET Framework in Visual Studio on Windows.

How to iterate a loop with index and element in Swift

We called enumerate function to implements this. like

    for (index, element) in array.enumerate() {
     index is indexposition of array
     element is element of array 
   }

Mercurial — revert back to old version and continue from there

hg update [-r REV]

If later you commit, you will effectively create a new branch. Then you might continue working only on this branch or eventually merge the existing one into it.

How can I get the MAC and the IP address of a connected client in PHP?

// Turn on output buffering  
ob_start();  

//Get the ipconfig details using system commond  
system('ipconfig /all');  

// Capture the output into a variable  
$mycomsys=ob_get_contents();  

// Clean (erase) the output buffer  
ob_clean();  

$find_mac = "Physical"; 
//find the "Physical" & Find the position of Physical text  

$pmac = strpos($mycomsys, $find_mac);  
// Get Physical Address  

$macaddress=substr($mycomsys,($pmac+36),17);  
//Display Mac Address  

echo $macaddress;  

This works for me on Windows, as ipconfig /all is Windows system command.

How to select a value in dropdown javascript?

Yes. As mentioned in the posts, value property is nonstandard and does not work with IE. You will need to use the selectedIndex property to achieve this. You can refer to the w3schools DOM reference to see the properties of HTML elements. The following link will give you the list of properties you can work with on the select element.

http://www.w3schools.com/jsref/dom_obj_select.asp

Update

This was not supported during 2011 on IE. As commented by finnTheHuman, it is supported at present.

Remote debugging a Java application

Answer covering Java >= 9:

For Java 9+, the JVM option needs a slight change by prefixing the address with the IP address of the machine hosting the JVM, or just *:

-agentlib:jdwp=transport=dt_socket,server=y,address=*:8000,suspend=n

This is due to a change noted in https://www.oracle.com/technetwork/java/javase/9-notes-3745703.html#JDK-8041435.

For Java < 9, the port number is enough to connect.

Autoplay audio files on an iPad with HTML5

UPDATE: This is a hack and it's not working anymore on IOS 4.X and above. This one worked on IOS 3.2.X.

It's not true. Apple doesn't want to autoplay video and audio on IPad because of the high amout of traffic you can use on mobile networks. I wouldn't use autoplay for online content. For Offline HTML sites it's a great feature and thats what I've used it for.

Here is a "javascript fake click" solution: http://www.roblaplaca.com/examples/html5AutoPlay/

Copy & Pasted Code from the site:

<script type="text/javascript"> 
        function fakeClick(fn) {
            var $a = $('<a href="#" id="fakeClick"></a>');
                $a.bind("click", function(e) {
                    e.preventDefault();
                    fn();
                });

            $("body").append($a);

            var evt, 
                el = $("#fakeClick").get(0);

            if (document.createEvent) {
                evt = document.createEvent("MouseEvents");
                if (evt.initMouseEvent) {
                    evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
                    el.dispatchEvent(evt);
                }
            }

            $(el).remove();
        }

        $(function() {
            var video = $("#someVideo").get(0);

            fakeClick(function() {
                video.play();
            });
        });

        </script> 

This is not my source. I've found this some time ago and tested the code on an IPad and IPhone with IOS 3.2.X.

Git: can't undo local changes (error: path ... is unmerged)

git checkout foo/bar.txt

did you tried that? (without a HEAD keyword)

I usually revert my changes this way.

Converting String to "Character" array in Java

One liner with :

String str = "testString";

//[t, e, s, t, S, t, r, i, n, g]
Character[] charObjectArray = 
    str.chars().mapToObj(c -> (char)c).toArray(Character[]::new); 

What it does is:

  • get an IntStream of the characters (you may want to also look at codePoints())
  • map each 'character' value to Character (you need to cast to actually say that its really a char, and then Java will box it automatically to Character)
  • get the resulting array by calling toArray()

Make ABC Ordered List Items Have Bold Style

You could do something like this also:

ol {
  font-weight: bold;
}

ol > li > * {
  font-weight: normal;
}

So you have no "style" attributes in your HTML

Declare a dictionary inside a static class

The correct syntax ( as tested in VS 2008 SP1), is this:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

Counting array elements in Python

If you have a multi-dimensional array, len() might not give you the value you are looking for. For instance:

import numpy as np
a = np.arange(10).reshape(2, 5)
print len(a) == 2

This code block will return true, telling you the size of the array is 2. However, there are in fact 10 elements in this 2D array. In the case of multi-dimensional arrays, len() gives you the length of the first dimension of the array i.e.

import numpy as np
len(a) == np.shape(a)[0]

To get the number of elements in a multi-dimensional array of arbitrary shape:

import numpy as np
size = 1
for dim in np.shape(a): size *= dim

RecyclerView inside ScrollView is not working

Calculating RecyclerView's height manually is not good, better is to use a custom LayoutManager.

The reason for above issue is any view which has it's scroll(ListView, GridView, RecyclerView) failed to calculate it's height when add as a child in another view has scroll. So overriding its onMeasure method will solve the issue.

Please replace the default layout manager with the below:

public class MyLinearLayoutManager extends android.support.v7.widget.LinearLayoutManager {

private static boolean canMakeInsetsDirty = true;
private static Field insetsDirtyField = null;

private static final int CHILD_WIDTH = 0;
private static final int CHILD_HEIGHT = 1;
private static final int DEFAULT_CHILD_SIZE = 100;

private final int[] childDimensions = new int[2];
private final RecyclerView view;

private int childSize = DEFAULT_CHILD_SIZE;
private boolean hasChildSize;
private int overScrollMode = ViewCompat.OVER_SCROLL_ALWAYS;
private final Rect tmpRect = new Rect();

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context) {
    super(context);
    this.view = null;
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);
    this.view = null;
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view) {
    super(view.getContext());
    this.view = view;
    this.overScrollMode = ViewCompat.getOverScrollMode(view);
}

@SuppressWarnings("UnusedDeclaration")
public MyLinearLayoutManager(RecyclerView view, int orientation, boolean reverseLayout) {
    super(view.getContext(), orientation, reverseLayout);
    this.view = view;
    this.overScrollMode = ViewCompat.getOverScrollMode(view);
}

public void setOverScrollMode(int overScrollMode) {
    if (overScrollMode < ViewCompat.OVER_SCROLL_ALWAYS || overScrollMode > ViewCompat.OVER_SCROLL_NEVER)
        throw new IllegalArgumentException("Unknown overscroll mode: " + overScrollMode);
    if (this.view == null) throw new IllegalStateException("view == null");
    this.overScrollMode = overScrollMode;
    ViewCompat.setOverScrollMode(view, overScrollMode);
}

public static int makeUnspecifiedSpec() {
    return View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED);
}

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state, int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);

    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);

    final boolean hasWidthSize = widthMode != View.MeasureSpec.UNSPECIFIED;
    final boolean hasHeightSize = heightMode != View.MeasureSpec.UNSPECIFIED;

    final boolean exactWidth = widthMode == View.MeasureSpec.EXACTLY;
    final boolean exactHeight = heightMode == View.MeasureSpec.EXACTLY;

    final int unspecified = makeUnspecifiedSpec();

    if (exactWidth && exactHeight) {
        // in case of exact calculations for both dimensions let's use default "onMeasure" implementation
        super.onMeasure(recycler, state, widthSpec, heightSpec);
        return;
    }

    final boolean vertical = getOrientation() == VERTICAL;

    initChildDimensions(widthSize, heightSize, vertical);

    int width = 0;
    int height = 0;

    // it's possible to get scrap views in recycler which are bound to old (invalid) adapter entities. This
    // happens because their invalidation happens after "onMeasure" method. As a workaround let's clear the
    // recycler now (it should not cause any performance issues while scrolling as "onMeasure" is never
    // called whiles scrolling)
    recycler.clear();

    final int stateItemCount = state.getItemCount();
    final int adapterItemCount = getItemCount();
    // adapter always contains actual data while state might contain old data (f.e. data before the animation is
    // done). As we want to measure the view with actual data we must use data from the adapter and not from  the
    // state
    for (int i = 0; i < adapterItemCount; i++) {
        if (vertical) {
            if (!hasChildSize) {
                if (i < stateItemCount) {
                    // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                    // we will use previously calculated dimensions
                    measureChild(recycler, i, widthSize, unspecified, childDimensions);
                } else {
                    logMeasureWarning(i);
                }
            }
            height += childDimensions[CHILD_HEIGHT];
            if (i == 0) {
                width = childDimensions[CHILD_WIDTH];
            }
            if (hasHeightSize && height >= heightSize) {
                break;
            }
        } else {
            if (!hasChildSize) {
                if (i < stateItemCount) {
                    // we should not exceed state count, otherwise we'll get IndexOutOfBoundsException. For such items
                    // we will use previously calculated dimensions
                    measureChild(recycler, i, unspecified, heightSize, childDimensions);
                } else {
                    logMeasureWarning(i);
                }
            }
            width += childDimensions[CHILD_WIDTH];
            if (i == 0) {
                height = childDimensions[CHILD_HEIGHT];
            }
            if (hasWidthSize && width >= widthSize) {
                break;
            }
        }
    }

    if (exactWidth) {
        width = widthSize;
    } else {
        width += getPaddingLeft() + getPaddingRight();
        if (hasWidthSize) {
            width = Math.min(width, widthSize);
        }
    }

    if (exactHeight) {
        height = heightSize;
    } else {
        height += getPaddingTop() + getPaddingBottom();
        if (hasHeightSize) {
            height = Math.min(height, heightSize);
        }
    }

    setMeasuredDimension(width, height);

    if (view != null && overScrollMode == ViewCompat.OVER_SCROLL_IF_CONTENT_SCROLLS) {
        final boolean fit = (vertical && (!hasHeightSize || height < heightSize))
                || (!vertical && (!hasWidthSize || width < widthSize));

        ViewCompat.setOverScrollMode(view, fit ? ViewCompat.OVER_SCROLL_NEVER : ViewCompat.OVER_SCROLL_ALWAYS);
    }
}

private void logMeasureWarning(int child) {
    if (BuildConfig.DEBUG) {
        Log.w("MyLinearLayoutManager", "Can't measure child #" + child + ", previously used dimensions will be reused." +
                "To remove this message either use #setChildSize() method or don't run RecyclerView animations");
    }
}

private void initChildDimensions(int width, int height, boolean vertical) {
    if (childDimensions[CHILD_WIDTH] != 0 || childDimensions[CHILD_HEIGHT] != 0) {
        // already initialized, skipping
        return;
    }
    if (vertical) {
        childDimensions[CHILD_WIDTH] = width;
        childDimensions[CHILD_HEIGHT] = childSize;
    } else {
        childDimensions[CHILD_WIDTH] = childSize;
        childDimensions[CHILD_HEIGHT] = height;
    }
}

@Override
public void setOrientation(int orientation) {
    // might be called before the constructor of this class is called
    //noinspection ConstantConditions
    if (childDimensions != null) {
        if (getOrientation() != orientation) {
            childDimensions[CHILD_WIDTH] = 0;
            childDimensions[CHILD_HEIGHT] = 0;
        }
    }
    super.setOrientation(orientation);
}

public void clearChildSize() {
    hasChildSize = false;
    setChildSize(DEFAULT_CHILD_SIZE);
}

public void setChildSize(int childSize) {
    hasChildSize = true;
    if (this.childSize != childSize) {
        this.childSize = childSize;
        requestLayout();
    }
}

private void measureChild(RecyclerView.Recycler recycler, int position, int widthSize, int heightSize, int[] dimensions) {
    final View child;
    try {
        child = recycler.getViewForPosition(position);
    } catch (IndexOutOfBoundsException e) {
        if (BuildConfig.DEBUG) {
            Log.w("MyLinearLayoutManager", "MyLinearLayoutManager doesn't work well with animations. Consider switching them off", e);
        }
        return;
    }

    final RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) child.getLayoutParams();

    final int hPadding = getPaddingLeft() + getPaddingRight();
    final int vPadding = getPaddingTop() + getPaddingBottom();

    final int hMargin = p.leftMargin + p.rightMargin;
    final int vMargin = p.topMargin + p.bottomMargin;

    // we must make insets dirty in order calculateItemDecorationsForChild to work
    makeInsetsDirty(p);
    // this method should be called before any getXxxDecorationXxx() methods
    calculateItemDecorationsForChild(child, tmpRect);

    final int hDecoration = getRightDecorationWidth(child) + getLeftDecorationWidth(child);
    final int vDecoration = getTopDecorationHeight(child) + getBottomDecorationHeight(child);

    final int childWidthSpec = getChildMeasureSpec(widthSize, hPadding + hMargin + hDecoration, p.width, canScrollHorizontally());
    final int childHeightSpec = getChildMeasureSpec(heightSize, vPadding + vMargin + vDecoration, p.height, canScrollVertically());

    child.measure(childWidthSpec, childHeightSpec);

    dimensions[CHILD_WIDTH] = getDecoratedMeasuredWidth(child) + p.leftMargin + p.rightMargin;
    dimensions[CHILD_HEIGHT] = getDecoratedMeasuredHeight(child) + p.bottomMargin + p.topMargin;

    // as view is recycled let's not keep old measured values
    makeInsetsDirty(p);
    recycler.recycleView(child);
}

private static void makeInsetsDirty(RecyclerView.LayoutParams p) {
    if (!canMakeInsetsDirty) {
        return;
    }
    try {
        if (insetsDirtyField == null) {
            insetsDirtyField = RecyclerView.LayoutParams.class.getDeclaredField("mInsetsDirty");
            insetsDirtyField.setAccessible(true);
        }
        insetsDirtyField.set(p, true);
    } catch (NoSuchFieldException e) {
        onMakeInsertDirtyFailed();
    } catch (IllegalAccessException e) {
        onMakeInsertDirtyFailed();
    }
}

private static void onMakeInsertDirtyFailed() {
    canMakeInsetsDirty = false;
    if (BuildConfig.DEBUG) {
        Log.w("MyLinearLayoutManager", "Can't make LayoutParams insets dirty, decorations measurements might be incorrect");
    }
}
}

Does C# support multiple inheritance?

You can't inherit multiple classes at a time. But there is an options to do that by the help of interface. See below code

interface IA
{
    void PrintIA();
}

class  A:IA
{
    public void PrintIA()
    {
        Console.WriteLine("PrintA method in Base Class A");
    }
}

interface IB
{
    void PrintIB();
}

class B : IB
{
    public void PrintIB()
    {
        Console.WriteLine("PrintB method in Base Class B");
    }
}

public class AB: IA, IB
{
    A a = new A();
    B b = new B();

    public void PrintIA()
    {
       a.PrintIA();
    }

    public void PrintIB()
    {
        b.PrintIB();
    }
}

you can call them as below

AB ab = new AB();
ab.PrintIA();
ab.PrintIB();

How do I remove a CLOSE_WAIT socket connection

Even though too much of CLOSE_WAIT connections means there is something wrong with your code in the first and this is accepted not good practice.

You might want to check out: https://github.com/rghose/kill-close-wait-connections

What this script does is send out the ACK which the connection was waiting for.

This is what worked for me.

DB2 Query to retrieve all table names for a given schema

This should work:

select * from syscat.tables

Pandas: how to change all the values of a column?

You can do a column transformation by using apply

Define a clean function to remove the dollar and commas and convert your data to float.

def clean(x):
    x = x.replace("$", "").replace(",", "").replace(" ", "")
    return float(x)

Next, call it on your column like this.

data['Revenue'] = data['Revenue'].apply(clean)

How can I convert a DateTime to the number of seconds since 1970?

That approach will be good if the date-time in question is in UTC, or represents local time in an area that has never observed daylight saving time. The DateTime difference routines do not take into account Daylight Saving Time, and consequently will regard midnight June 1 as being a multiple of 24 hours after midnight January 1. I'm unaware of anything in Windows that reports historical daylight-saving rules for the current locale, so I don't think there's any good way to correctly handle any time prior to the most recent daylight-saving rule change.

Clang vs GCC for my Linux Development project

I use both because sometimes they give different, useful error messages.

The Python project was able to find and fix a number of small buglets when one of the core developers first tried compiling with clang.

Why doesn't Java support unsigned ints?

As soon as signed and unsigned ints are mixed in an expression things start to get messy and you probably will lose information. Restricting Java to signed ints only really clears things up. I’m glad I don’t have to worry about the whole signed/unsigned business, though I sometimes do miss the 8th bit in a byte.

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You should replace the old OpenSSL binary file by the new one via a symlink:

sudo ln -sf /usr/local/ssl/bin/openssl `which openssl`

Remember that after this procedure you should reboot the server or restart all the services related to OpenSSL.

Single statement across multiple lines in VB.NET without the underscore character

I will say no.

But the only proof that I have is personal experience and the fact that documentation on line continuation doesn't have anything else in it.

http://msdn.microsoft.com/en-us/library/aa711641(VS.71).aspx

What is the difference between a pandas Series and a single-column DataFrame?

Import cars data

import pandas as pd

cars = pd.read_csv('cars.csv', index_col = 0)

Here is how the cars.csv file looks.

Print out drives_right column as Series:

print(cars.loc[:,"drives_right"])

    US      True
    AUS    False
    JAP    False
    IN     False
    RU      True
    MOR     True
    EG      True
    Name: drives_right, dtype: bool

The single bracket version gives a Pandas Series, the double bracket version gives a Pandas DataFrame.

Print out drives_right column as DataFrame

print(cars.loc[:,["drives_right"]])

         drives_right
    US           True
    AUS         False
    JAP         False
    IN          False
    RU           True
    MOR          True
    EG           True

Adding a Series to another Series creates a DataFrame.

Connection pooling options with JDBC: DBCP vs C3P0

Unfortunately they are all out of date. DBCP has been updated a bit recently, the other two are 2-3 years old, with many outstanding bugs.

Form Validation With Bootstrap (jQuery)

enter image description here

Here is a very simple and lightweight plugin for validation with Boostrap, you can use it if you like: https://github.com/wpic/bootstrap.validator.js

How to install Java SDK on CentOS?

I have written a shell script to install/uninstall java on centos. You can get it done by just run the shell. The core of this shell is :

1.download the jdk rpm(RedHat Package Manager) package.
2.install java using rpm.

You can see more detail here: https://github.com/daikaixian/WaterShell/tree/master/program_installer

Hope it works for you.

Show a message box from a class in c#?

using System.Windows.Forms;
...
MessageBox.Show("Hello World!");

What does "while True" mean in Python?

while True:
    ...

means infinite loop.

The while statement is often used of a finite loop. But using the constant 'True' guarantees the repetition of the while statement without the need to control the loop (setting a boolean value inside the iteration for example), unless you want to break it.

In fact

True == (1 == 1)

How to use Select2 with JSON via Ajax request?

If ajax request is not fired, please check the select2 class in the select element. Removing the select2 class will fix that issue.

How do you detect the clearing of a "search" HTML5 input?

It made sense to me that clicking the X should count as a change event. I already had the onChange event all setup to do what I needed it to do. So for me, the fix was to simply do this jQuery line:

$('#search').click(function(){ $(this).change(); });

What's the best way to dedupe a table?

I think this should require nothing more then just grouping by all columns except the id and choosing one row from every group - for simplicity just the first row, but this does not actually matter besides you have additional constraints on the id.

Or the other way around to get rid of the rows ... just delete all rows accept a single one from all groups.

'names' attribute must be the same length as the vector

Depending on what you're doing in the loop, the fact that the %in% operator returns a vector might be an issue; consider a simple example:

c1 <- c("one","two","three","more","more")
c2 <- c("seven","five","three")

if(c1%in%c2) {
    print("hello")
}

then the following warning is issued:

Warning message:
In if (c1 %in% c2) { :
  the condition has length > 1 and only the first element will be used

if something in your if statement is dependent on a specific number of elements, and they don't match, then it is possible to obtain the error you see

Adding whitespace in Java

Use the StringUtils class, it also includes null check

StringUtils.leftPad(String str, int size)
StringUtils.rightPad(String str, int size)

PHP foreach with Nested Array?

If you know the number of levels in nested arrays you can simply do nested loops. Like so:

//  Scan through outer loop
foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

if you do not know the depth of array you need to use recursion. See example below:

//  Multi-dementional Source Array
$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(
            7,
            8,
            array("four", 9, 10)
    ))
);

//  Output array
displayArrayRecursively($tmpArray);

/**
 * Recursive function to display members of array with indentation
 *
 * @param array $arr Array to process
 * @param string $indent indentation string
 */
function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                //
                displayArrayRecursively($value, $indent . '--');
            } else {
                //  Output
                echo "$indent $value \n";
            }
        }
    }
}

The code below with display only nested array with values for your specific case (3rd level only)

$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

//  Scan through outer loop
foreach ($tmpArray as $inner) {

    //  Check type
    if (is_array($inner)) {
        //  Scan through inner loop
        foreach ($inner[1] as $value) {
           echo "$value \n";
        }
    }
}

How to change Format of a Cell to Text using VBA

for large numbers that display with scientific notation set format to just '#'

How to set Android camera orientation properly?

This solution will work for all versions of Android. You can use reflection in Java to make it work for all Android devices:

Basically you should create a reflection wrapper to call the Android 2.2 setDisplayOrientation, instead of calling the specific method.

The method:

    protected void setDisplayOrientation(Camera camera, int angle){
    Method downPolymorphic;
    try
    {
        downPolymorphic = camera.getClass().getMethod("setDisplayOrientation", new Class[] { int.class });
        if (downPolymorphic != null)
            downPolymorphic.invoke(camera, new Object[] { angle });
    }
    catch (Exception e1)
    {
    }
}

And instead of using camera.setDisplayOrientation(x) use setDisplayOrientation(camera, x) :

    if (Integer.parseInt(Build.VERSION.SDK) >= 8)
        setDisplayOrientation(mCamera, 90);
    else
    {
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT)
        {
            p.set("orientation", "portrait");
            p.set("rotation", 90);
        }
        if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE)
        {
            p.set("orientation", "landscape");
            p.set("rotation", 90);
        }
    }   

Multiple controllers with AngularJS in single page app

What is the problem? To use multiple controllers, just use multiple ngController directives:

<div class="widget" ng-controller="widgetController">
    <p>Stuff here</p>
</div>

<div class="menu" ng-controller="menuController">
    <p>Other stuff here</p>
</div>

You will need to have the controllers available in your application module, as usual.

The most basic way to do it could be as simple as declaring the controller functions like this:

function widgetController($scope) {
   // stuff here
}

function menuController($scope) {
   // stuff here
}

Convert a file path to Uri in Android

Below code works fine before 18 API :-

public String getRealPathFromURI(Uri contentUri) {

        // can post image
        String [] proj={MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery( contentUri,
                        proj, // Which columns to return
                        null,       // WHERE clause; which rows to return (all rows)
                        null,       // WHERE clause selection arguments (none)
                        null); // Order-by clause (ascending by name)
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();

        return cursor.getString(column_index);
}

below code use on kitkat :-

public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

see below link for more info:-

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

Programmatically set left drawable in a TextView

You can use setCompoundDrawablesWithIntrinsicBounds(int left, int top, int right, int bottom)

set 0 where you don't want images

Example for Drawable on the left:

TextView textView = (TextView) findViewById(R.id.myTxtView);
textView.setCompoundDrawablesWithIntrinsicBounds(R.drawable.icon, 0, 0, 0);

Alternatively, you can use setCompoundDrawablesRelativeWithIntrinsicBounds to respect RTL/LTR layouts.


Tip: Whenever you know any XML attribute but don't have clue about how to use it at runtime. just go to the description of that property in developer doc. There you will find Related Methods if it's supported at runtime . i.e. For DrawableLeft

Groovy Shell warning "Could not open/create prefs root node ..."

I was getting the following message:

Could not open/create prefs root node Software\JavaSoft\Prefs at root 0x80000002

and it was gone after creating one of these registry keys, mine is 64 bit so I tried only that.

32 bit Windows
HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs

64 bit Windows
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\JavaSoft\Prefs

What are libtool's .la file for?

I found very good explanation about .la files here http://openbooks.sourceforge.net/books/wga/dealing-with-libraries.html

Summary (The way I understood): Because libtool deals with static and dynamic libraries internally (through --diable-shared or --disable-static) it creates a wrapper on the library files it builds. They are treated as binary library files with in libtool supported environment.

ng-repeat finish event

If you simply want to execute some code at the end of the loop, here's a slightly simpler variation that doesn't require extra event handling:

<div ng-controller="Ctrl">
  <div class="thing" ng-repeat="thing in things" my-post-repeat-directive>
    thing {{thing}}
  </div>
</div>
function Ctrl($scope) {
  $scope.things = [
    'A', 'B', 'C'  
  ];
}

angular.module('myApp', [])
.directive('myPostRepeatDirective', function() {
  return function(scope, element, attrs) {
    if (scope.$last){
      // iteration is complete, do whatever post-processing
      // is necessary
      element.parent().css('border', '1px solid black');
    }
  };
});

See a live demo.

jquery function setInterval

Don't pass the result of swapImages to setInterval by invoking it. Just pass the function, like this:

setInterval(swapImages, 1000);

How can I make visible an invisible control with jquery? (hide and show not work)

Here's some code I use to deal with this.

First we show the element, which will typically set the display type to "block" via .show() function, and then set the CSS rule to "visible":

jQuery( '.element' ).show().css( 'visibility', 'visible' );

Or, assuming that the class that is hiding the element is called hidden, such as in Twitter Bootstrap, toggleClass() can be useful:

jQuery( '.element' ).toggleClass( 'hidden' );

Lastly, if you want to chain functions, perhaps with fancy with a fading effect, you can do it like so:

jQuery( '.element' ).css( 'visibility', 'visible' ).fadeIn( 5000 );

is there something like isset of php in javascript/jQuery?

You can just:

if(variable||variable===0){
    //Yes it is set
    //do something
}
else {
    //No it is not set
    //Or its null
    //do something else 
}

How to create a <style> tag with Javascript?

This object variable will append style tag to the head tag with type attribute and one simple transition rule inside that matches every single id/class/element. Feel free to modify content property and inject as many rules as you need. Just make sure that css rules inside content remain in one line (or 'escape' each new line, if You prefer so).

var script = {

  type: 'text/css', style: document.createElement('style'), 
  content: "* { transition: all 220ms cubic-bezier(0.390, 0.575, 0.565, 1.000); }",
  append: function() {

    this.style.type = this.type;
    this.style.appendChild(document.createTextNode(this.content));
    document.head.appendChild(this.style);

}}; script.append();

PersistenceContext EntityManager injection NullPointerException

If the component is an EJB, then, there shouldn't be a problem injecting an EM.

But....In JBoss 5, the JAX-RS integration isn't great. If you have an EJB, you cannot use scanning and you must manually list in the context-param resteasy.jndi.resource. If you still have scanning on, Resteasy will scan for the resource class and register it as a vanilla JAX-RS service and handle the lifecycle.

This is probably the problem.

Subprocess changing directory

You want to use an absolute path to the executable, and use the cwd kwarg of Popen to set the working directory. See the docs.

If cwd is not None, the child’s current directory will be changed to cwd before it is executed. Note that this directory is not considered when searching the executable, so you can’t specify the program’s path relative to cwd.

how to convert string into time format and add two hours

Try this one, I test it, working fine

Date date = null;
String str = "2012/07/25 12:00:00";
DateFormat formatter = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
date = formatter.parse(str);
Calendar calendar = Calendar.getInstance();
calendar.setTime(date);
calendar.add(Calendar.HOUR, 2);
System.out.println(calendar.getTime());  // Output : Wed Jul 25 14:00:00 IST 2012

If you want to convert in your input type than add this code also

formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
str=formatter.format(calendar.getTime());
System.out.println(str);  // Output : 2012-07-25 14:00:00

JS map return object

Use .map without return in simple way. Also start using let and const instead of var because let and const is more recommended

_x000D_
_x000D_
const rockets = [_x000D_
    { country:'Russia', launches:32 },_x000D_
    { country:'US', launches:23 },_x000D_
    { country:'China', launches:16 },_x000D_
    { country:'Europe(ESA)', launches:7 },_x000D_
    { country:'India', launches:4 },_x000D_
    { country:'Japan', launches:3 }_x000D_
];_x000D_
_x000D_
const launchOptimistic = rockets.map(elem => (_x000D_
  {_x000D_
    country: elem.country,_x000D_
    launches: elem.launches+10_x000D_
  } _x000D_
));_x000D_
_x000D_
console.log(launchOptimistic);
_x000D_
_x000D_
_x000D_

How can I determine browser window size on server side C#

So here is how you will do it.

Write a javascript function which fires whenever the window is resized.

window.onresize = function(event) {
    var height=$(window).height();
    var width=$(window).width();
    $.ajax({
     url: "/getwindowsize.ashx",
     type: "POST",
     data : { Height: height, 
              Width:width, 
              selectedValue:selectedValue },
     contentType: "application/json; charset=utf-8",
     dataType: "json",
     success: function (response) { 
           // do stuff
     }

}

Codebehind of Handler:

 public class getwindowsize : IHttpHandler {

public void ProcessRequest (HttpContext context) {
    context.Response.ContentType = "application/json";
     string Height = context.Request.QueryString["Height"]; 
     string Width = context.Request.QueryString["Width"]; 
    }

kill a process in bash

try kill -9 {processID}

To find the process ID you can use ps -ef | grep gedit

Automatically run %matplotlib inline in IPython Notebook

Further to @Kyle Kelley and @DGrady, here is the entry which can be found in the

$HOME/.ipython/profile_default/ipython_kernel_config.py (or whichever profile you have created)

Change

# Configure matplotlib for interactive use with the default matplotlib backend.
# c.IPKernelApp.matplotlib = none

to

# Configure matplotlib for interactive use with the default matplotlib backend.
c.IPKernelApp.matplotlib = 'inline'

This will then work in both ipython qtconsole and notebook sessions.

Regex - how to match everything except a particular pattern

pattern - re

str.split(/re/g) 

will return everything except the pattern.

Test here

Converting string "true" / "false" to boolean value

If you're using the variable result:

result = result == "true";

Fastest way to check if a file exist using standard C++/C++11/C?

In C++17 :

#include <experimental/filesystem>

bool is_file_exist(std::string& str) {   
    namespace fs = std::experimental::filesystem;
    fs::path p(str);
    return fs::exists(p);
}

Reset local repository branch to be just like remote repository HEAD

git reset --hard HEAD actually only resets to the last committed state. In this case HEAD refers to the HEAD of your branch.

If you have several commits, this won't work..

What you probably want to do, is reset to the head of origin or whatever you remote repository is called. I'd probably just do something like

git reset --hard origin/HEAD

Be careful though. Hard resets cannot easily be undone. It is better to do as Dan suggests, and branch off a copy of your changes before resetting.

Set variable with multiple values and use IN

You need a table variable:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

YouTube Video Embedded via iframe Ignoring z-index?

We can simply add ?wmode=transparent to the end of YouTube URL. This will tell YouTube to include the video with the wmode set. So you new embed code will look like this:-

<iframe width="420" height="315" src="http://www.youtube.com/embed/C4I84Gy-cPI?wmode=transparent" frameborder="0" allowfullscreen>

Insert Multiple Rows Into Temp Table With SQL Server 2012

Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

What version of the SQL Server engine do you get from SELECT @@VERSION ??

Android check internet connection

Try the following code:

public static boolean isNetworkAvailable(Context context) {
        boolean outcome = false;

        if (context != null) {
            ConnectivityManager cm = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo[] networkInfos = cm.getAllNetworkInfo();

            for (NetworkInfo tempNetworkInfo : networkInfos) {


                /**
                 * Can also check if the user is in roaming
                 */
                if (tempNetworkInfo.isConnected()) {
                    outcome = true;
                    break;
                }
            }
        }

        return outcome;
    }

Get second child using jQuery

How's this:

$(t).first().next()

MAJOR UPDATE:

Apart from how beautiful the answer looks, you must also give a thought to the performance of the code. Therefore, it is also relavant to know what exactly is in the $(t) variable. Is it an array of <TD> or is it a <TR> node with several <TD>s inside it? To further illustrate the point, see the jsPerf scores on a <ul> list with 50 <li> children:

http://jsperf.com/second-child-selector

The $(t).first().next() method is the fastest here, by far.

But, on the other hand, if you take the <tr> node and find the <td> children and and run the same test, the results won't be the same.

Hope it helps. :)

Excel formula to get week number in month (having Monday)

If week 1 always starts on the first Monday of the month try this formula for week number

=INT((6+DAY(A1+1-WEEKDAY(A1-1)))/7)

That gets the week number from the date in A1 with no intermediate calculations - if you want to use your "Monday's date" in B1 you can use this version

=INT((DAY(B1)+6)/7)

Writing a list to a file with Python

You can also use the print function if you're on python3 as follows.

f = open("myfile.txt","wb")
print(mylist, file=f)

PHP: Update multiple MySQL fields in single query

Comma separate the values:

UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"

Angular 2 - View not updating after model changes

Instead of dealing with zones and change detection — let AsyncPipe handle complexity. This will put observable subscription, unsubscription (to prevent memory leaks) and changes detection on Angular shoulders.

Change your class to make an observable, that will emit results of new requests:

export class RecentDetectionComponent implements OnInit {

    recentDetections$: Observable<Array<RecentDetection>>;

    constructor(private recentDetectionService: RecentDetectionService) {
    }

    ngOnInit() {
        this.recentDetections$ = Observable.interval(5000)
            .exhaustMap(() => this.recentDetectionService.getJsonFromApi())
            .do(recent => console.log(recent[0].macAddress));
    }
}

And update your view to use AsyncPipe:

<tr *ngFor="let detected of recentDetections$ | async">
    ...
</tr>

Want to add, that it's better to make a service with a method that will take interval argument, and:

  • create new requests (by using exhaustMap like in code above);
  • handle requests errors;
  • stop browser from making new requests while offline.

node.js require() cache - possible to invalidate?

If it's for unit tests, another good tool to use is proxyquire. Everytime you proxyquire the module, it will invalidate the module cache and cache a new one. It also allows you to modify the modules required by the file that you are testing.

Quickly reading very large tables as dataframes

I didn't see this question initially and asked a similar question a few days later. I am going to take my previous question down, but I thought I'd add an answer here to explain how I used sqldf() to do this.

There's been little bit of discussion as to the best way to import 2GB or more of text data into an R data frame. Yesterday I wrote a blog post about using sqldf() to import the data into SQLite as a staging area, and then sucking it from SQLite into R. This works really well for me. I was able to pull in 2GB (3 columns, 40mm rows) of data in < 5 minutes. By contrast, the read.csv command ran all night and never completed.

Here's my test code:

Set up the test data:

bigdf <- data.frame(dim=sample(letters, replace=T, 4e7), fact1=rnorm(4e7), fact2=rnorm(4e7, 20, 50))
write.csv(bigdf, 'bigdf.csv', quote = F)

I restarted R before running the following import routine:

library(sqldf)
f <- file("bigdf.csv")
system.time(bigdf <- sqldf("select * from f", dbname = tempfile(), file.format = list(header = T, row.names = F)))

I let the following line run all night but it never completed:

system.time(big.df <- read.csv('bigdf.csv'))

How do I get the path of a process in Unix / Linux

You can also get the path on GNU/Linux with (not thoroughly tested):

char file[32];
char buf[64];
pid_t pid = getpid();
sprintf(file, "/proc/%i/cmdline", pid);
FILE *f = fopen(file, "r");
fgets(buf, 64, f);
fclose(f);

If you want the directory of the executable for perhaps changing the working directory to the process's directory (for media/data/etc), you need to drop everything after the last /:

*strrchr(buf, '/') = '\0';
/*chdir(buf);*/

jquery toggle slide from left to right and back

Hide #categories initially

#categories {
    display: none;
}

and then, using JQuery UI, animate the Menu slowly

var duration = 'slow';

$('#cat_icon').click(function () {
    $('#cat_icon').hide(duration, function() {
        $('#categories').show('slide', {direction: 'left'}, duration);});
});
$('.panel_title').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

You can use any time in milliseconds as well

var duration = 2000;

If you want to hide on class='panel_item' too, select both panel_title and panel_item

$('.panel_title,.panel_item').click(function () {
    $('#categories').hide('slide', {direction: 'left'}, duration, function() {
        $('#cat_icon').show(duration);});
});

JSFiddle

How do I create a right click context menu in Java Swing?

This question is a bit old - as are the answers (and the tutorial as well)

The current api for setting a popupMenu in Swing is

myComponent.setComponentPopupMenu(myPopupMenu);

This way it will be shown automagically, both for mouse and keyboard triggers (the latter depends on LAF). Plus, it supports re-using the same popup across a container's children. To enable that feature:

myChild.setInheritsPopupMenu(true);

Bootstrap navbar Active State not working

With Bootstrap 4 you can use this:

$(document).ready(function() {
    $(document).on('click', '.nav-item a', function (e) {
        $(this).parent().addClass('active').siblings().removeClass('active');
    });
});

How do I set Tomcat Manager Application User Name and Password for NetBeans?

Netbeans Problem: For apache Tomcat server Authentication required dialog box requesting user name and password

This dialog box appear If a user role and his credentials are not set or is incorrect for Tomcat startup via NetBeans IDE,

OR when user/pass set in IDE is not matches with user/pass in "canf/tomcat-user.xml" file

1..Need to check user name and password set in IDE tools-->server

2..Check \CATALINA_BASE\conf\tomcat-users.xml. whether user and his role is defined or not. If not add these lines

<user username="ide" password="EiWnNlBG" roles="manager-script,admin"/>
</tomcat-users>

3.. set the same user/pass in IDE tools->server

  1. restart your server to get effect of changes

Source: http://ohmjavaclasses.blogspot.com/2011/12/netbeans-problem-for-apache-tomcat.html

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I hope this will help somebody, I solved the problem like this

There was a problem because the database was not open. Command startup opens the database.

This you can solve with command alter database open in some case with alter database open resetlogs

$ sqlplus / sysdba

SQL> startup
ORACLE instance started.

Total System Global Area 1073741824 bytes
Fixed Size          8628936 bytes
Variable Size         624952632 bytes
Database Buffers      436207616 bytes
Redo Buffers            3952640 bytes
Database mounted.
Database opened.

SQL> conn user/pass123
Connected.

Blur effect on a div element

I think this is what you are looking for? If you are looking to add a blur effect to a div element, you can do this directly through CSS Filters-- See fiddle: http://jsfiddle.net/ayhj9vb0/

 div {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
  width: 100px;
  height: 100px;
  background-color: #ccc;

}

Printing the value of a variable in SQL Developer

1 ) Go to view menu.
2 ) Select the DBMS_OUTPUT menu item.
3 ) Press Ctrl + N and select connection editor.
4 ) Execute the SET SERVEROUTPUT ON Command.
5 ) Then execute your PL/SQL Script.

enter image description here enter image description here