Programs & Examples On #Outlook calendar

outlook-calendar is related to the calendar function of Outlook (which is a personal information manager from Microsoft, available as a part of the Microsoft Office suite).

How to remove non UTF-8 characters from text file

This command:

iconv -f utf-8 -t utf-8 -c file.txt

will clean up your UTF-8 file, skipping all the invalid characters.

-f is the source format
-t the target format
-c skips any invalid sequence

PHP function to get the subdomain of a URL

I know I'm really late to the game, but here goes.

What I did was take the HTTP_HOST server variable ($_SERVER['HTTP_HOST']) and the number of letters in the domain (so for example.com it would be 11).

Then I used the substr function to get the subdomain. I did

$numberOfLettersInSubdomain = strlen($_SERVER['HTTP_HOST'])-12
$subdomain = substr($_SERVER['HTTP_HOST'], $numberOfLettersInSubdomain);

I cut the substring off at 12 instead of 11 because substrings start on 1 for the second parameter. So now if you entered test.example.com, the value of $subdomain would be test.

This is better than using explode because if the subdomain has a . in it, this will not cut it off.

Ubuntu: Using curl to download an image

curl without any options will perform a GET request. It will simply return the data from the URI specified. Not retrieve the file itself to your local machine.

When you do,

$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png

You will receive binary data:

                   |?>?$! <R?HP@T*?Pm?Z??jU???ZP+UAUQ@?
??{X\? K???>0c?yF[i?}4?!?V¸?H_?)nO#?;I??vg^_ ??-Hm$$N0.
???%Y[?L?U3?_^9??P?T?0'u8?l?4 ...

In order to save this, you can use:

$ curl https://www.python.org/static/apple-touch-icon-144x144-precomposed.png > image.png

to store that raw image data inside of a file.

An easier way though, is just to use wget.

$ wget https://www.python.org/static/apple-touch-icon-144x144-precomposed.png
$ ls
.
..
apple-touch-icon-144x144-precomposed.png

How to resolve the error "Unable to access jarfile ApacheJMeter.jar errorlevel=1" while initiating Jmeter?

If you'll go through these steps:

  1. In the Terminal type brew install jmeter and hit Enter
  2. When it'll be done type jmeter and hit Enter again

You won't have to solve any kind of issue. Don't thank

How to convert datatype:object to float64 in python?

You can convert most of the columns by just calling convert_objects:

In [36]:

df = df.convert_objects(convert_numeric=True)
df.dtypes
Out[36]:
Date         object
WD            int64
Manpower    float64
2nd          object
CTR          object
2ndU        float64
T1            int64
T2          int64
T3           int64
T4        float64
dtype: object

For column '2nd' and 'CTR' we can call the vectorised str methods to replace the thousands separator and remove the '%' sign and then astype to convert:

In [39]:

df['2nd'] = df['2nd'].str.replace(',','').astype(int)
df['CTR'] = df['CTR'].str.replace('%','').astype(np.float64)
df.dtypes
Out[39]:
Date         object
WD            int64
Manpower    float64
2nd           int32
CTR         float64
2ndU        float64
T1            int64
T2            int64
T3            int64
T4           object
dtype: object
In [40]:

df.head()
Out[40]:
        Date  WD  Manpower   2nd   CTR  2ndU   T1    T2   T3     T4
0   2013/4/6   6       NaN  2645  5.27  0.29  407   533  454    368
1   2013/4/7   7       NaN  2118  5.89  0.31  257   659  583    369
2  2013/4/13   6       NaN  2470  5.38  0.29  354   531  473    383
3  2013/4/14   7       NaN  2033  6.77  0.37  396   748  681    458
4  2013/4/20   6       NaN  2690  5.38  0.29  361   528  541    381

Or you can do the string handling operations above without the call to astype and then call convert_objects to convert everything in one go.

UPDATE

Since version 0.17.0 convert_objects is deprecated and there isn't a top-level function to do this so you need to do:

df.apply(lambda col:pd.to_numeric(col, errors='coerce'))

See the docs and this related question: pandas: to_numeric for multiple columns

error: Unable to find vcvarsall.bat

Looks like its looking for VC compilers, so you could try to mention compiler type with -c mingw32, since you have msys

python setup.py install -c mingw32

Android transparent status bar and actionbar

I'm developing an app that needs to look similar in all devices with >= API14 when it comes to actionbar and statusbar customization. I've finally found a solution and since it took a bit of my time I'll share it to save some of yours. We start by using an appcompat-21 dependency.

Transparent Actionbar:

values/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="android:windowContentOverlay">@null</item>
    <item name="windowActionBarOverlay">true</item>
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="windowActionBarOverlay">false</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>


values-v21/styles.xml:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    ...
</style>

<style name="AppTheme.ActionBar.Transparent" parent="AppTheme">
    <item name="colorPrimary">@android:color/transparent</item>
</style>

<style name="AppTheme.ActionBar" parent="AppTheme">
    <item name="colorPrimaryDark">@color/bg_colorPrimaryDark</item>
    <item name="colorPrimary">@color/default_yellow</item>
</style>

Now you can use these themes in your AndroidManifest.xml to specify which activities will have a transparent or colored ActionBar:

    <activity
            android:name=".MyTransparentActionbarActivity"
            android:theme="@style/AppTheme.ActionBar.Transparent"/>

    <activity
            android:name=".MyColoredActionbarActivity"
            android:theme="@style/AppTheme.ActionBar"/>

enter image description here enter image description here enter image description here enter image description here enter image description here

Note: in API>=21 to get the Actionbar transparent you need to get the Statusbar transparent too, otherwise will not respect your colour styles and will stay light-grey.



Transparent Statusbar (only works with API>=19):
This one it's pretty simple just use the following code:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

But you'll notice a funky result: enter image description here

This happens because when the Statusbar is transparent the layout will use its height. To prevent this we just need to:

SOLUTION ONE:
Add this line android:fitsSystemWindows="true" in your layout view container of whatever you want to be placed bellow the Actionbar:

    ...
        <LinearLayout
                android:fitsSystemWindows="true"
                android:layout_width="match_parent"
                android:layout_height="match_parent">
            ...
        </LinearLayout>
    ...

SOLUTION TWO:
Add a few lines to our previous method:

protected void setStatusBarTranslucent(boolean makeTranslucent) {
        View v = findViewById(R.id.bellow_actionbar);
        if (v != null) {
            int paddingTop = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT ? MyScreenUtils.getStatusBarHeight(this) : 0;
            TypedValue tv = new TypedValue();
            getTheme().resolveAttribute(android.support.v7.appcompat.R.attr.actionBarSize, tv, true);
            paddingTop += TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics());
            v.setPadding(0, makeTranslucent ? paddingTop : 0, 0, 0);
        }

        if (makeTranslucent) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        } else {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

Where R.id.bellow_actionbar will be the layout container view id of whatever we want to be placed bellow the Actionbar:

...
    <LinearLayout
            android:id="@+id/bellow_actionbar"
            android:layout_width="match_parent"
            android:layout_height="match_parent">
        ...
    </LinearLayout>
...

enter image description here

So this is it, it think I'm not forgetting something. In this example I didn't use a Toolbar but I think it'll have the same result. This is how I customize my Actionbar:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        View vg = getActionBarView();
        getWindow().requestFeature(vg != null ? Window.FEATURE_ACTION_BAR : Window.FEATURE_NO_TITLE);

        super.onCreate(savedInstanceState);
        setContentView(getContentView());

        if (vg != null) {
            getSupportActionBar().setCustomView(vg, new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            getSupportActionBar().setDisplayShowCustomEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(false);
            getSupportActionBar().setDisplayShowTitleEnabled(false);
            getSupportActionBar().setDisplayUseLogoEnabled(false);
        }
        setStatusBarTranslucent(true);
    }

Note: this is an abstract class that extends ActionBarActivity
Hope it helps!

How to escape apostrophe (') in MySql?

I think if you have any data point with apostrophe you can add one apostrophe before the apostrophe

eg. 'This is John's place'

Here MYSQL assumes two sentence 'This is John' 's place'

You can put 'This is John''s place'. I think it should work that way.

How to connect to a MS Access file (mdb) using C#?

Another simplest way to connect is through an OdbcConnection using App.config file like this

  <appSettings>  
    <add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True"/>
  </appSettings>

MyDB.mdb is my database file and it is present in current primary application folder with main exe file.

if your mdf file has password then use like this

  <appSettings>
    <add key="Conn" value="Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|MyDB.mdb;Persist Security Info=True;Jet OLEDB:Database Password=Admin$@123"/>
  </appSettings>

How do I get a list of all subdomains of a domain?

In Windows nslookup the command is

ls -d somedomain.com > outfile.txt

which stores the subdomain list in outfile.txt

few domains these days allow this

Javascript sleep/delay/wait function

The behavior exact to the one specified by you is impossible in JS as implemented in current browsers. Sorry.

Well, you could in theory make a function with a loop where loop's end condition would be based on time, but this would hog your CPU, make browser unresponsive and would be extremely poor design. I refuse to even write an example for this ;)


Update: My answer got -1'd (unfairly), but I guess I could mention that in ES6 (which is not implemented in browsers yet, nor is it enabled in Node.js by default), it will be possible to write a asynchronous code in a synchronous fashion. You would need promises and generators for that.

You can use it today, for instance in Node.js with harmony flags, using Q.spawn(), see this blog post for example (last example there).

How can I add NSAppTransportSecurity to my info.plist file?

Open your info.plist file of your project with any editor of your preference, then add this code at the end of the file before the last

<key>NSAppTransportSecurity</key>
<dict>
   <key>NSAllowsArbitraryLoads</key>
<true/>
</dict>

VBScript - How to make program wait until process has finished?

This may not specifically answer your long 3 part question but this thread is old and I found this while searching today. Here is one shorter way to: "Wait until a process has finished." If you know the name of the process such as "EXCEL.EXE"

strProcess = "EXCEL.EXE"    
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Do While colProcesses.Count > 0
    Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
    Wscript.Sleep(1000) 'Sleep 1 second
   'msgbox colProcesses.count 'optional to show the loop works
Loop

Credit to: http://crimsonshift.com/scripting-check-if-process-or-program-is-running-and-start-it/

How to find files modified in last x minutes (find -mmin does not work as expected)

I am working through the same need and I believe your timeframe is incorrect.

Try these:

  • 15min change: find . -mtime -.01
  • 1hr change: find . -mtime -.04
  • 12 hr change: find . -mtime -.5

You should be using 24 hours as your base. The number after -mtime should be relative to 24 hours. Thus -.5 is the equivalent of 12 hours, because 12 hours is half of 24 hours.

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

How to filter array when object key value is in array

You can use Array#filter function and additional array for storing sorted values;

var recordsSorted = []

ids.forEach(function(e) {
    recordsSorted.push(records.filter(function(o) {
        return o.empid === e;
    }));
});

console.log(recordsSorted);

Result:

[ [ { empid: 1, fname: 'X', lname: 'Y' } ],
  [ { empid: 4, fname: 'C', lname: 'Y' } ],
  [ { empid: 5, fname: 'C', lname: 'Y' } ] ]

No provider for HttpClient

In my case, the error occured when using a service from an angular module located in an npm package, where the service requires injection of HttpClient. When installing the npm package, a duplicate node_modules directory was created inside the package directory due to version conflict handling of npm (engi-sdk-client is the module containing the service):

enter image description here

Obviously, the dependency to HttpClient is not resolved correctly, as the locations of HttpClientModule injected into the service (lives in the duplicate node_modules directory) and the one injected in app.module (the correct node_modules) don't match.

I've also had this error in other setups containing a duplicate node_modules directory due to a wrong npm install call.

This defective setup also leads to the described runtime exception No provider for HttpClient!.

TL;DR; Check for duplicate node_modules directories, if none of the other solutions work!

Python - OpenCV - imread - Displaying Image

This can help you

namedWindow( "Display window", CV_WINDOW_AUTOSIZE );// Create a window for display.
imshow( "Display window", image );                   // Show our image inside it.

PHP Multiple Checkbox Array

<form method='post' id='userform' action='thisform.php'> <tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td> </tr> </table> <input type='submit' class='buttons'> </form>

<?php 
if (isset($_POST['checkboxvar'])) 
{
    print_r($_POST['checkboxvar']); 
}
?>

You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.

To echo checked options into your email you would then do this:

echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want

Please keep in mind you should always sanitize your input as needed.

For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays

How do I replace a character in a string in Java?

StringBuilder s = new StringBuilder(token.length());

CharacterIterator it = new StringCharacterIterator(token);
for (char ch = it.first(); ch != CharacterIterator.DONE; ch = it.next()) {
    switch (ch) {
        case '&':
            s.append("&amp;");
            break;
        case '<':
            s.append("&lt;");
            break;
        case '>':
            s.append("&gt;");
            break;
        default:
            s.append(ch);
            break;
    }
}

token = s.toString();

Write a file on iOS

Your code is working at my end, i have just tested it. Where are you checking your changes? Use Documents directory path. To get path -

NSLog(@"%@",documentsDirectory);

and copy path from console and then open finder and press Cmd+shift+g and paste path here and then open your file

Convert a Unicode string to a string in Python (containing extra symbols)

>>> text=u'abcd'
>>> str(text)
'abcd'

If the string only contains ascii characters.

How can I remove the first line of a text file using bash/sed script?

You can use -i to update the file without using '>' operator. The following command will delete the first line from the file and save it to the file.

sed -i '1d' filename

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

Running Python in PowerShell?

Since, you are able to run Python in PowerShell. You can just do python <scriptName>.py to run the script. So, for a script named test.py containing

name = raw_input("Enter your name: ")
print "Hello, " + name

The PowerShell session would be

PS C:\Python27> python test.py
Enter your name: Monty Python
Hello, Monty Python
PS C:\Python27>

Install sbt on ubuntu

It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.

Tool to Unminify / Decompress JavaScript

Chrome developer tools has this feature built-in. Bring up the developer tools (pressing F12 is one way), in the Sources tab, the bottom left bar has a set of icons. The "{}" icon is "Pretty print" and does this conversion on demand.

UPDATE: IE9 "F12 developer tools" also has a "Format JavaScript" feature in the Script tab under the Tools icon there. (see Tip #4 in F12 The best kept web debugging secret)

enter image description here

How do I add space between two variables after a print in Python

A quick warning, this a pretty wordy answer.

print is tricky sometimes, I had some problems with it when I first started. What you want is a few spaces in between two variables after you print them right? There's many ways to do this, as shown in the above answers.

This is your code:

count = 1
conv = count * 2.54
print count, conv

It's output is this:

1 2.54

If you want spaces in between, you can do it the naive way by sticking a string of spaces in between them. The variables count and conv need to be converted to string types to concatenate(join) them together. This is done with str().

print (str(count) + "           " + str(conv))
### Provides an output of:
1           2.54

To do this is the newer, more pythonic way, we use the % sign in conjunction with a letter to denote the kind of value we're using. Here I use underscores instead of spaces to show how many there are. The modulo before the last values just tells python to insert the following values in, in the order we provided.

print ('%i____%s' % (count, conv))
### provides an output of:
1____2.54

I used %i for count because it is a whole number, and %s for conv, because using %i in that instance would provide us with "2" instead of "2.54" Technically, I could've used both %s, but it's all good.

I hope this helps!

-Joseph

P.S. if you want to get complicated with your formatting, you should look at prettyprint for large amounts of text such as dictionaries and tuple lists(imported as pprint) as well as which does automatic tabs, spacing and other cool junk.

Here's some more information about strings in the python docs. http://docs.python.org/library/string.html#module-string

How do I style a <select> dropdown with only CSS?

Yes. You may style any HTML element by its tag name, like this:

select {
  font-weight: bold;
}

Of course, you can also use a CSS class to style it, like any other element:

<select class="important">
  <option>Important Option</option>
  <option>Another Important Option</option>
</select>

<style type="text/css">
  .important {
    font-weight: bold;
  }
</style>

ERROR Error: No value accessor for form control with unspecified name attribute on switch

I also had the same error , angular 7

 <button (click)="Addcity(city.name)" [(ngModel)]="city.name"  class="dropdown-item fontstyle"
     *ngFor="let city of Cities; let i = index">
      {{city.name}}
 </button>

I just added ngDefaultControl

   <button (click)="Addcity(city.name)" [(ngModel)]="city.name"  ngDefaultControl class="dropdown-item fontstyle"
 *ngFor="let city of Cities; let i = index">
  {{city.name}}

Garbage collector in Android

It seems System.gc() do not work on Art Android 6.0.1 Nexus 5x, So I use Runtime.getRuntime().gc(); instead.

Create a one to many relationship using SQL Server

If you are not using SSMS then here is the syntax:

ALTER TABLE <table_name>
ADD <constraint_name> FOREIGN KEY 
(<column_name1> ,
<column_name2> )
REFERENCES <table_name>
(<column_name1> ,
<column_name2>)

http://infogoal.com/sql/sql-add-foreignkey.htm

Eclipse internal error while initializing Java tooling

Delete your existing workspace and then recreate the workspace and add your projects.

PHP: How to get current time in hour:minute:second?

You can combine both in the same date function call

date("d-m-Y H:i:s");  

Changing text color onclick

Do something like this:

<script>
function changeColor(id)
{
  document.getElementById(id).style.color = "#ff0000"; // forecolor
  document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>

<div id="myid">Hello There !!</div>

<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>

C# Return Different Types?

Here is how you might do it with generics:

public T GetAnything<T>()
{
   T t = //Code to create instance

   return t;
}

But you would have to know what type you wanted returned at design time. And that would mean that you could just call a different method for each creation...

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

Bash script processing limited number of commands in parallel

Use the wait built-in:

process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait

For the above example, 4 processes process1 ... process4 would be started in the background, and the shell would wait until those are completed before starting the next set.

From the GNU manual:

wait [jobspec or pid ...]

Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.

How to display pandas DataFrame of floats using a format string for columns?

As of Pandas 0.17 there is now a styling system which essentially provides formatted views of a DataFrame using Python format strings:

import pandas as pd
import numpy as np

constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
C

which displays

enter image description here

This is a view object; the DataFrame itself does not change formatting, but updates in the DataFrame are reflected in the view:

constants.name = ['pie','eek']
C

enter image description here

However it appears to have some limitations:

  • Adding new rows and/or columns in-place seems to cause inconsistency in the styled view (doesn't add row/column labels):

    constants.loc[2] = dict(name='bogus', value=123.456)
    constants['comment'] = ['fee','fie','fo']
    constants
    

enter image description here

which looks ok but:

C

enter image description here

  • Formatting works only for values, not index entries:

    constants = pd.DataFrame([('pi',np.pi),('e',np.e)],
                   columns=['name','value'])
    constants.set_index('name',inplace=True)
    C = constants.style.format({'name': '~~ {} ~~', 'value':'--> {:15.10f} <--'})
    C
    

enter image description here

How to run a C# application at Windows startup?

OK here are my 2 cents: try passing path with each backslash as double backslash. I have found sometimes calling WIN API requires that.

Error in installation a R package

The solution indicated by Guannan Shen has one drawback that usually goes unnoticed.

When you run sudo R in order to run install.packages() as superuser, the directories in which you install the library end up belonging to root user, a.k.a., the superuser.

So, next time you need to update your libraries, you will not remember that you ran sudo, therefore leaving root as the owner of the files and directories; that eventually causes the error when trying to move files, because no one can overwrite root but themself.

That can be averted by running

sudo chown -R yourusername:yourusername *

in the directory lib that contains your local libraries, replacing yourusername by the adequated value in your installation. Then you try installing once again.

Error: allowDefinition='MachineToApplication' beyond application level

The error suggests that the code you are using is expecting a virtual directory to be setup on IIS.

Look up the documentation and add the required virtual directory. It should be a directory that has a web.config in it (not the root directory).

facebook: permanent Page Access Token?

If you are requesting only page data, then you can use a page access token. You will only have to authorize the user once to get the user access token; extend it to two months validity then request the token for the page. This is all explained in Scenario 5. Note, that the acquired page access token is only valid for as long as the user access token is valid.

Laravel Eloquent Join vs Inner Join?

Probably not what you want to hear, but a "feeds" table would be a great middleman for this sort of transaction, giving you a denormalized way of pivoting to all these data with a polymorphic relationship.

You could build it like this:

<?php

Schema::create('feeds', function($table) {
    $table->increments('id');
    $table->timestamps();
    $table->unsignedInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
    $table->morphs('target'); 
});

Build the feed model like so:

<?php

class Feed extends Eloquent
{
    protected $fillable = ['user_id', 'target_type', 'target_id'];

    public function user()
    {
        return $this->belongsTo('User');
    }

    public function target()
    {
        return $this->morphTo();
    }
}

Then keep it up to date with something like:

<?php

Vote::created(function(Vote $vote) {
    $target_type = 'Vote';
    $target_id   = $vote->id;
    $user_id     = $vote->user_id;

    Feed::create(compact('target_type', 'target_id', 'user_id'));
});

You could make the above much more generic/robust—this is just for demonstration purposes.

At this point, your feed items are really easy to retrieve all at once:

<?php

Feed::whereIn('user_id', $my_friend_ids)
    ->with('user', 'target')
    ->orderBy('created_at', 'desc')
    ->get();

Generate MD5 hash string with T-SQL

try this:

select SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5',  '[email protected]' )),3,32) 

Calculate distance between 2 GPS coordinates

Java Version of Haversine Algorithm based on Roman Makarov`s reply to this thread

public class HaversineAlgorithm {

    static final double _eQuatorialEarthRadius = 6378.1370D;
    static final double _d2r = (Math.PI / 180D);

    public static int HaversineInM(double lat1, double long1, double lat2, double long2) {
        return (int) (1000D * HaversineInKM(lat1, long1, lat2, long2));
    }

    public static double HaversineInKM(double lat1, double long1, double lat2, double long2) {
        double dlong = (long2 - long1) * _d2r;
        double dlat = (lat2 - lat1) * _d2r;
        double a = Math.pow(Math.sin(dlat / 2D), 2D) + Math.cos(lat1 * _d2r) * Math.cos(lat2 * _d2r)
                * Math.pow(Math.sin(dlong / 2D), 2D);
        double c = 2D * Math.atan2(Math.sqrt(a), Math.sqrt(1D - a));
        double d = _eQuatorialEarthRadius * c;

        return d;
    }

}

How do I switch between command and insert mode in Vim?

There is also one more solution for that kind of problem, which is rather rare, I think, and you may experience it, if you are using vim on OS X Sierra. Actually, it's a problem with Esc button — not with vim. For example, I wasnt able to exit fullscreen video on youtube using Esc, but I lived with that for a few months until I had experienced the same problem with vim.

I found this solution. If you are lazy enough to follow external link, switching off Siri and killing the process in Activity Monitor helped.

How to show alert message in mvc 4 controller?

You cannot show an alert from a controller. There is one way communication from the client to the server.The server can therefore not tell the client to do anything. The client requests and the server gives a response.

You therefore need to use javascript when the response returns to show a messagebox of some sort.

OR

using jquery on the button that calls the controller action

<script>
 $(document).ready(function(){
  $("#submitButton").on("click",function()
  {
   alert('Your Message');
  });

});
<script>

Can I delete a git commit but keep the changes?

You're looking for either git reset HEAD^ --soft or git reset HEAD^ --mixed.

There are 3 modes to the reset command as stated in the docs:

git reset HEAD^ --soft

undo the git commit. Changes still exist in the working tree(the project folder) + the index (--cached)

git reset HEAD^ --mixed

undo git commit + git add. Changes still exist in the working tree

git reset HEAD^ --hard

Like you never made these changes to the codebase. Changes are gone from the working tree.

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

Get the number of rows in a HTML table

The following code assumes that your table has the ID 'MyTable'

<script language="JavaScript">
<!--
var oRows = document.getElementById('MyTable').getElementsByTagName('tr');
var iRowCount = oRows.length;

alert('Your table has ' + iRowCount + ' rows.');
//-->
</script>

Answer taken from : http://www.delphifaq.com/faq/f771.shtml, which is the first result on google for the query : "Get the number of rows in a HTML table" ;)

Time comparison

Java doesn't (yet) have a good built-in Time class (it has one for JDBC queries, but that's not what you want).

One option would be use the JodaTime APIs and its LocalTime class.

Sticking with just the built-in Java APIs, you are stuck with java.util.Date. You can use a SimpleDateFormat to parse the time, then the Date comparison functions to see if it is before or after some other time:

SimpleDateFormat parser = new SimpleDateFormat("HH:mm");
Date ten = parser.parse("10:00");
Date eighteen = parser.parse("18:00");

try {
    Date userDate = parser.parse(someOtherDate);
    if (userDate.after(ten) && userDate.before(eighteen)) {
        ...
    }
} catch (ParseException e) {
    // Invalid date was entered
}

Or you could just use some string manipulations, perhaps a regular expression to extract just the hour and the minute portions, convert them to numbers and do a numerical comparison:

Pattern p = Pattern.compile("(\d{2}):(\d{2})");
Matcher m = p.matcher(userString);
if (m.matches() ) {
    String hourString = m.group(1);
    String minuteString = m.group(2);
    int hour = Integer.parseInt(hourString);
    int minute = Integer.parseInt(minuteString);

    if (hour >= 10 && hour <= 18) {
        ...
    }
}

It really all depends on what you are trying to accomplish.

Java; String replace (using regular expressions)?

What is your polynomial? If you're "processing" it, I'm envisioning some sort of tree of sub-expressions being generated at some point, and would think that it would be much simpler to use that to generate your string than to re-parse the raw expression with a regex.

Just throwing a different way of thinking out there. I'm not sure what else is going on in your app.

How to set an "Accept:" header on Spring RestTemplate request?

Here is a simple answer. Hope it helps someone.

import org.springframework.boot.devtools.remote.client.HttpHeaderInterceptor;
import org.springframework.http.MediaType;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.web.client.RestTemplate;


public String post(SomeRequest someRequest) {
    // create a list the headers 
    List<ClientHttpRequestInterceptor> interceptors = new ArrayList<>();
    interceptors.add(new HttpHeaderInterceptor("Accept", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("ContentType", MediaType.APPLICATION_JSON_VALUE));
    interceptors.add(new HttpHeaderInterceptor("username", "user123"));
    interceptors.add(new HttpHeaderInterceptor("customHeader1", "c1"));
    interceptors.add(new HttpHeaderInterceptor("customHeader2", "c2"));
    // initialize RestTemplate
    RestTemplate restTemplate = new RestTemplate();
    // set header interceptors here
    restTemplate.setInterceptors(interceptors);
    // post the request. The response should be JSON string
    String response = restTemplate.postForObject(Url, someRequest, String.class);
    return response;
}

Clean out Eclipse workspace metadata

The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?

For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.

How to log SQL statements in Spring Boot?

For the MS-SQL server driver (Microsoft SQL Server JDBC Driver).

try using:

logging.level.com.microsoft.sqlserver.jdbc=debug

in your application.properties file.

My personal preference is to set:

logging.level.com.microsoft.sqlserver.jdbc=info
logging.level.com.microsoft.sqlserver.jdbc.internals=debug

You can look at these links for reference:

How to add 10 days to current time in Rails

Try this on Ruby. It will return a new date/time the specified number of days in the future

DateTime.now.days_since(10)

How to convert An NSInteger to an int?

Ta da:

NSInteger myInteger = 42;
int myInt = (int) myInteger;

NSInteger is nothing more than a 32/64 bit int. (it will use the appropriate size based on what OS/platform you're running)

How do I programmatically "restart" an Android app?

try this:

Intent intent = getPackageManager().getLaunchIntentForPackage(getPackageName());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);

font awesome icon in select option

If you want the caret down symbol, remove the "appearence: none" it implies to remove webkit and moz- as well from select in css.

Loading DLLs at runtime in C#

Right now, you're creating an instance of every type defined in the assembly. You only need to create a single instance of Class1 in order to call the method:

class Program
{
    static void Main(string[] args)
    {
        var DLL = Assembly.LoadFile(@"C:\visual studio 2012\Projects\ConsoleApplication1\ConsoleApplication1\DLL.dll");

        var theType = DLL.GetType("DLL.Class1");
        var c = Activator.CreateInstance(theType);
        var method = theType.GetMethod("Output");
        method.Invoke(c, new object[]{@"Hello"});

        Console.ReadLine();
    }
}

How to stop C++ console application from exiting immediately?

If you run your code from a competent IDE, such as Code::Blocks, the IDE will manage the console it uses to run the code, keeping it open when the application closes. You don't want to add special code to keep the console open, because this will prevent it functioning correctly when you use it for real, outside of the IDE.

How to access cookies in AngularJS?

AngularJS provides ngCookies module and $cookieStore service to use Browser Cookies.

We need to add angular-cookies.min.js file to use cookie feature.

Here is some method of AngularJS Cookie.

  • get(key); // This method returns the value of given cookie key.

  • getObject(key); //This method returns the deserialized value of given cookie key.

  • getAll(); //This method returns a key value object with all the cookies.

  • put(key, value, [options]); //This method sets a value for given cookie key.

  • remove(key, [options]); //This method remove given cookie.

Example

Html

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.0-beta.1/angular-cookies.min.js"></script>
</head>
<body ng-controller="MyController">
{{cookiesUserName}} loves {{cookietechnology}}.
</body>
</html>

JavaScript

var myApp = angular.module('myApp', ['ngCookies']);
myApp.controller('MyController', ['$scope', '$cookies', '$cookieStore', '$window', function($scope, $cookies, $cookieStore, $window) {
$cookies.userName = 'Max Joe';
$scope.cookiesUserName = $cookies.userName;
$cookieStore.put('technology', 'Web');
$scope.cookietechnology = $cookieStore.get('technology'); }]);

I have Taken reference from http://www.tutsway.com/simple-example-of-cookie-in-angular-js.php.

How to replace a character from a String in SQL?

Are you sure that the data stored in the database is actually a question mark? I would tend to suspect from the sample data that the problem is one of character set conversion where ? is being used as the replacement character when the character can't be represented in the client character set. Possibly, the database is actually storing Microsoft "smart quote" characters rather than simple apostrophes.

What does the DUMP function show is actually stored in the database?

SELECT column_name,
       dump(column_name,1016)
  FROM your_table
 WHERE <<predicate that returns just the sample data you posted>>

What application are you using to view the data? What is the client's NLS_LANG set to?

What is the database and national character set? Is the data stored in a VARCHAR2 column? Or NVARCHAR2?

SELECT parameter, value
  FROM v$nls_parameters
 WHERE parameter LIKE '%CHARACTERSET';

If all the problem characters are stored in the database as 0x19 (decimal 25), your REPLACE would need to be something like

UPDATE table_name
   SET column1 = REPLACE(column1, chr(25), q'[']'),
       column2 = REPLACE(column2, chr(25), q'[']'),
       ...
       columnN = REPLACE(columnN, chr(25), q'[']')
 WHERE INSTR(column1,chr(25)) > 0
    OR INSTR(column2,chr(25)) > 0 
    ...
    OR INSTR(columnN,chr(25)) > 0

When to use Hadoop, HBase, Hive and Pig?

First of all we should get clear that Hadoop was created as a faster alternative to RDBMS. To process large amount of data at a very fast rate which earlier took a lot of time in RDBMS.

Now one should know the two terms :

  1. Structured Data : This is the data that we used in traditional RDBMS and is divided into well defined structures.

  2. Unstructured Data : This is important to understand, about 80% of the world data is unstructured or semi structured. These are the data which are on its raw form and cannot be processed using RDMS. Example : facebook, twitter data. (http://www.dummies.com/how-to/content/unstructured-data-in-a-big-data-environment.html).

So, large amount of data was being generated in the last few years and the data was mostly unstructured, that gave birth to HADOOP. It was mainly used for very large amount of data that takes unfeasible amount of time using RDBMS. It had many drawbacks, that it could not be used for comparatively small data in real time but they have managed to remove its drawbacks in the newer version.

Before going further I would like to tell that a new Big Data tool is created when they see a fault on the previous tools. So, whichever tool you will see that is created has been done to overcome the problem of the previous tools.

Hadoop can be simply said as two things : Mapreduce and HDFS. Mapreduce is where the processing takes place and HDFS is the DataBase where data is stored. This structure followed WORM principal i.e. write once read multiple times. So, once we have stored data in HDFS, we cannot make changes. This led to the creation of HBASE, a NOSQL product where we can make changes in the data also after writing it once.

But with time we saw that Hadoop had many faults and for that we created different environment over the Hadoop structure. PIG and HIVE are two popular examples.

HIVE was created for people with SQL background. The queries written is similar to SQL named as HIVEQL. HIVE was developed to process completely structured data. It is not used for ustructured data.

PIG on the other hand has its own query language i.e. PIG LATIN. It can be used for both structured as well as unstructured data.

Moving to the difference as when to use HIVE and when to use PIG, I don't think anyone other than the architect of PIG could say. Follow the link : https://developer.yahoo.com/blogs/hadoop/comparing-pig-latin-sql-constructing-data-processing-pipelines-444.html

Finding rows that don't contain numeric data in Oracle

I've found this useful:

 select translate('your string','_0123456789','_') from dual

If the result is NULL, it's numeric (ignoring floating point numbers.)

However, I'm a bit baffled why the underscore is needed. Without it the following also returns null:

 select translate('s123','0123456789', '') from dual

There is also one of my favorite tricks - not perfect if the string contains stuff like "*" or "#":

 SELECT 'is a number' FROM dual WHERE UPPER('123') = LOWER('123')

How to sum data.frame column values?

When you have 'NA' values in the column, then

sum(as.numeric(JuneData1$Account.Balance), na.rm = TRUE)

Try/catch does not seem to have an effect

Adding "-EA Stop" solved this for me.

Requests -- how to tell if you're getting a 404

Look at the r.status_code attribute:

if r.status_code == 404:
    # A 404 was issued.

Demo:

>>> import requests
>>> r = requests.get('http://httpbin.org/status/404')
>>> r.status_code
404

If you want requests to raise an exception for error codes (4xx or 5xx), call r.raise_for_status():

>>> r = requests.get('http://httpbin.org/status/404')
>>> r.raise_for_status()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "requests/models.py", line 664, in raise_for_status
    raise http_error
requests.exceptions.HTTPError: 404 Client Error: NOT FOUND
>>> r = requests.get('http://httpbin.org/status/200')
>>> r.raise_for_status()
>>> # no exception raised.

You can also test the response object in a boolean context; if the status code is not an error code (4xx or 5xx), it is considered ‘true’:

if r:
    # successful response

If you want to be more explicit, use if r.ok:.

Create Map in Java

There is even a better way to create a Map along with initialization:

Map<String, String> rightHereMap = new HashMap<String, String>()
{
    {
        put("key1", "value1");
        put("key2", "value2");
    }
};

For more options take a look here How can I initialise a static Map?

log4net hierarchy and logging levels

Its true the official documentation (Apache log4net™ Manual - Introduction) states there are the following levels...

  • ALL
  • DEBUG
  • INFO
  • WARN
  • ERROR
  • FATAL
  • OFF

... but oddly when I view assembly log4net.dll, v1.2.15.0 sealed class log4net.Core.Level I see the following levels defined...

public static readonly Level Alert;
public static readonly Level All;
public static readonly Level Critical;
public static readonly Level Debug;
public static readonly Level Emergency;
public static readonly Level Error;
public static readonly Level Fatal;
public static readonly Level Fine;
public static readonly Level Finer;
public static readonly Level Finest;
public static readonly Level Info;
public static readonly Level Log4Net_Debug;
public static readonly Level Notice;
public static readonly Level Off;
public static readonly Level Severe;
public static readonly Level Trace;
public static readonly Level Verbose;
public static readonly Level Warn;

I have been using TRACE in conjunction with PostSharp OnBoundaryEntry and OnBoundaryExit for a long time. I wonder why these other levels are not in the documentation. Furthermore, what is the true priority of all these levels?

How to create a printable Twitter-Bootstrap page

In case someone is looking for a solution for Bootstrap v2.X.X here. I am leaving the solution I was using. This is not fully tested on all browsers however it could be a good start.

1) make sure the media attribute of bootstrap-responsive.css is screen.

<link href="/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />

2) create a print.css and make sure its media attribute print

<link href="/css/print.css" rel="stylesheet" media="print" />

3) inside print.css, add the "width" of your website in html & body

html, 
body {
    width: 1200px !important;
}

4.) reproduce the necessary media query classes in print.css because they were inside bootstrap-responsive.css and we have disabled it when printing.

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Here is full version of print.css:

html, 
body {
    width: 1200px !important;
}

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

what do <form action="#"> and <form method="post" action="#"> do?

action="" will resolve to the page's address. action="#" will resolve to the page's address + #, which will mean an empty fragment identifier.

Doing the latter might prevent a navigation (new load) to the same page and instead try to jump to the element with the id in the fragment identifier. But, since it's empty, it won't jump anywhere.

Usually, authors just put # in href-like attributes when they're not going to use the attribute where they're using scripting instead. In these cases, they could just use action="" (or omit it if validation allows).

How to compile a Perl script to a Windows executable with Strawberry Perl?

There are three packagers, and two compilers:

free packager: PAR
commercial packagers: perl2exe, perlapp
compilers: B::C, B::CC

http://search.cpan.org/dist/B-C/perlcompile.pod

(Note: perlfaq3 is still wrong)

For strawberry you need perl-5.16 and B-C from git master (1.43), as B-C-1.42 does not support 5.16.

Embedding Base64 Images

Most modern desktop browsers such as Chrome, Mozilla and Internet Explorer support images encoded as data URL. But there are problems displaying data URLs in some mobile browsers: Android Stock Browser and Dolphin Browser won't display embedded JPEGs.

I reccomend you to use the following tools for online base64 encoding/decoding:

Check the "Format as Data URL" option to format as a Data URL.

How to draw a checkmark / tick using CSS?

Try this // html example

<span>&#10003;</span>

// css example

span {
  content: "\2713";
}

What is the difference between require and require-dev sections in composer.json?

Different Environments

Typically, software will run in different environments:

  • development
  • testing
  • staging
  • production

Different Dependencies in Different Environments

The dependencies which are declared in the require section of composer.json are typically dependencies which are required for running an application or a package in

  • staging
  • production

environments, whereas the dependencies declared in the require-dev section are typically dependencies which are required in

  • developing
  • testing

environments.

For example, in addition to the packages used for actually running an application, packages might be needed for developing the software, such as:

  • friendsofphp/php-cs-fixer (to detect and fix coding style issues)
  • squizlabs/php_codesniffer (to detect and fix coding style issues)
  • phpunit/phpunit (to drive the development using tests)
  • etc.

Deployment

Now, in development and testing environments, you would typically run

$ composer install

to install both production and development dependencies.

However, in staging and production environments, you only want to install dependencies which are required for running the application, and as part of the deployment process, you would typically run

$ composer install --no-dev

to install only production dependencies.

Semantics

In other words, the sections

  • require
  • require-dev

indicate to composer which packages should be installed when you run

$ composer install

or

$ composer install --no-dev

That is all.

Note Development dependencies of packages your application or package depend on will never be installed

For reference, see:

How to make a movie out of images in python

I use the ffmpeg-python binding. You can find more information here.

import ffmpeg
(
    ffmpeg
    .input('/path/to/jpegs/*.jpg', pattern_type='glob', framerate=25)
    .output('movie.mp4')
    .run()
)

Convert an integer to a float number

intutils.ToFloat32

// ToFloat32 converts a int num to a float32 num
func ToFloat32(in int) float32 {
    return float32(in)
}

// ToFloat64 converts a int num to a float64 num
func ToFloat64(in int) float64 {
    return float64(in)
}

postgres: upgrade a user to be a superuser?

ALTER USER myuser WITH SUPERUSER;

You can read more at the Documentation

Fixing broken UTF-8 encoding

If you have double-encoded UTF8 characters (various smart quotes, dashes, apostrophe ’, quotation mark “, etc), in mysql you can dump the data, then read it back in to fix the broken encoding.

Like this:

mysqldump -h DB_HOST -u DB_USER -p DB_PASSWORD --opt --quote-names \
    --skip-set-charset --default-character-set=latin1 DB_NAME > DB_NAME-dump.sql

mysql -h DB_HOST -u DB_USER -p DB_PASSWORD \
    --default-character-set=utf8 DB_NAME < DB_NAME-dump.sql

This was a 100% fix for my double encoded UTF-8.

Source: http://blog.hno3.org/2010/04/22/fixing-double-encoded-utf-8-data-in-mysql/

jQuery to loop through elements with the same class

With a simple for loop:

var testimonials= $('.testimonial');
for (var i = 0; i < testimonials.length; i++) {
  // Using $() to re-wrap the element.
  $(testimonials[i]).text('a');
}

How to add items to array in nodejs

Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:

var array = [];
calendars.forEach(function(item) {
    array.push(item.id);
});

console.log(array);

You can also use the map() method to generate an Array filled with the results of calling the specified function on each element. Something like:

var array = calendars.map(function(item) {
    return item.id;
});

console.log(array);

And, since ECMAScript 2015 has been released, you may start seeing examples using let or const instead of var and the => syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):

let array = calendars.map(item => item.id);
console.log(array);

Java, List only subdirectories from a directory, not files

A very simple Java 8 solution:

File[] directories = new File("/your/path/").listFiles(File::isDirectory);

It's equivalent to using a FileFilter (works with older Java as well):

File[] directories = new File("/your/path/").listFiles(new FileFilter() {
    @Override
    public boolean accept(File file) {
        return file.isDirectory();
    }
});

Performance of Java matrix math libraries?

There are many different freely available java linear algebra libraries. http://www.ujmp.org/java-matrix/benchmark/ Unfortunately that benchmark only gives you info about matrix multiplication (with transposing the test does not allow the different libraries to exploit their respective design features).

What you should look at is how these linear algebra libraries perform when asked to compute various matrix decompositions. http://ojalgo.org/matrix_compare.html

How can I check if a program exists from a Bash script?

My setup for a Debian server:

I had the problem when multiple packages contained the same name.

For example apache2. So this was my solution:

function _apt_install() {
    apt-get install -y $1 > /dev/null
}

function _apt_install_norecommends() {
    apt-get install -y --no-install-recommends $1 > /dev/null
}
function _apt_available() {
    if [ `apt-cache search $1 | grep -o "$1" | uniq | wc -l` = "1" ]; then
        echo "Package is available : $1"
        PACKAGE_INSTALL="1"
    else
        echo "Package $1 is NOT available for install"
        echo  "We can not continue without this package..."
        echo  "Exitting now.."
        exit 0
    fi
}
function _package_install {
    _apt_available $1
    if [ "${PACKAGE_INSTALL}" = "1" ]; then
        if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
             echo  "package is already_installed: $1"
        else
            echo  "installing package : $1, please wait.."
            _apt_install $1
            sleep 0.5
        fi
    fi
}

function _package_install_no_recommends {
    _apt_available $1
    if [ "${PACKAGE_INSTALL}" = "1" ]; then
        if [ "$(dpkg-query -l $1 | tail -n1 | cut -c1-2)" = "ii" ]; then
             echo  "package is already_installed: $1"
        else
            echo  "installing package : $1, please wait.."
            _apt_install_norecommends $1
            sleep 0.5
        fi
    fi
}

Command /usr/bin/codesign failed with exit code 1

Very often the error /usr/bin/codesign failed with exit code 1 occurred in case the user has no file extensions for texture files in Models.scnassets folder. macOS very often generates a files with hidden extensions.

For example: you have a file myTexture but it must include an extension as well – myTexture.png.

How to get HttpClient returning status code and response body?

BasicResponseHandler throws if the status is not 2xx. See its javadoc.

Here is how I would do it:

HttpResponse response = client.execute( get );
int code = response.getStatusLine().getStatusCode();
InputStream body = response.getEntity().getContent();
// Read the body stream

Or you can also write a ResponseHandler starting from BasicResponseHandler source that don't throw when the status is not 2xx.

JQuery, setTimeout not working

You've got a couple of issues here.

Firstly, you're defining your code within an anonymous function. This construct:

(function() {
  ...
)();

does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.

You're passing in a code block to setTimeout(). The problem is that update() is not within scope when executed like that. It however if you pass in a function pointer instead so this works:

(function() {
  $(document).ready(function() {update();});

  function update() { 
    $("#board").append(".");
    setTimeout(update, 1000);     }
  }
)();

because the function pointer update is within scope of that block.

But like I said, there is no need for the anonymous function so you can rewrite it like this:

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout(update, 1000);     }
}

or

$(document).ready(function() {update();});

function update() { 
  $("#board").append(".");
  setTimeout('update()', 1000);     }
}

and both of these work. The second works because the update() within the code block is within scope now.

I also prefer the $(function() { ... } shortened block form and rather than calling setTimeout() within update() you can just use setInterval() instead:

$(function() {
  setInterval(update, 1000);
});

function update() {
  $("#board").append(".");
}

Hope that clears that up.

SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch

I had the same problem and finally resolved it by changing the order of pem blocks in certificate file.

The cert block should be put in the beginning of the file, then intermediate blocks, then root block.

I realized this problem by comparing a problematic certificate file with a working certificate file.

Checking if a string is empty or null in Java

You can use Apache commons-lang

StringUtils.isEmpty(String str) - Checks if a String is empty ("") or null.

or

StringUtils.isBlank(String str) - Checks if a String is whitespace, empty ("") or null.

the latter considers a String which consists of spaces or special characters eg " " empty too. See java.lang.Character.isWhitespace API

Laravel csrf token mismatch for ajax POST Request

For Laravel 5.8, setting the csrf meta tag for your layout and setting the request header for csrf in ajax settings won't work if you are using ajax to submit a form that already includes a _token input field generated by the Laravel blade templating engine.

You must include the already generated csrf token from the form with your ajax request because the server would be expecting it and not the one in your meta tag.

For instance, this is how the _token input field generated by Blade looks like:

<form>
    <input name="_token" type="hidden" value="cf54ty6y7yuuyyygytfggfd56667DfrSH8i">
    <input name="my_data" type="text" value="">
    <!-- other input fields -->
</form>

You then submit your form with ajax like this:

<script> 
    $(document).ready(function() { 
        let token = $('form').find('input[name="_token"]').val();
        let myData = $('form').find('input[name="my_data"]').val();
        $('form').submit(function() { 
            $.ajax({ 
                type:'POST', 
                url:'/ajax', 
                data: {_token: token, my_data: myData}
                // headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, // unnecessary 
                // other ajax settings
            }); 
            return false;
        }); 
    }); 
</script>

The csrf token in the meta header is only useful when you are submitting a form without a Blade generated _token input field.

How do I write a batch script that copies one directory to another, replaces old files?

It seems that the latest function for this in windows 7 is robocopy.

Usage example:

robocopy <source> <destination> /e /xf <file to exclude> <another file>

/e copies subdirectories including empty ones, /xf excludes certain files from being copied.

More options here: http://technet.microsoft.com/en-us/library/cc733145(v=ws.10).aspx

Generating a drop down list of timezones with PHP

You can create very easy a dropdown from this array (It was a time-consuming task to put this together and test it). We already use this list in some of our apps.

It is very important to store timezone identifiers in your database and not just the timezone offset like "GMT+2", because of Daylight Saving Times.

UPDATE

I updated/corrected the timezones list (also checkout: https://github.com/paptamas/timezones):

<?php
$timezones = array (
'(GMT-11:00) Midway Island' => 'Pacific/Midway',
'(GMT-11:00) Samoa' => 'Pacific/Samoa',
'(GMT-10:00) Hawaii' => 'Pacific/Honolulu',
'(GMT-09:00) Alaska' => 'US/Alaska',
'(GMT-08:00) Pacific Time (US &amp; Canada)' => 'America/Los_Angeles',
'(GMT-08:00) Tijuana' => 'America/Tijuana',
'(GMT-07:00) Arizona' => 'US/Arizona',
'(GMT-07:00) Chihuahua' => 'America/Chihuahua',
'(GMT-07:00) La Paz' => 'America/Chihuahua',
'(GMT-07:00) Mazatlan' => 'America/Mazatlan',
'(GMT-07:00) Mountain Time (US &amp; Canada)' => 'US/Mountain',
'(GMT-06:00) Central America' => 'America/Managua',
'(GMT-06:00) Central Time (US &amp; Canada)' => 'US/Central',
'(GMT-06:00) Guadalajara' => 'America/Mexico_City',
'(GMT-06:00) Mexico City' => 'America/Mexico_City',
'(GMT-06:00) Monterrey' => 'America/Monterrey',
'(GMT-06:00) Saskatchewan' => 'Canada/Saskatchewan',
'(GMT-05:00) Bogota' => 'America/Bogota',
'(GMT-05:00) Eastern Time (US &amp; Canada)' => 'US/Eastern',
'(GMT-05:00) Indiana (East)' => 'US/East-Indiana',
'(GMT-05:00) Lima' => 'America/Lima',
'(GMT-05:00) Quito' => 'America/Bogota',
'(GMT-04:00) Atlantic Time (Canada)' => 'Canada/Atlantic',
'(GMT-04:30) Caracas' => 'America/Caracas',
'(GMT-04:00) La Paz' => 'America/La_Paz',
'(GMT-04:00) Santiago' => 'America/Santiago',
'(GMT-03:30) Newfoundland' => 'Canada/Newfoundland',
'(GMT-03:00) Brasilia' => 'America/Sao_Paulo',
'(GMT-03:00) Buenos Aires' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Georgetown' => 'America/Argentina/Buenos_Aires',
'(GMT-03:00) Greenland' => 'America/Godthab',
'(GMT-02:00) Mid-Atlantic' => 'America/Noronha',
'(GMT-01:00) Azores' => 'Atlantic/Azores',
'(GMT-01:00) Cape Verde Is.' => 'Atlantic/Cape_Verde',
'(GMT+00:00) Casablanca' => 'Africa/Casablanca',
'(GMT+00:00) Edinburgh' => 'Europe/London',
'(GMT+00:00) Greenwich Mean Time : Dublin' => 'Etc/Greenwich',
'(GMT+00:00) Lisbon' => 'Europe/Lisbon',
'(GMT+00:00) London' => 'Europe/London',
'(GMT+00:00) Monrovia' => 'Africa/Monrovia',
'(GMT+00:00) UTC' => 'UTC',
'(GMT+01:00) Amsterdam' => 'Europe/Amsterdam',
'(GMT+01:00) Belgrade' => 'Europe/Belgrade',
'(GMT+01:00) Berlin' => 'Europe/Berlin',
'(GMT+01:00) Bern' => 'Europe/Berlin',
'(GMT+01:00) Bratislava' => 'Europe/Bratislava',
'(GMT+01:00) Brussels' => 'Europe/Brussels',
'(GMT+01:00) Budapest' => 'Europe/Budapest',
'(GMT+01:00) Copenhagen' => 'Europe/Copenhagen',
'(GMT+01:00) Ljubljana' => 'Europe/Ljubljana',
'(GMT+01:00) Madrid' => 'Europe/Madrid',
'(GMT+01:00) Paris' => 'Europe/Paris',
'(GMT+01:00) Prague' => 'Europe/Prague',
'(GMT+01:00) Rome' => 'Europe/Rome',
'(GMT+01:00) Sarajevo' => 'Europe/Sarajevo',
'(GMT+01:00) Skopje' => 'Europe/Skopje',
'(GMT+01:00) Stockholm' => 'Europe/Stockholm',
'(GMT+01:00) Vienna' => 'Europe/Vienna',
'(GMT+01:00) Warsaw' => 'Europe/Warsaw',
'(GMT+01:00) West Central Africa' => 'Africa/Lagos',
'(GMT+01:00) Zagreb' => 'Europe/Zagreb',
'(GMT+02:00) Athens' => 'Europe/Athens',
'(GMT+02:00) Bucharest' => 'Europe/Bucharest',
'(GMT+02:00) Cairo' => 'Africa/Cairo',
'(GMT+02:00) Harare' => 'Africa/Harare',
'(GMT+02:00) Helsinki' => 'Europe/Helsinki',
'(GMT+02:00) Istanbul' => 'Europe/Istanbul',
'(GMT+02:00) Jerusalem' => 'Asia/Jerusalem',
'(GMT+02:00) Kyiv' => 'Europe/Helsinki',
'(GMT+02:00) Pretoria' => 'Africa/Johannesburg',
'(GMT+02:00) Riga' => 'Europe/Riga',
'(GMT+02:00) Sofia' => 'Europe/Sofia',
'(GMT+02:00) Tallinn' => 'Europe/Tallinn',
'(GMT+02:00) Vilnius' => 'Europe/Vilnius',
'(GMT+03:00) Baghdad' => 'Asia/Baghdad',
'(GMT+03:00) Kuwait' => 'Asia/Kuwait',
'(GMT+03:00) Minsk' => 'Europe/Minsk',
'(GMT+03:00) Nairobi' => 'Africa/Nairobi',
'(GMT+03:00) Riyadh' => 'Asia/Riyadh',
'(GMT+03:00) Volgograd' => 'Europe/Volgograd',
'(GMT+03:30) Tehran' => 'Asia/Tehran',
'(GMT+04:00) Abu Dhabi' => 'Asia/Muscat',
'(GMT+04:00) Baku' => 'Asia/Baku',
'(GMT+04:00) Moscow' => 'Europe/Moscow',
'(GMT+04:00) Muscat' => 'Asia/Muscat',
'(GMT+04:00) St. Petersburg' => 'Europe/Moscow',
'(GMT+04:00) Tbilisi' => 'Asia/Tbilisi',
'(GMT+04:00) Yerevan' => 'Asia/Yerevan',
'(GMT+04:30) Kabul' => 'Asia/Kabul',
'(GMT+05:00) Islamabad' => 'Asia/Karachi',
'(GMT+05:00) Karachi' => 'Asia/Karachi',
'(GMT+05:00) Tashkent' => 'Asia/Tashkent',
'(GMT+05:30) Chennai' => 'Asia/Calcutta',
'(GMT+05:30) Kolkata' => 'Asia/Kolkata',
'(GMT+05:30) Mumbai' => 'Asia/Calcutta',
'(GMT+05:30) New Delhi' => 'Asia/Calcutta',
'(GMT+05:30) Sri Jayawardenepura' => 'Asia/Calcutta',
'(GMT+05:45) Kathmandu' => 'Asia/Katmandu',
'(GMT+06:00) Almaty' => 'Asia/Almaty',
'(GMT+06:00) Astana' => 'Asia/Dhaka',
'(GMT+06:00) Dhaka' => 'Asia/Dhaka',
'(GMT+06:00) Ekaterinburg' => 'Asia/Yekaterinburg',
'(GMT+06:30) Rangoon' => 'Asia/Rangoon',
'(GMT+07:00) Bangkok' => 'Asia/Bangkok',
'(GMT+07:00) Hanoi' => 'Asia/Bangkok',
'(GMT+07:00) Jakarta' => 'Asia/Jakarta',
'(GMT+07:00) Novosibirsk' => 'Asia/Novosibirsk',
'(GMT+08:00) Beijing' => 'Asia/Hong_Kong',
'(GMT+08:00) Chongqing' => 'Asia/Chongqing',
'(GMT+08:00) Hong Kong' => 'Asia/Hong_Kong',
'(GMT+08:00) Krasnoyarsk' => 'Asia/Krasnoyarsk',
'(GMT+08:00) Kuala Lumpur' => 'Asia/Kuala_Lumpur',
'(GMT+08:00) Perth' => 'Australia/Perth',
'(GMT+08:00) Singapore' => 'Asia/Singapore',
'(GMT+08:00) Taipei' => 'Asia/Taipei',
'(GMT+08:00) Ulaan Bataar' => 'Asia/Ulan_Bator',
'(GMT+08:00) Urumqi' => 'Asia/Urumqi',
'(GMT+09:00) Irkutsk' => 'Asia/Irkutsk',
'(GMT+09:00) Osaka' => 'Asia/Tokyo',
'(GMT+09:00) Sapporo' => 'Asia/Tokyo',
'(GMT+09:00) Seoul' => 'Asia/Seoul',
'(GMT+09:00) Tokyo' => 'Asia/Tokyo',
'(GMT+09:30) Adelaide' => 'Australia/Adelaide',
'(GMT+09:30) Darwin' => 'Australia/Darwin',
'(GMT+10:00) Brisbane' => 'Australia/Brisbane',
'(GMT+10:00) Canberra' => 'Australia/Canberra',
'(GMT+10:00) Guam' => 'Pacific/Guam',
'(GMT+10:00) Hobart' => 'Australia/Hobart',
'(GMT+10:00) Melbourne' => 'Australia/Melbourne',
'(GMT+10:00) Port Moresby' => 'Pacific/Port_Moresby',
'(GMT+10:00) Sydney' => 'Australia/Sydney',
'(GMT+10:00) Yakutsk' => 'Asia/Yakutsk',
'(GMT+11:00) Vladivostok' => 'Asia/Vladivostok',
'(GMT+12:00) Auckland' => 'Pacific/Auckland',
'(GMT+12:00) Fiji' => 'Pacific/Fiji',
'(GMT+12:00) International Date Line West' => 'Pacific/Kwajalein',
'(GMT+12:00) Kamchatka' => 'Asia/Kamchatka',
'(GMT+12:00) Magadan' => 'Asia/Magadan',
'(GMT+12:00) Marshall Is.' => 'Pacific/Fiji',
'(GMT+12:00) New Caledonia' => 'Asia/Magadan',
'(GMT+12:00) Solomon Is.' => 'Asia/Magadan',
'(GMT+12:00) Wellington' => 'Pacific/Auckland',
'(GMT+13:00) Nuku\'alofa' => 'Pacific/Tongatapu'
);
?>   

How to cancel/abort jQuery AJAX request?

jQuery: Use this as a starting point - as inspiration. I solved it like this: (this is not a perfect solution, it just aborts the last instance and is WIP code)

var singleAjax = function singleAjax_constructor(url, params) {
    // remember last jQuery's get request
    if (this.lastInstance) {
        this.lastInstance.abort();  // triggers .always() and .fail()
        this.lastInstance = false;
    }

    // how to use Deferred : http://api.jquery.com/category/deferred-object/
    var $def = new $.Deferred();

    // pass the deferrer's request handlers into the get response handlers
    this.lastInstance = $.get(url, params)
        .fail($def.reject)         // triggers .always() and .fail()
        .success($def.resolve);    // triggers .always() and .done()

    // return the deferrer's "control object", the promise object
    return $def.promise();
}


// initiate first call
singleAjax('/ajax.php', {a: 1, b: 2})
    .always(function(a,b,c) {console && console.log(a,b,c);});

// second call kills first one
singleAjax('/ajax.php', {a: 1, b: 2})
    .always(function(a,b,c) {console && console.log(a,b,c);});
    // here you might use .always() .fail() .success() etc.

Laravel Eloquent get results grouped by days

this way work properly and I used it in many projects! for example I get data of views the last 30 days:

$viewsData = DB::table('page_views')
    ->where('page_id', $page->id)
    ->whereDate('created_at', '>=', now()->subDays(30))
    ->select(DB::raw('DATE(created_at) as data'), DB::raw('count(*) as views'))
    ->groupBy('date')
    ->get();

If you want to get the number of views based on different IPs, you can use the DISTINCT like below :

$viewsData = DB::table('page_views')
    ->where('page_id', $page->id)
    ->whereDate('created_at', '>=', now()->subDays(30))
    ->select(DB::raw('DATE(created_at) as data'), DB::raw('count(DISTINCT user_ip) as visitors'))
    ->groupBy('date')
    ->get();

You can easily customize it by manipulating the columns name

apache redirect from non www to www

-If you host multiple domain names (Optional)

-If all those domain names are using https (as they should)

-if you want all those domain names to use www dot domainName

This will avoid doble redirection (http://non www to http://www and then to https://www)

<VirtualHost *:80>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^(.*)$ https://www.%1$1 [R=301,L]
</VirtualHost>

And

<VirtualHost *:443>
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^(.*)$ https://www.%{HTTP_HOST}$1 [R=301,L]
</VirtualHost>

You should change the redirection code 301 to the most convenient one

Django - Did you forget to register or load this tag?

{% load static %}

Please add this template tag on top of the HTML or base HTML file

Why and when to use angular.copy? (Deep Copy)

Use angular.copy when assigning value of object or array to another variable and that object value should not be changed.

Without deep copy or using angular.copy, changing value of property or adding any new property update all object referencing that same object.

_x000D_
_x000D_
var app = angular.module('copyExample', []);_x000D_
app.controller('ExampleController', ['$scope',_x000D_
  function($scope) {_x000D_
    $scope.printToConsole = function() {_x000D_
      $scope.main = {_x000D_
        first: 'first',_x000D_
        second: 'second'_x000D_
      };_x000D_
_x000D_
      $scope.child = angular.copy($scope.main);_x000D_
      console.log('Main object :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object with angular.copy :');_x000D_
      console.log($scope.child);_x000D_
_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('New Child object :')_x000D_
      console.log($scope.child);_x000D_
      console.log('Main object after child change and using angular.copy :');_x000D_
      console.log($scope.main);_x000D_
      console.log('Assing main object without copy and updating child');_x000D_
_x000D_
      $scope.child = $scope.main;_x000D_
      $scope.child.first = 'last';_x000D_
      console.log('Main object after update:');_x000D_
      console.log($scope.main);_x000D_
      console.log('Child object after update:');_x000D_
      console.log($scope.child);_x000D_
    }_x000D_
  }_x000D_
]);_x000D_
_x000D_
// Basic object assigning example_x000D_
_x000D_
var main = {_x000D_
  first: 'first',_x000D_
  second: 'second'_x000D_
};_x000D_
var one = main; // same as main_x000D_
var two = main; // same as main_x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same_x000D_
_x000D_
two = {_x000D_
  three: 'three'_x000D_
}; // two changed but one and main remains same_x000D_
console.log('main :' + JSON.stringify(main)); // one and main are same_x000D_
console.log('one :' + JSON.stringify(one)); // one and main are same_x000D_
console.log('two :' + JSON.stringify(two)); // two is changed_x000D_
_x000D_
two = main; // same as main_x000D_
_x000D_
two.first = 'last'; // change value of object's property so changed value of all object property _x000D_
_x000D_
console.log('main :' + JSON.stringify(main)); // All object are same with new value_x000D_
console.log('one :' + JSON.stringify(one)); // All object are same with new value_x000D_
console.log('two :' + JSON.stringify(two)); // All object are same with new value
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
_x000D_
<div ng-app="copyExample" ng-controller="ExampleController">_x000D_
  <button ng-click='printToConsole()'>Explain</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

If you are using Cloudflare then this is always the Cloudflare IP address from the node which is serving you.

In this case you get the real IP address from the $_SERVER['HTTP_FORWARDED_FOR'] entry as described in the the other answers.

How to use patterns in a case statement?

Brace expansion doesn't work, but *, ? and [] do. If you set shopt -s extglob then you can also use extended pattern matching:

  • ?() - zero or one occurrences of pattern
  • *() - zero or more occurrences of pattern
  • +() - one or more occurrences of pattern
  • @() - one occurrence of pattern
  • !() - anything except the pattern

Here's an example:

shopt -s extglob
for arg in apple be cd meet o mississippi
do
    # call functions based on arguments
    case "$arg" in
        a*             ) foo;;    # matches anything starting with "a"
        b?             ) bar;;    # matches any two-character string starting with "b"
        c[de]          ) baz;;    # matches "cd" or "ce"
        me?(e)t        ) qux;;    # matches "met" or "meet"
        @(a|e|i|o|u)   ) fuzz;;   # matches one vowel
        m+(iss)?(ippi) ) fizz;;   # matches "miss" or "mississippi" or others
        *              ) bazinga;; # catchall, matches anything not matched above
    esac
done

What exactly are DLL files, and how do they work?

Let’s say you are making an executable that uses some functions found in a library.

If the library you are using is static, the linker will copy the object code for these functions directly from the library and insert them into the executable.

Now if this executable is run it has every thing it needs, so the executable loader just loads it into memory and runs it.

If the library is dynamic the linker will not insert object code but rather it will insert a stub which basically says this function is located in this DLL at this location.

Now if this executable is run, bits of the executable are missing (i.e the stubs) so the loader goes through the executable fixing up the missing stubs. Only after all the stubs have been resolved will the executable be allowed to run.

To see this in action delete or rename the DLL and watch how the loader will report a missing DLL error when you try to run the executable.

Hence the name Dynamic Link Library, parts of the linking process is being done dynamically at run time by the executable loader.

One a final note, if you don't link to the DLL then no stubs will be inserted by the linker, but Windows still provides the GetProcAddress API that allows you to load an execute the DLL function entry point long after the executable has started.

C# how to change data in DataTable?

Try the SetField method:

table.Rows[i].SetField(column, value);
table.Rows[i].SetField(columnIndex, value);
table.Rows[i].SetField(columnName, value);

This should get the job done and is a bit "cleaner" than using Rows[i][j].

$watch an object

The reason why your code doesn't work is because $watch by default does reference check. So in a nutshell it make sure that the object which is passed to it is new object. But in your case you are just modifying some property of form object not creating a new one. In order to make it work you can pass true as the third parameter.

$scope.$watch('form', function(newVal, oldVal){
    console.log('invoked');
}, true);

It will work but You can use $watchCollection which will be more efficient then $watch because $watchCollection will watch for shallow properties on form object. E.g.

$scope.$watchCollection('form', function (newVal, oldVal) {
    console.log(newVal, oldVal);
});

What is the difference between PUT, POST and PATCH?

The below definition is from the real world example.

Example Overview
For every client data, we are storing an identifier to find that client data and we will send back that identifier to that client for reference.

  1. POST

    • If the Client sends data without any identifier using the POST method then we will store it and assign a new identifier.
    • If the Client again sends the same data without any identifier using the POST method, then we will store it and assign a new identifier.
    • Note: Duplication is allowed here
  2. PUT

    • If the Client Sends data with an identifier then we will check whether that identifier exists. If the identifier exists we will update data else we will create it and assign a new identifier.
  3. PATCH

    • If the Client Sends data with an identifier then we will check whether that identifier exists. If the identifier exists we will update data else we will throw an exception.

Note: On Put Method, We are not throwing an exception if an identifier is not found. But in Patch method, we are throwing an exception if the identifier is not found.

Do let me know if you have any queries on the above.

Cannot load 64-bit SWT libraries on 32-bit JVM ( replacing SWT file )

Eclipse is launching your application with whatever JRE you defined in your launch configuration. Since you're running the 32-bit Eclipse, you're running/debugging against its 32-bit SWT libraries, and you'll need to run a 32-bit JRE.

Your 64-bit JRE is, for whatever reason, your default Installed JRE.

To change this, first make sure you have a 32-bit JRE configured in the Installed JREs preference. Go to Window -> Preferences and navigate to Java -> Installed JREs:

Installed JREs

You can click Add and navigate to your 32-bit JVM's JAVA_HOME to add it.

Then in your Run Configuration, find your Eclipse Application and make sure the Runtime JRE is set to the 32-bit JRE you just configured:

Run Configuration

(Note the combobox that is poorly highlighted.)

Don't try replacing SWT jars, that will likely end poorly.

HTML select dropdown list

If you want to achieve the same for the jquery-ui selectmenu control then you have to set 'display: none' in the open event handler and add '-menu' to the id string.

<select id="myid">
<option value="" disabled="disabled" selected="selected">Please select     name</option>
 <option value="Tom">Tom</option>
 <option value="Marry">Mary</option>
 <option value="Jane">Jane</option>
 <option value="Harry">Harry</option>
 </select>

$('select#listsTypeSelect').selectmenu({
  change: function( event, data ) {
    alert($(this).val());
},
open: function( event, ui ) {
    $('ul#myid-menu li:first-child').css('display', 'none');
}
});

Setting Java heap space under Maven 2 on Windows

It worked - To change in Eclipse, go to Window -> Preferences -> Java -> Installed JREs. Select the checked JRE/JDK and click edit.

Default VM Arguments = -Xms128m -Xmx1024m

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

If you happened to run npm install command on Windows, first make sure you open your command prompt with Administration Privileges. That's what solved the issue for me.

Modifying CSS class property values on the fly with JavaScript / jQuery

Like @benvie said, its more efficient to change a style sheet rather than using jQuery.css (which will loop through all of the elements in the set). It is also important not to add a new style to the head every time the function is called because it will create a memory leak and thousands of CSS rules that have to be individually applied by the browser. I would do something like this:

//Add the stylesheet once and store a cached jQuery object
var $style = $("<style type='text/css'>").appendTo('head'); 

function onResize() {
    var css = "\
        .someClass {\
            left:   "+leftVal+";\
            width:  "+widthVal+";\
            height: "+heightVal+";\
        }";

    $style.html(css);
}

This solution will change your styles by modifying the DOM only once per resize. Note that for effective js minification and compression, you probably don't want to pretty-print the css, but I did for clarity.

How to cache Google map tiles for offline usage?

On Android platforms, Oruxmaps (http://www.oruxmaps.com) does a great job at caching all WMS sources. It is available in the play store. I use it daily in remote areas without any connectivity, works like a charm.

Git Stash vs Shelve in IntelliJ IDEA

When using JetBrains IDE's with Git, "stashing and unstashing actions are supported in addition to shelving and unshelving. These features have much in common; the major difference is in the way patches are generated and applied. Shelve can operate with either individual files or bunch of files, while Stash can only operate with a whole bunch of changed files at once. Here are some more details on the differences between them."

struct in class

You should define the struct out of the class like this:

#include <iostream>
using namespace std;
struct X
{
        int v;
};
class E
{
public: 
      X var;
};

int main(){

E object;
object.var.v=10; 

return 0;
}

Is Unit Testing worth the effort?

I wrote a very large blog post about the topic. I've found that unit testing alone isn't worth the work and usually gets cut when deadlines get closer.

Instead of talking about unit testing from the "test-after" verification point of view, we should look at the true value found when you set out to write a spec/test/idea before the implementation.

This simple idea has changed the way I write software and I wouldn't go back to the "old" way.

How test first development changed my life

Paging UICollectionView by cells, not screen

Here is the optimised solution in Swift5, including handling the wrong indexPath. - Michael Lin Liu

  • Step1. Get the indexPath of the current cell.
  • Step2. Detect the velocity when scroll.
  • Step3. Increase the indexPath's row when the velocity is increased.
  • Step4. Tell the collection view to scroll to the next item
    func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
        
        targetContentOffset.pointee = scrollView.contentOffset
        
        //M: Get the first visiable item's indexPath from visibaleItems.
        var indexPaths = *YOURCOLLECTIONVIEW*.indexPathsForVisibleItems
        indexPaths.sort()
        var indexPath = indexPaths.first!

        //M: Use the velocity to detect the paging control movement.
        //M: If the movement is forward, then increase the indexPath.
        if velocity.x > 0{
            indexPath.row += 1
            
            //M: If the movement is in the next section, which means the indexPath's row is out range. We set the indexPath to the first row of the next section.
            if indexPath.row == *YOURCOLLECTIONVIEW*.numberOfItems(inSection: indexPath.section){
                indexPath.row = 0
                indexPath.section += 1
            }
        }
        else{
            //M: If the movement is backward, the indexPath will be automatically changed to the first visiable item which is indexPath.row - 1. So there is no need to write the logic.
        }
        
        //M: Tell the collection view to scroll to the next item.
        *YOURCOLLECTIONVIEW*.scrollToItem(at: indexPath, at: .left, animated: true )
 }

Histogram using gnuplot?

Be very careful: all of the answers on this page are implicitly taking the decision of where the binning starts - the left-hand edge of the left-most bin, if you like - out of the user's hands. If the user is combining any of these functions for binning data with his/her own decision about where binning starts (as is done on the blog which is linked to above) the functions above are all incorrect. With an arbitrary starting point for binning 'Min', the correct function is:

bin(x) = width*(floor((x-Min)/width)+0.5) + Min

You can see why this is correct sequentially (it helps to draw a few bins and a point somewhere in one of them). Subtract Min from your data point to see how far into the binning range it is. Then divide by binwidth so that you're effectively working in units of 'bins'. Then 'floor' the result to go to the left-hand edge of that bin, add 0.5 to go to the middle of the bin, multiply by the width so that you're no longer working in units of bins but in an absolute scale again, then finally add back on the Min offset you subtracted at the start.

Consider this function in action:

Min = 0.25 # where binning starts
Max = 2.25 # where binning ends
n = 2 # the number of bins
width = (Max-Min)/n # binwidth; evaluates to 1.0
bin(x) = width*(floor((x-Min)/width)+0.5) + Min

e.g. the value 1.1 truly falls in the left bin:

  • this function correctly maps it to the centre of the left bin (0.75);
  • Born2Smile's answer, bin(x)=width*floor(x/width), incorrectly maps it to 1;
  • mas90's answer, bin(x)=width*floor(x/width) + binwidth/2.0, incorrectly maps it to 1.5.

Born2Smile's answer is only correct if the bin boundaries occur at (n+0.5)*binwidth (where n runs over integers). mas90's answer is only correct if the bin boundaries occur at n*binwidth.

Removing leading and trailing spaces from a string

neat and clean

 void trimLeftTrailingSpaces(string &input) {
        input.erase(input.begin(), find_if(input.begin(), input.end(), [](int ch) {
            return !isspace(ch);
        }));
    }

    void trimRightTrailingSpaces(string &input) {
        input.erase(find_if(input.rbegin(), input.rend(), [](int ch) {
            return !isspace(ch);
        }).base(), input.end());
    }

disable Bootstrap's Collapse open/close animation

If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...

Just add this somewhere in your code:

$(document).ready(
    $('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
        e.preventDefault();
    }),
    $('[data-toggle="collapse"]').on('click', function(e) {
        e.preventDefault();
        $($(this).data('target')).toggleClass('in');
    })
);

What are the differences between using the terminal on a mac vs linux?

If you did a new or clean install of OS X version 10.3 or more recent, the default user terminal shell is bash.

Bash is essentially an enhanced and GNU freeware version of the original Bourne shell, sh. If you have previous experience with bash (often the default on GNU/Linux installations), this makes the OS X command-line experience familiar, otherwise consider switching your shell either to tcsh or to zsh, as some find these more user-friendly.

If you upgraded from or use OS X version 10.2.x, 10.1.x or 10.0.x, the default user shell is tcsh, an enhanced version of csh('c-shell'). Early implementations were a bit buggy and the programming syntax a bit weird so it developed a bad rap.

There are still some fundamental differences between mac and linux as Gordon Davisson so aptly lists, for example no useradd on Mac and ifconfig works differently.

The following table is useful for knowing the various unix shells.

sh      The original Bourne shell   Present on every unix system 
ksh     Original Korn shell         Richer shell programming environment than sh 
csh     Original C-shell            C-like syntax; early versions buggy 
tcsh    Enhanced C-shell            User-friendly and less buggy csh implementation 
bash    GNU Bourne-again shell      Enhanced and free sh implementation 
zsh     Z shell                     Enhanced, user-friendly ksh-like shell

You may also find these guides helpful:

http://homepage.mac.com/rgriff/files/TerminalBasics.pdf

http://guides.macrumors.com/Terminal
http://www.ofb.biz/safari/article/476.html

On a final note, I am on Linux (Ubuntu 11) and Mac osX so I use bash and the thing I like the most is customizing the .bashrc (source'd from .bash_profile on OSX) file with aliases, some examples below. I now placed all my aliases in a separate .bash_aliases file and include it with:

if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

in the .bashrc or .bash_profile file.

Note that this is an example of a mac-linux difference because on a Mac you can't have the --color=auto. The first time I did this (without knowing) I redefined ls to be invalid which was a bit alarming until I removed --auto-color !

You may also find https://unix.stackexchange.com/q/127799/10043 useful

# ~/.bash_aliases
# ls variants
#alias l='ls -CF' 
alias la='ls -A' 
alias l='ls -alFtr' 
alias lsd='ls -d .*' 
# Various
alias h='history | tail'
alias hg='history | grep'
alias mv='mv -i' 
alias zap='rm -i'
# One letter quickies:
alias p='pwd'
alias x='exit'
alias {ack,ak}='ack-grep'
# Directories
alias s='cd ..'
alias play='cd ~/play/'
# Rails
alias src='script/rails console'
alias srs='script/rails server'
alias raked='rake db:drop db:create db:migrate db:seed' 
alias rvm-restart='source '\''/home/durrantm/.rvm/scripts/rvm'\'''
alias rrg='rake routes | grep '
alias rspecd='rspec --drb '
#
# DropBox - syncd
WORKBASE="~/Dropbox/97_2012/work"
alias work="cd $WORKBASE"
alias code="cd $WORKBASE/ror/code"
#
# DropNot - NOT syncd !
WORKBASE_GIT="~/Dropnot"
alias {dropnot,not}="cd $WORKBASE_GIT"
alias {webs,ww}="cd $WORKBASE_GIT/webs"
alias {setups,docs}="cd $WORKBASE_GIT/setups_and_docs"
alias {linker,lnk}="cd $WORKBASE_GIT/webs/rails_v3/linker"
#
# git
alias {gsta,gst}='git status' 
# Warning: gst conflicts with gnu-smalltalk (when used).
alias {gbra,gb}='git branch'
alias {gco,go}='git checkout'
alias {gcob,gob}='git checkout -b '
alias {gadd,ga}='git add '
alias {gcom,gc}='git commit'
alias {gpul,gl}='git pull '
alias {gpus,gh}='git push '
alias glom='git pull origin master'
alias ghom='git push origin master'
alias gg='git grep '
#
# vim
alias v='vim'
#
# tmux
alias {ton,tn}='tmux set -g mode-mouse on'
alias {tof,tf}='tmux set -g mode-mouse off'
#
# dmc
alias {dmc,dm}='cd ~/Dropnot/webs/rails_v3/dmc/'
alias wf='cd ~/Dropnot/webs/rails_v3/dmc/dmWorkflow'
alias ws='cd ~/Dropnot/webs/rails_v3/dmc/dmStaffing'

Load vs. Stress testing

Load testing = putting a specified amount of load on the server for certain amount of time. 100 simultaneous users for 10 minutes. Ensure stability of software. Stress testing = increasing the amount of load steadily until the software crashes. 10 simultaneous users increasing every 2 minutes until the server crashes.

To make a comparison to weight lifting: You "max" your weight to see what you can do for 1 rep (stress testing) and then on regular workouts you do 85% of your max value for 3 sets of 10 reps (load testing)

How to display JavaScript variables in a HTML page without document.write

If you want to avoid innerHTML you can use the DOM methods to construct elements and append them to the page.

?var element = document.createElement('div');
var text = document.createTextNode('This is some text');
element.appendChild(text);
document.body.appendChild(element);??????

How to set text size of textview dynamically for different screens

After long time stuck this issue, finally solved like this

textView.setTextSize(TypedValue.COMPLEX_UNIT_PX,
              getResources().getDimension(R.dimen.textsize));

create folder like this res/values/dimens.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>

  <dimen name="textsize">8sp</dimen>

 </resources>

How to copy multiple files in one layer using a Dockerfile?

COPY README.md package.json gulpfile.js __BUILD_NUMBER ./

or

COPY ["__BUILD_NUMBER", "README.md", "gulpfile", "another_file", "./"]

You can also use wildcard characters in the sourcefile specification. See the docs for a little more detail.

Directories are special! If you write

COPY dir1 dir2 ./

that actually works like

COPY dir1/* dir2/* ./

If you want to copy multiple directories (not their contents) under a destination directory in a single command, you'll need to set up the build context so that your source directories are under a common parent and then COPY that parent.

Get list of a class' instance methods

TestClass.instance_methods

or without all the inherited methods

TestClass.instance_methods - Object.methods

(Was 'TestClass.methods - Object.methods')

How to copy selected files from Android with adb pull

You can move your files to other folder and then pull whole folder.

adb shell mkdir /sdcard/tmp
adb shell mv /sdcard/mydir/*.jpg /sdcard/tmp # move your jpegs to temporary dir
adb pull /sdcard/tmp/ # pull this directory (be sure to put '/' in the end)
adb shell mv /sdcard/tmp/* /sdcard/mydir/ # move them back
adb shell rmdir /sdcard/tmp # remove temporary directory

Normalizing a list of numbers in Python

Use scikit-learn:

from sklearn.preprocessing import MinMaxScaler
data = np.array([1,2,3]).reshape(-1, 1)
scaler = MinMaxScaler()
scaler.fit(data)
print(scaler.transform(data))

Apple Cover-flow effect using jQuery or other library?

I tried using the the Jack's Asylum cover flow but it wouldn't let me easily remove and re-add an entire coverflow. I eventually found http://finnrudolph.de/ImageFlow and not only is it more reliable, it's easier to hook into, uses less markup, and doesn't jitter when flipping through images. It's by far the best I've found, and I've tried several on this page.

Is mathematics necessary for programming?

Two things come to mind:

  • Context is all-important. If you're a games programmer or in an engineering discipline, then math may be vital for your job. I do database and web development, therefore high school-level math is fine for me.
  • You are very likely to be reusing someone else's pre-built math code rather than reinventing the wheel, especially in fields like encryption and compression. (This may also apply if you're in games development using a third party physics tool or a 3D engine.) Having a framework of tried and tested routines for use in your programs prevents errors and potential security weaknesses - definitely a good thing.

Converting Array to List

If you are dealing with String[] instead of int[], We can use

ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(StringArray));

npm start error with create-react-app

For me it was simply that I hadn't added react-scripts to the project so:

npm i -S react-scripts

If this doesn't work, then rm node_modules as suggested by others

rm -r node_modules
npm i

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

The most likely explanations for that error are:

  1. The file you are attempting to load is not an executable file. CreateProcess requires you to provide an executable file. If you wish to be able to open any file with its associated application then you need ShellExecute rather than CreateProcess.
  2. There is a problem loading one of the dependencies of the executable, i.e. the DLLs that are linked to the executable. The most common reason for that is a mismatch between a 32 bit executable and a 64 bit DLL, or vice versa. To investigate, use Dependency Walker's profile mode to check exactly what is going wrong.

Reading down to the bottom of the code, I can see that the problem is number 1.

How do I copy SQL Azure database to my local development server?

There are multiple ways to do this:

  1. Using SSIS (SQL Server Integration Services). It only imports data in your table. Column properties, constraints, keys, indices, stored procedures, triggers, security settings, users, logons, etc. are not transferred. However it is very simple process and can be done simply by going through wizard in SQL Server Management Studio.
  2. Using combination of SSIS and DB creation scripts. This will get you data and all missing metadata that is not transferred by SSIS. This is also very simple. First transfer data using SSIS (see instructions below), then create DB Create script from SQL Azure database, and re-play it on your local database.
  3. Finally, you can use Import/Export service in SQL Azure. This transfers data (with a schema objects) to Azure Blob Storage as a BACPAC. You will need an Azure Storage account and do this in Azure web portal. It is as simple as pressing an "Export" button in the Azure web portal when you select the database you want to export. The downside is that it is only manual procedure, I don't know a way to automate this through tools or scripts -- at least the first part that requires a click on the web page.

Manual procedure for method #1 (using SSIS) is the following:

  • In Sql Server Management Studio (SSMS) create new empty database on your local SQL instance.
  • Choose Import Data from context menu (right click the database -> Tasks -> Import data...)
  • Type in connection parameters for the source (SQL Azure). Select ".Net Framework Data Provider for SqlServer" as a provider.
  • Choose existing empty local database as destination.
  • Follow the wizard -- you will be able to select tables data you want to copy. You can choose to skip any of the tables you don't need. E.g. if you keep application logs in database, you probably don't need it in your backup.

You can automate it by creating SSIS package and re-executing it any time you like to re-import the data. Note that you can only import using SSIS to a clean DB, you cannot do incremental updates to your local database once you already done it once.

Method #2 (SSID data plus schema objects) is very simple. First go though a steps described above, then create DB Creation script (righ click on database in SSMS, choose Generate Scripts -> Database Create). Then re-play this script on your local database.

Method #3 is described in the Blog here: http://dacguy.wordpress.com/2012/01/24/sql-azure-importexport-service-has-hit-production/. There is a video clip with the process of transferring DB contents to Azure Blob storage as BACPAC. After that you can copy the file locally and import it to your SQL instance. Process of importing BACPAC to Data-Tier application is described here: http://msdn.microsoft.com/en-us/library/hh710052.aspx.

How to make a GUI for bash scripts?

If you have Qt/KDE installed, you can use kdialog, which pops up a Qt dialog window. You can easily specify to display a Yes/No dialog, OK/Cancel, simple text input, password input etc. You then have access to the return values from these dialogs at the shell.

C# Checking if button was clicked

These helped me a lot: I wanted to save values from my gridview, and it was reloading my gridview /overriding my new values, as i have IsPostBack inside my PageLoad.

if (HttpContext.Current.Request["MYCLICKEDBUTTONID"] == null)
{
   //Do not reload the gridview.

}
else
{
   reload my gridview.
}

SOURCE: http://bytes.com/topic/asp-net/answers/312809-please-help-how-identify-button-clicked

How do I get next month date from today's date and insert it in my database?

If you want a specific date in next month, you can do this:

// Calculate the timestamp
$expire = strtotime('first day of +1 month');

// Format the timestamp as a string
echo date('m/d/Y', $expire);

Note that this actually works more reliably where +1 month can be confusing. For example...

Current Day   | first day of +1 month     | +1 month
---------------------------------------------------------------------------
2015-01-01    | 2015-02-01                | 2015-02-01
2015-01-30    | 2015-02-01                | 2015-03-02  (skips Feb)
2015-01-31    | 2015-02-01                | 2015-03-03  (skips Feb)
2015-03-31    | 2015-04-01                | 2015-05-01  (skips April)
2015-12-31    | 2016-01-01                | 2016-01-31

Download file of any type in Asp.Net MVC using FileResult?

The MVC framework supports this natively. The System.Web.MVC.Controller.File controller provides methods to return a file by name/stream/array.

For example using a virtual path to the file you could do the following.

return File(virtualFilePath, System.Net.Mime.MediaTypeNames.Application.Octet,  Path.GetFileName(virtualFilePath));

How to Add a Dotted Underline Beneath HTML Text

Reformatted the answer by @epascarello:

_x000D_
_x000D_
u.dotted {_x000D_
  border-bottom: 1px dashed #999;_x000D_
  text-decoration: none;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<u class="dotted">I like cheese</u>
_x000D_
_x000D_
_x000D_

android: data binding error: cannot find symbol class

Sometimes the reason of these errors are not the DataBinding itself, but some other part of our code. In my case I had an error in Room database so the compiler couldn't generate the binding classes and it gives me these errors.

According to Google:

Previous versions of the data binding compiler generated the binding classes in the same step that compiles your managed code. If your managed code fails to compile, you might get multiple errors reporting that the binding classes aren't found. The new data binding compiler prevents these errors by generating the binding classes before the managed compiler builds your app.

So to enable new data binding compiler, add the following option to your gradle.properties file:

android.databinding.enableV2=true

You can also enable the new compiler in your gradle command by adding the following parameter:

-Pandroid.databinding.enableV2=true

Note that the new compiler in Android Studio version 3.2 is enabled by default.

How do I disable form fields using CSS?

You can't use CSS to disable Textbox. solution would be HTML Attribute.

disabled="disabled"

How can I count the occurrences of a list item?

If you want to count all values at once you can do it very fast using numpy arrays and bincount as follows

import numpy as np
a = np.array([1, 2, 3, 4, 1, 4, 1])
np.bincount(a)

which gives

>>> array([0, 3, 1, 1, 2])

Configure active profile in SpringBoot via Maven

You should use the Spring Boot Maven Plugin:

<project>  
  ...
  <build>
    ...
    <plugins>
      ...
      <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.5.1.RELEASE</version>
        <configuration>
          <profiles>
            <profile>foo</profile>
            <profile>bar</profile>
          </profiles>
        </configuration>
        ...
      </plugin>
      ...
    </plugins>
    ...
  </build>
  ...
</project>

What is the difference between DSA and RSA?

And in addition to the above nice answers.

  • DSA uses Discrete logarithm.
  • RSA uses Integer Factorization.

RSA stands for Ron Rivest, Adi Shamir and Leonard Adleman.

insert a NOT NULL column to an existing table

Other SQL implementations have similar restrictions. The reason is that adding a column requires adding values for that column (logically, even if not physically), which default to NULL. If you don't allow NULL, and don't have a default, what is the value going to be?

Since SQL Server supports ADD CONSTRAINT, I'd recommend Pavel's approach of creating a nullable column, and then adding a NOT NULL constraint after you've filled it with non-NULL values.

How to construct a set out of list items in python?

Simply put the line:

new_list = set(your_list)

How do I get AWS_ACCESS_KEY_ID for Amazon?

  1. Open the AWS Console
  2. Click on your username near the top right and select My Security Credentials
  3. Click on Users in the sidebar
  4. Click on your username
  5. Click on the Security Credentials tab
  6. Click Create Access Key
  7. Click Show User Security Credentials

How to use img src in vue.js?

Try this:

<img v-bind:src="'/media/avatars/' + joke.avatar" /> 

Don't forget single quote around your path string. also in your data check you have correctly defined image variable.

joke: {
  avatar: 'image.jpg'
}

A working demo here: http://jsbin.com/pivecunode/1/edit?html,js,output

Docker: Multiple Dockerfiles in project

When working on a project that requires the use of multiple dockerfiles, simply create each dockerfile in a separate directory. For instance,

app/ db/

Each of the above directories will contain their dockerfile. When an application is being built, docker will search all directories and build all dockerfiles.

Return the characters after Nth character in a string

Since there is the [vba] tag, split is also easy:

str1 = "001 baseball"
str2 = Split(str1)

Then use str2(1).

Split array into two parts without for loop in java

You can use System.arraycopy().

int[] source = new int[1000];

int[] part1 = new int[500];
int[] part2 = new int[500];

//              (src   , src-offset  , dest , offset, count)
System.arraycopy(source, 0           , part1, 0     , part1.length);
System.arraycopy(source, part1.length, part2, 0     , part2.length);

Push to GitHub without a password using ssh-key

Additionally for gists, it seems you must leave out the username

git remote set-url origin [email protected]:<Project code>

How do ports work with IPv6?

They're the same, aren't they? Now I'm losing confidence in myself but I really thought IPv6 was just an addressing change. TCP and UDP are still addressed as they are under IPv4.

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

Remove Unnamed columns in pandas dataframe

The approved solution doesn't work in my case, so my solution is the following one:

    ''' The column name in the example case is "Unnamed: 7"
 but it works with any other name ("Unnamed: 0" for example). '''

        df.rename({"Unnamed: 7":"a"}, axis="columns", inplace=True)

        # Then, drop the column as usual.

        df.drop(["a"], axis=1, inplace=True)

Hope it helps others.

jQuery get values of checked checkboxes into array

var idsArr = [];

$('#tableID').find('input[type=checkbox]:checked').each(function() {
    idsArr .push(this.value);
});

console.log(idsArr);

Singular matrix issue with Numpy

The matrix you pasted

[[   1,    8,   50],
 [   8,   64,  400],
 [  50,  400, 2500]]

Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)

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

Git - Ignore node_modules folder everywhere

Add this

node_modules/

to .gitignore file to ignore all directories called node_modules in current folder and any subfolders

How to Create an excel dropdown list that displays text with a numeric hidden value

Data validation drop down

There is a list option in Data validation. If this is combined with a VLOOKUP formula you would be able to convert the selected value into a number.

The steps in Excel 2010 are:

  • Create your list with matching values.
  • On the Data tab choose Data Validation
  • The Data validation form will be displayed
  • Set the Allow dropdown to List
  • Set the Source range to the first part of your list
  • Click on OK (User messages can be added if required)

In a cell enter a formula like this

=VLOOKUP(A2,$D$3:$E$5,2,FALSE)

which will return the matching value from the second part of your list.

Screenshot of Data validation list

Form control drop down

Alternatively, Form controls can be placed on a worksheet. They can be linked to a range and return the position number of the selected value to a specific cell.

The steps in Excel 2010 are:

  • Create your list of data in a worksheet
  • Click on the Developer tab and dropdown on the Insert option
  • In the Form section choose Combo box or List box
  • Use the mouse to draw the box on the worksheet
  • Right click on the box and select Format control
  • The Format control form will be displayed
  • Click on the Control tab
  • Set the Input range to your list of data
  • Set the Cell link range to the cell where you want the number of the selected item to appear
  • Click on OK

Screenshot of form control

How to create a new img tag with JQuery, with the src and id from a JavaScript object?

var img = $('<img />', { 
  id: 'Myid',
  src: 'MySrc.gif',
  alt: 'MyAlt'
});
img.appendTo($('#YourDiv'));

How to add a custom button to the toolbar that calls a JavaScript function?

This article may be useful too http://mito-team.com/article/2012/collapse-button-for-ckeditor-for-drupal

There are code samples and step-by-step guide about building your own CKEditor plugin with custom button.

How can I wait In Node.js (JavaScript)? l need to pause for a period of time

The shortest solution without any dependencies:

await new Promise(resolve => setTimeout(resolve, 5000));

Getting Textbox value in Javascript

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

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

use the help of this, hope it will be usefull

Two constructors

Let's, just as example:

public class Test {     public Test() {         System.out.println("NO ARGS");     }      public Test(String s) {         this();         System.out.println("1 ARG");     }      public static void main(String args[])     {         Test t = new Test("s");     } } 

It will print

>>> NO ARGS >>> 1 ARG 

The correct way to call the constructor is by:

this(); 

Difference between single and double quotes in Bash

Others explained very well and just want to give with simple examples.

Single quotes can be used around text to prevent the shell from interpreting any special characters. Dollar signs, spaces, ampersands, asterisks and other special characters are all ignored when enclosed within single quotes.

$ echo 'All sorts of things are ignored in single quotes, like $ & * ; |.' 

It will give this:

All sorts of things are ignored in single quotes, like $ & * ; |.

The only thing that cannot be put within single quotes is a single quote.

Double quotes act similarly to single quotes, except double quotes still allow the shell to interpret dollar signs, back quotes and backslashes. It is already known that backslashes prevent a single special character from being interpreted. This can be useful within double quotes if a dollar sign needs to be used as text instead of for a variable. It also allows double quotes to be escaped so they are not interpreted as the end of a quoted string.

$ echo "Here's how we can use single ' and double \" quotes within double quotes"

It will give this:

Here's how we can use single ' and double " quotes within double quotes

It may also be noticed that the apostrophe, which would otherwise be interpreted as the beginning of a quoted string, is ignored within double quotes. Variables, however, are interpreted and substituted with their values within double quotes.

$ echo "The current Oracle SID is $ORACLE_SID"

It will give this:

The current Oracle SID is test

Back quotes are wholly unlike single or double quotes. Instead of being used to prevent the interpretation of special characters, back quotes actually force the execution of the commands they enclose. After the enclosed commands are executed, their output is substituted in place of the back quotes in the original line. This will be clearer with an example.

$ today=`date '+%A, %B %d, %Y'`
$ echo $today 

It will give this:

Monday, September 28, 2015 

using setTimeout on promise chain

If you are inside a .then() block and you want to execute a settimeout()

            .then(() => {
                console.log('wait for 10 seconds . . . . ');
                return new Promise(function(resolve, reject) { 
                    setTimeout(() => {
                        console.log('10 seconds Timer expired!!!');
                        resolve();
                    }, 10000)
                });
            })
            .then(() => {
                console.log('promise resolved!!!');

            })

output will as shown below

wait for 10 seconds . . . .
10 seconds Timer expired!!!
promise resolved!!!

Happy Coding!

Android Get Current timestamp?

I suggest using Hits's answer, but adding a Locale format, this is how Android Developers recommends:

try {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
        return dateFormat.format(new Date()); // Find todays date
    } catch (Exception e) {
        e.printStackTrace();

        return null;
    }

Remove the last three characters from a string

The new C# 8.0 range operator can be a great shortcut to achieve this.

Example #1 (to answer the question):

string myString = "abcdxxx";
var shortenedString = myString[0..^3]
System.Console.WriteLine(shortenedString);
// Results: abcd

Example #2 (to show you how awesome range operators are):

string s = "FooBar99";
// If the last 2 characters of the string are 99 then change to 98
s = s[^2..] == "99" ? s[0..^2] + "98" : s;
System.Console.WriteLine(s);
// Results: FooBar98

Executing multi-line statements in the one-line command-line?

this style can be used in makefiles too (and in fact it is used quite often).

python - <<EOF
import sys
for r in range(3): print 'rob'
EOF

or

python - <<-EOF
    import sys
    for r in range(3): print 'rob'
EOF

in latter case leading tab characters are removed too (and some structured outlook can be achieved)

instead of EOF can stand any marker word not appearing in the here document at a beginning of a line (see also here documents in the bash manpage or here).

How to run a shell script on a Unix console or Mac terminal?

Little addition, to run an interpreter from the same folder, still using #!hashbang in scripts.

As example a php7.2 executable copied from /usr/bin is in a folder along a hello script.

#!./php7.2
<?php

echo "Hello!"; 

To run it:

./hello

Which behave just as equal as:

./php7.2 hello

The proper solutions with good documentation can be the tools linuxdeploy and/or appimage, this is using this method under the hood.

IIS: Display all sites and bindings in PowerShell

Try something like this to get the format you wanted:

Get-WebBinding | % {
    $name = $_.ItemXPath -replace '(?:.*?)name=''([^'']*)(?:.*)', '$1'
    New-Object psobject -Property @{
        Name = $name
        Binding = $_.bindinginformation.Split(":")[-1]
    }
} | Group-Object -Property Name | 
Format-Table Name, @{n="Bindings";e={$_.Group.Binding -join "`n"}} -Wrap

How can I open the interactive matplotlib window in IPython notebook?

Starting with matplotlib 1.4.0 there is now an an interactive backend for use in the notebook

%matplotlib notebook

There are a few version of IPython which do not have that alias registered, the fall back is:

%matplotlib nbagg

If that does not work update you IPython.

To play with this, goto tmpnb.org

and paste

%matplotlib notebook

import pandas as pd
import numpy as np
import matplotlib

from matplotlib import pyplot as plt
import seaborn as sns

ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()

df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,
                  columns=['A', 'B', 'C', 'D'])
df = df.cumsum()
df.plot(); plt.legend(loc='best')    

into a code cell (or just modify the existing python demo notebook)

An invalid XML character (Unicode: 0xc) was found

There are a few characters that are dissallowed in XML documents, even when you encapsulate data in CDATA-blocks.

If you generated the document you will need to entity encode it or strip it out. If you have an errorneous document, you should strip away these characters before trying to parse it.

See dolmens answer in this thread: Invalid Characters in XML

Where he links to this article: http://www.w3.org/TR/xml/#charsets

Basically, all characters below 0x20 is disallowed, except 0x9 (TAB), 0xA (CR?), 0xD (LF?)

Resize Google Maps marker icon image

A complete beginner like myself to the topic may find it harder to implement one of these answers than, if within your control, to resize the image yourself with an online editor or a photo editor like Photoshop.

A 500x500 image will appear larger on the map than a 50x50 image.

No programming required.

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.

CSS: 100% width or height while keeping aspect ratio?

This is a very straightforward solution that I came up with after following conca's link and looking at background size. It blows the image up and then fits it centered into the outer container w/o scaling it.

<style>
#cropcontainer
{
  width:  100%; 
  height: 100%; 
  background-size: 140%;
  background-position: center;
  background-repeat: no-repeat;
}
</style>

<div id="cropcontainer" style="background-image: url(yoururl); />

Change bar plot colour in geom_bar with ggplot2 in r

If you want all the bars to get the same color (fill), you can easily add it inside geom_bar.

ggplot(data=df, aes(x=c1+c2/2, y=c3)) + 
geom_bar(stat="identity", width=c2, fill = "#FF6666")

enter image description here

Add fill = the_name_of_your_var inside aes to change the colors depending of the variable :

c4 = c("A", "B", "C")
df = cbind(df, c4)
ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2)

enter image description here

Use scale_fill_manual() if you want to manually the change of colors.

ggplot(data=df, aes(x=c1+c2/2, y=c3, fill = c4)) + 
geom_bar(stat="identity", width=c2) + 
scale_fill_manual("legend", values = c("A" = "black", "B" = "orange", "C" = "blue"))

enter image description here

How do I include negative decimal numbers in this regular expression?

For negative number only, this is perfect.

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

Where does Anaconda Python install on Windows?

If you installed as admin ( and meant for all users )

C:\ProgramData\Anaconda3\Scripts\anaconda.exe

If you install as a normal user

C:\Users\User-Name\AppData\Local\Continuum\Anaconda2\Scripts\anaconda.exe

How to get id from URL in codeigniter?

if you have to pass the value you should enter url like this

localhost/yoururl/index.php/products_controller/delete_controller/70

and in controller function you can read like this

function delete_controller( $product_id = NULL ) {
  echo $product_id;
}

How can I create a self-signed cert for localhost?

If you are using Visual Studio, there is an easy way to setup and enable SSL using IIS Express explained here

How to migrate GIT repository from one server to a new one

Take a look at this recipe on GitHub: https://help.github.com/articles/importing-an-external-git-repository

I tried a number of methods before discovering git push --mirror.

Worked like a charm!

Can Windows' built-in ZIP compression be scripted?

There are VBA methods to zip and unzip using the windows built in compression as well, which should give some insight as to how the system operates. You may be able to build these methods into a scripting language of your choice.

The basic principle is that within windows you can treat a zip file as a directory, and copy into and out of it. So to create a new zip file, you simply make a file with the extension .zip that has the right header for an empty zip file. Then you close it, and tell windows you want to copy files into it as though it were another directory.

Unzipping is easier - just treat it as a directory.

In case the web pages are lost again, here are a few of the relevant code snippets:

ZIP

Sub NewZip(sPath)
'Create empty Zip File
'Changed by keepITcool Dec-12-2005
    If Len(Dir(sPath)) > 0 Then Kill sPath
    Open sPath For Output As #1
    Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
End Sub


Function bIsBookOpen(ByRef szBookName As String) As Boolean
' Rob Bovey
    On Error Resume Next
    bIsBookOpen = Not (Application.Workbooks(szBookName) Is Nothing)
End Function


Function Split97(sStr As Variant, sdelim As String) As Variant
'Tom Ogilvy
    Split97 = Evaluate("{""" & _
                       Application.Substitute(sStr, sdelim, """,""") & """}")
End Function

Sub Zip_File_Or_Files()
    Dim strDate As String, DefPath As String, sFName As String
    Dim oApp As Object, iCtr As Long, I As Integer
    Dim FName, vArr, FileNameZip

    DefPath = Application.DefaultFilePath
    If Right(DefPath, 1) <> "\" Then
        DefPath = DefPath & "\"
    End If

    strDate = Format(Now, " dd-mmm-yy h-mm-ss")
    FileNameZip = DefPath & "MyFilesZip " & strDate & ".zip"

    'Browse to the file(s), use the Ctrl key to select more files
    FName = Application.GetOpenFilename(filefilter:="Excel Files (*.xl*), *.xl*", _
                    MultiSelect:=True, Title:="Select the files you want to zip")
    If IsArray(FName) = False Then
        'do nothing
    Else
        'Create empty Zip File
        NewZip (FileNameZip)
        Set oApp = CreateObject("Shell.Application")
        I = 0
        For iCtr = LBound(FName) To UBound(FName)
            vArr = Split97(FName(iCtr), "\")
            sFName = vArr(UBound(vArr))
            If bIsBookOpen(sFName) Then
                MsgBox "You can't zip a file that is open!" & vbLf & _
                       "Please close it and try again: " & FName(iCtr)
            Else
                'Copy the file to the compressed folder
                I = I + 1
                oApp.Namespace(FileNameZip).CopyHere FName(iCtr)

                'Keep script waiting until Compressing is done
                On Error Resume Next
                Do Until oApp.Namespace(FileNameZip).items.Count = I
                    Application.Wait (Now + TimeValue("0:00:01"))
                Loop
                On Error GoTo 0
            End If
        Next iCtr

        MsgBox "You find the zipfile here: " & FileNameZip
    End If
End Sub

UNZIP

Sub Unzip1()
    Dim FSO As Object
    Dim oApp As Object
    Dim Fname As Variant
    Dim FileNameFolder As Variant
    Dim DefPath As String
    Dim strDate As String

    Fname = Application.GetOpenFilename(filefilter:="Zip Files (*.zip), *.zip", _
                                        MultiSelect:=False)
    If Fname = False Then
        'Do nothing
    Else
        'Root folder for the new folder.
        'You can also use DefPath = "C:\Users\Ron\test\"
        DefPath = Application.DefaultFilePath
        If Right(DefPath, 1) <> "\" Then
            DefPath = DefPath & "\"
        End If

        'Create the folder name
        strDate = Format(Now, " dd-mm-yy h-mm-ss")
        FileNameFolder = DefPath & "MyUnzipFolder " & strDate & "\"

        'Make the normal folder in DefPath
        MkDir FileNameFolder

        'Extract the files into the newly created folder
        Set oApp = CreateObject("Shell.Application")

        oApp.Namespace(FileNameFolder).CopyHere oApp.Namespace(Fname).items

        'If you want to extract only one file you can use this:
        'oApp.Namespace(FileNameFolder).CopyHere _
         'oApp.Namespace(Fname).items.Item("test.txt")

        MsgBox "You find the files here: " & FileNameFolder

        On Error Resume Next
        Set FSO = CreateObject("scripting.filesystemobject")
        FSO.deletefolder Environ("Temp") & "\Temporary Directory*", True
    End If
End Sub

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

How to use log levels in java

Logging has different levels such as :
Trace – A fine-grained debug message, typically capturing the flow through the application. Debug- A general debugging event should be logged under this.
ALL – All events could be logged.
INFO- An informational purpose, information written in plain english.
Warn- An event that might possible lead to an error.
Error- An error in the application, possibly recoverable.

Logging captured with debug level is information helpful to developers as well as other personnel, so it captures in broad range. If your code doesn't have exception or errors then you should be alright to use DEBUG level of logging, otherwise you should carefully choose options.

Generating statistics from Git repository

I tried http://gitstats.sourceforge.net/, starts are very interesting.

Once git clone git://repo.or.cz/gitstats.git is done, go to that folder and say gitstats <git repo location> <report output folder> (create a new folder for report as this generates lots of files)

Here is a quick list of stats from this:

  • activity
    • hour of the day
    • day of week
  • authors
    • List of Authors
    • Author of Month
    • Author of Year
  • files
    • File count by date
    • Extensions
  • lines
    • Lines of Code
  • tags

Passing bash variable to jq

I resolved this issue by escaping the inner double quotes

projectID=$(cat file.json | jq -r ".resource[] | select(.username==\"$EMAILID\") | .id")

Parcelable encountered IOException writing serializable object getactivity()

I faced Same issue, the issues was there are some inner classes with the static keyword.After removing the static keyword it started working and also the inner class should implements to Serializable

Issue scenario

class A implements Serializable{ 
  class static B{
  } 
}

Resolved By

class A implements Serializable{ 
      class B implements Serializable{
      } 
    }

Exists Angularjs code/naming conventions?

Update : STYLE GUIDE is now on Angular docs.

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

If you are looking for an opinionated style guide for syntax, conventions, and structuring AngularJS applications, then step right in. The styles contained here are based on my experience with AngularJS, presentations, training courses and working in teams.

The purpose of this style guide is to provide guidance on building AngularJS applications by showing the conventions I use and, more importantly, why I choose them.

- John Papa

Here is the Awesome Link (Latest and Up-to-date) : AngularJS Style Guide

Accessing an SQLite Database in Swift

Yet another SQLite wrapper for Swift 2 and Swift 3: http://github.com/groue/GRDB.swift

Features:

  • An API that will look familiar to users of ccgus/fmdb

  • A low-level SQLite API that leverages the Swift standard library

  • A pretty Swift query interface for SQL-allergic developers

  • Support for the SQLite WAL mode, and concurrent database access for extra performance

  • A Record class that wraps result sets, eats your custom SQL queries for breakfast, and provides basic CRUD operations

  • Swift type freedom: pick the right Swift type that fits your data. Use Int64 when needed, or stick with the convenient Int. Store and read NSDate or NSDateComponents. Declare Swift enums for discrete data types. Define your own database-convertible types.

  • Database Migrations

  • Speed: https://github.com/groue/GRDB.swift/wiki/Performance

For each row return the column name of the largest value

Based on the above suggestions, the following data.table solution worked very fast for me:

library(data.table)

set.seed(45)
DT <- data.table(matrix(sample(10, 10^7, TRUE), ncol=10))

system.time(
  DT[, col_max := colnames(.SD)[max.col(.SD, ties.method = "first")]]
)
#>    user  system elapsed 
#>    0.15    0.06    0.21
DT[]
#>          V1 V2 V3 V4 V5 V6 V7 V8 V9 V10 col_max
#>       1:  7  4  1  2  3  7  6  6  6   1      V1
#>       2:  4  6  9 10  6  2  7  7  1   3      V4
#>       3:  3  4  9  8  9  9  8  8  6   7      V3
#>       4:  4  8  8  9  7  5  9  2  7   1      V4
#>       5:  4  3  9 10  2  7  9  6  6   9      V4
#>      ---                                       
#>  999996:  4  6 10  5  4  7  3  8  2   8      V3
#>  999997:  8  7  6  6  3 10  2  3 10   1      V6
#>  999998:  2  3  2  7  4  7  5  2  7   3      V4
#>  999999:  8 10  3  2  3  4  5  1  1   4      V2
#> 1000000: 10  4  2  6  6  2  8  4  7   4      V1

And also comes with the advantage that can always specify what columns .SD should consider by mentioning them in .SDcols:

DT[, MAX2 := colnames(.SD)[max.col(.SD, ties.method="first")], .SDcols = c("V9", "V10")]

In case we need the column name of the smallest value, as suggested by @lwshang, one just needs to use -.SD:

DT[, col_min := colnames(.SD)[max.col(-.SD, ties.method = "first")]]

Incorrect string value: '\xF0\x9F\x8E\xB6\xF0\x9F...' MySQL

FOR SQLALCHEMY AND PYTHON

The encoding used for Unicode has traditionally been 'utf8'. However, for MySQL versions 5.5.3 on forward, a new MySQL-specific encoding 'utf8mb4' has been introduced, and as of MySQL 8.0 a warning is emitted by the server if plain utf8 is specified within any server-side directives, replaced with utf8mb3. The rationale for this new encoding is due to the fact that MySQL’s legacy utf-8 encoding only supports codepoints up to three bytes instead of four. Therefore, when communicating with a MySQL database that includes codepoints more than three bytes in size, this new charset is preferred, if supported by both the database as well as the client DBAPI, as in:

e = create_engine(
    "mysql+pymysql://scott:tiger@localhost/test?charset=utf8mb4")
All modern DBAPIs should support the utf8mb4 charset.

enter link description here

I need to learn Web Services in Java. What are the different types in it?

  1. SOAP Web Services are standard-based and supported by almost every software platform: They rely heavily in XML and have support for transactions, security, asynchronous messages and many other issues. It’s a pretty big and complicated standard, but covers almost every messaging situation. On the other side, RESTful services relies of HTTP protocol and verbs (GET, POST, PUT, DELETE) to interchange messages in any format, preferable JSON and XML. It’s a pretty simple and elegant architectural approach.
  2. As in every topic in the Java World, there are several libraries to build/consume Web Services. In the SOAP Side you have the JAX-WS standard and Apache Axis, and in REST you can use Restlets or Spring REST Facilities among other libraries.

With question 3, this article states that RESTful Services are appropiate in this scenarios:

  • If you have limited bandwidth
  • If your operations are stateless: No information is preserved from one invocation to the next one, and each request is treated independently.
  • If your clients require caching.

While SOAP is the way to go when:

  • If you require asynchronous processing
  • If you need formal contract/Interfaces
  • In your service operations are stateful: For example, you store information/data on a request and use that stored data on the next one.

How can I pad a String in Java?

A simple solution would be:

package nl;
public class Padder {
    public static void main(String[] args) {
        String s = "123" ;
        System.out.println("#"+("     " + s).substring(s.length())+"#");
    }
}

Are querystring parameters secure in HTTPS (HTTP + SSL)?

The entire transmission, including the query string, the whole URL, and even the type of request (GET, POST, etc.) is encrypted when using HTTPS.

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer  connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip

How to implement a Boolean search with multiple columns in pandas

A more concise--but not necessarily faster--method is to use DataFrame.isin() and DataFrame.any()

In [27]: n = 10

In [28]: df = DataFrame(randint(4, size=(n, 2)), columns=list('ab'))

In [29]: df
Out[29]:
   a  b
0  0  0
1  1  1
2  1  1
3  2  3
4  2  3
5  0  2
6  1  2
7  3  0
8  1  1
9  2  2

[10 rows x 2 columns]

In [30]: df.isin([1, 2])
Out[30]:
       a      b
0  False  False
1   True   True
2   True   True
3   True  False
4   True  False
5  False   True
6   True   True
7  False  False
8   True   True
9   True   True

[10 rows x 2 columns]

In [31]: df.isin([1, 2]).any(1)
Out[31]:
0    False
1     True
2     True
3     True
4     True
5     True
6     True
7    False
8     True
9     True
dtype: bool

In [32]: df.loc[df.isin([1, 2]).any(1)]
Out[32]:
   a  b
1  1  1
2  1  1
3  2  3
4  2  3
5  0  2
6  1  2
8  1  1
9  2  2

[8 rows x 2 columns]

Printing *s as triangles in Java?

// This is for normal triangle

for (int i = 0; i < 5; i++)
        {
            for (int j = 5; j > i; j--)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= i + 1; k++) {
                System.out.print(" *");
            }
            System.out.print("\n");
        }

// This is for left triangle, just removed space before printing *

for (int i = 0; i < 5; i++)
        {
            for (int j = 5; j > i; j--)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= i + 1; k++) {
                System.out.print("*");
            }
            System.out.print("\n");
        }

JSON to pandas DataFrame

#Use the small trick to make the data json interpret-able
#Since your data is not directly interpreted by json.loads()

>>> import json
>>> f=open("sampledata.txt","r+")
>>> data = f.read()
>>> for x in data.split("\n"):
...     strlist = "["+x+"]"
...     datalist=json.loads(strlist)
...     for y in datalist:
...             print(type(y))
...             print(y)
...
...
<type 'dict'>
{u'0': [[10.8, 36.0], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'1': [[10.8, 36.1], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'2': [[10.8, 36.2], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'3': [[10.8, 36.300000000000004], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'4': [[10.8, 36.4], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'5': [[10.8, 36.5], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'6': [[10.8, 36.6], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'7': [[10.8, 36.7], {u'10': 0, u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'8': [[10.8, 36.800000000000004], {u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}
<type 'dict'>
{u'9': [[10.8, 36.9], {u'1': 0, u'0': 0, u'3': 0, u'2': 0, u'5': 0, u'4': 0, u'7': 0, u'6': 0, u'9': 0, u'8': 0}]}


Transfer files to/from session I'm logged in with PuTTY

Same everyday problem.

I just created a simple vc project to solve this problem.

It copies the file as Base64 encoded data directly to the clipboard, and then this can be pasted into the PuTTY console and decoded on the remote side.

This solution is for relatively small files (relative to the connection speed to your remote console).

Installation:

Download clip_b64.exe and place it in the SendTo folder (or a .lnk shortcut to it). To open this folder, in the address bar of the explorer, enter shell:sendto or %appdata%\Microsoft\Windows\SendTo.

You may need to install VC 2017 redist to run it, or use the statically linked clip_b64s.exe execution.

Usage:

On the local machine:

In the File Explorer, right-click the file you are transferring to open the context menu, then go to the "Send To" section and select Clip_B64 from the list.

On the remote console (over putty-ssh link):

Run the shell command base64 -d > file-name-you-want and right-click in the console (or press Shift + Insert) to place the clipboard content in it, and then press Ctrl + D to finish.

voila

How to present UIActionSheet iOS Swift?

Your Approach is fine, but you can add UIActionSheet with other way with ease.

You can add UIActionSheetDelegate in UIViewController` like

class ViewController: UIViewController ,UIActionSheetDelegate

Set you method like,

@IBAction func downloadSheet(sender: AnyObject)
{

    let actionSheet = UIActionSheet(title: "Choose Option", delegate: self, cancelButtonTitle: "Cancel", destructiveButtonTitle: nil, otherButtonTitles: "Save", "Delete")

    actionSheet.showInView(self.view)
}

You can get your button index when it clicked like

func actionSheet(actionSheet: UIActionSheet, clickedButtonAtIndex buttonIndex: Int)
{
    println("\(buttonIndex)")
    switch (buttonIndex){

    case 0:
        println("Cancel")
    case 1:
        println("Save")
    case 2:
        println("Delete")
    default:
        println("Default")
        //Some code here..

    }
}

Update 1: for iOS8+

    //Create the AlertController and add Its action like button in Actionsheet
    let actionSheetControllerIOS8: UIAlertController = UIAlertController(title: "Please select", message: "Option to select", preferredStyle: .ActionSheet)

    let cancelActionButton = UIAlertAction(title: "Cancel", style: .cancel) { _ in
        print("Cancel")
    }
    actionSheetControllerIOS8.addAction(cancelActionButton)

    let saveActionButton = UIAlertAction(title: "Save", style: .default)
        { _ in
           print("Save")
    }
    actionSheetControllerIOS8.addAction(saveActionButton)

    let deleteActionButton = UIAlertAction(title: "Delete", style: .default)
        { _ in
            print("Delete")
    }
    actionSheetControllerIOS8.addAction(deleteActionButton)
    self.present(actionSheetControllerIOS8, animated: true, completion: nil)