Programs & Examples On #Memset

memset is a C++ function that sets the first N bytes of the block of memory to the specified value (interpreted as an unsigned char)

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

Well, the fastest way to do it is to not do it at all.

Sounds odd I know, here's some pseudocode:

int array [][];
bool array_is_empty;


void ClearArray ()
{
   array_is_empty = true;
}

int ReadValue (int x, int y)
{
   return array_is_empty ? 0 : array [x][y];
}

void SetValue (int x, int y, int value)
{
   if (array_is_empty)
   {
      memset (array, 0, number of byte the array uses);
      array_is_empty = false;
   }
   array [x][y] = value;
}

Actually, it's still clearing the array, but only when something is being written to the array. This isn't a big advantage here. However, if the 2D array was implemented using, say, a quad tree (not a dynamic one mind), or a collection of rows of data, then you can localise the effect of the boolean flag, but you'd need more flags. In the quad tree just set the empty flag for the root node, in the array of rows just set the flag for each row.

Which leads to the question "why do you want to repeatedly zero a large 2d array"? What is the array used for? Is there a way to change the code so that the array doesn't need zeroing?

For example, if you had:

clear array
for each set of data
  for each element in data set
    array += element 

that is, use it for an accumulation buffer, then changing it like this would improve the performance no end:

 for set 0 and set 1
   for each element in each set
     array = element1 + element2

 for remaining data sets
   for each element in data set
     array += element 

This doesn't require the array to be cleared but still works. And that will be far faster than clearing the array. Like I said, the fastest way is to not do it in the first place.

Reset C int array to zero : the fastest way?

zero(myarray); is all you need in C++.

Just add this to a header:

template<typename T, size_t SIZE> inline void zero(T(&arr)[SIZE]){
    memset(arr, 0, SIZE*sizeof(T));
}

jQuery: select all elements of a given class, except for a particular Id

Using the .not() method with selecting an entire element is also an option.

This way could be usefull if you want to do another action with that element directly.

$(".thisClass").not($("#thisId")[0].doAnotherAction()).doAction();

Get HTML code from website in C#

Getting HTML code from a website. You can use code like this.

string urlAddress = "http://google.com";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();

if (response.StatusCode == HttpStatusCode.OK)
{
  Stream receiveStream = response.GetResponseStream();
  StreamReader readStream = null;

  if (String.IsNullOrWhiteSpace(response.CharacterSet))
     readStream = new StreamReader(receiveStream);
  else
     readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));

  string data = readStream.ReadToEnd();

  response.Close();
  readStream.Close();
}

This will give you the returned HTML code from the website. But find text via LINQ is not that easy. Perhaps it is better to use regular expression but that does not play well with HTML code

Getting Python error "from: can't read /var/mail/Bio"

Same here. I had this error when running an import command from terminal without activating python3 shell through manage.py in a django project (yes, I am a newbie yet). As one must expect, activating shell allowed the command to be interpreted correctly.

./manage.py shell

and only then

>>> from django.contrib.sites.models import Site

Regex for not empty and not whitespace

/^[\s]*$/ matches empty strings and strings containing whitespaces only

How do I reference to another (open or closed) workbook, and pull values back, in VBA? - Excel 2007

You will have to open the file in one way or another if you want to access the data within it. Obviously, one way is to open it in your Excel application instance, e.g.:-

(untested code)

Dim wbk As Workbook
Set wbk = Workbooks.Open("C:\myworkbook.xls")

' now you can manipulate the data in the workbook anyway you want, e.g. '

Dim x As Variant
x = wbk.Worksheets("Sheet1").Range("A6").Value

Call wbk.Worksheets("Sheet2").Range("A1:G100").Copy
Call ThisWorbook.Worksheets("Target").Range("A1").PasteSpecial(xlPasteValues)
Application.CutCopyMode = False

' etc '

Call wbk.Close(False)

Another way to do it would be to use the Excel ADODB provider to open a connection to the file and then use SQL to select data from the sheet you want, but since you are anyway working from within Excel I don't believe there is any reason to do this rather than just open the workbook. Note that there are optional parameters for the Workbooks.Open() method to open the workbook as read-only, etc.

Function is not defined - uncaught referenceerror

One more thing. In my experience this error occurred because there was another error previous to the Function is not defined - uncaught referenceerror.

So, look through the console to see if a previous error exists and if so, correct any that exist. You might be lucky in that they were the problem.

Quickest way to compare two generic lists for differences

Not for this Problem, but here's some code to compare lists for equal and not! identical objects:

public class EquatableList<T> : List<T>, IEquatable<EquatableList<T>> where    T : IEquatable<T>

/// <summary>
/// True, if this contains element with equal property-values
/// </summary>
/// <param name="element">element of Type T</param>
/// <returns>True, if this contains element</returns>
public new Boolean Contains(T element)
{
    return this.Any(t => t.Equals(element));
}

/// <summary>
/// True, if list is equal to this
/// </summary>
/// <param name="list">list</param>
/// <returns>True, if instance equals list</returns>
public Boolean Equals(EquatableList<T> list)
{
    if (list == null) return false;
    return this.All(list.Contains) && list.All(this.Contains);
}

How can I uninstall npm modules in Node.js?

I just install stylus by default under my home dir, so I just use npm uninstall stylus to detach it, or you can try npm rm <package_name> out.

Printing out a number in assembly language?

PRINT_SUM PROC NEAR
 CMP AL, 0
 JNE PRINT_AX
 PUSH AX
 MOV AL, '0'
 MOV AH, 0EH
 INT 10H
 POP AX
 RET 
    PRINT_AX:    
 PUSHA
 MOV AH, 0
 CMP AX, 0
 JE PN_DONE
 MOV DL, 10
 DIV DL    
 CALL PRINT_AX
 MOV AL, AH
 ADD AL, 30H
 MOV AH, 0EH
 INT 10H    
    PN_DONE:
 POPA  
 RET  
PRINT_SUM ENDP

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

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

Pandas dataframe get first row of each group

maybe this is what you want

import pandas as pd
idx = pd.MultiIndex.from_product([['state1','state2'],   ['county1','county2','county3','county4']])
df = pd.DataFrame({'pop': [12,15,65,42,78,67,55,31]}, index=idx)
                pop
state1 county1   12
       county2   15
       county3   65
       county4   42
state2 county1   78
       county2   67
       county3   55
       county4   31
df.groupby(level=0, group_keys=False).apply(lambda x: x.sort_values('pop', ascending=False)).groupby(level=0).head(3)

> Out[29]: 
                pop
state1 county3   65
       county4   42
       county2   15
state2 county1   78
       county2   67
       county3   55

How to detect DataGridView CheckBox event change?

Here is some code:

private void dgvStandingOrder_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
    if (dgvStandingOrder.Columns[e.ColumnIndex].Name == "IsSelected" && dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
    {
        bool isChecked = (bool)dgvStandingOrder[e.ColumnIndex, e.RowIndex].EditedFormattedValue;
        if (isChecked == false)
        {
            dgvStandingOrder.Rows[e.RowIndex].Cells["Status"].Value = "";
        }
        dgvStandingOrder.EndEdit();
    }
}

private void dgvStandingOrder_CellEndEdit(object sender, DataGridViewCellEventArgs e)
{

    dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
}

private void dgvStandingOrder_CurrentCellDirtyStateChanged(object sender, EventArgs e)
{
    if (dgvStandingOrder.CurrentCell is DataGridViewCheckBoxCell)
    {
        dgvStandingOrder.CommitEdit(DataGridViewDataErrorContexts.Commit);
    }
}

How to show progress dialog in Android?

ProgressDialog is now officially deprecated in Android O. I use DelayedProgressDialog from https://github.com/Q115/DelayedProgressDialog to get the job done.

Usage:

DelayedProgressDialog progressDialog = new DelayedProgressDialog();
progressDialog.show(getSupportFragmentManager(), "tag");

Convert InputStream to byte array in Java

The other case to get correct byte array via stream, after send request to server and waiting for the response.

/**
         * Begin setup TCP connection to PC app
         * to open integrate connection between mobile app and pc app (or mobile app)
         */
        mSocket = new Socket(IP, port);
       // mSocket.setSoTimeout(30000);

        DataOutputStream mDos = new DataOutputStream(mSocket.getOutputStream());

        String str = "MobileRequest#" + params[0] + "#<EOF>";

        mDos.write(str.getBytes());

        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        /* Since data are accepted as byte, all of them will be collected in the
        following byte array which initialised with accepted data length. */
        DataInputStream mDis = new DataInputStream(mSocket.getInputStream());
        byte[] data = new byte[mDis.available()];

        // Collecting data into byte array
        for (int i = 0; i < data.length; i++)
            data[i] = mDis.readByte();

        // Converting collected data in byte array into String.
        String RESPONSE = new String(data);

"You have mail" message in terminal, os X

Probably it is some message from your system.

Type in terminal:

man mail

, and see how can you get this message from your system.

How to name variables on the fly?

Use assign:

assign(paste("orca", i, sep = ""), list_name[[i]])

Angular.js vs Knockout.js vs Backbone.js

It depends on the nature of your application. And, since you did not describe it in great detail, it is an impossible question to answer. I find Backbone to be the easiest, but I work in Angular all day. Performance is more up to the coder than the framework, in my opinion.

Are you doing heavy DOM manipulation? I would use jQuery and Backbone.

Very data driven app? Angular with its nice data binding.

Game programming? None - direct to canvas; maybe a game engine.

Proper way to initialize a C# dictionary with values?

With C# 6.0, you can create a dictionary in following way:

var dict = new Dictionary<string, int>
{
    ["one"] = 1,
    ["two"] = 2,
    ["three"] = 3
};

It even works with custom types.

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

"This operation requires IIS integrated pipeline mode."

For Visual Studio 2012 while debugging that error accrued

Website Menu -> Use IIS Express did it for me

Fit cell width to content

There are many ways to do this!

correct me if I'm wrong but the question is looking for this kind of result.

<table style="white-space:nowrap;width:100%;">
<tr>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:50%">this should stretch</td>
<td class="block" style="width:auto">this should be the content width</td>
</tr>
</table>

The first 2 fields will "share" the remaining page (NOTE: if you add more text to either 50% fields it will take more space), and the last field will dominate the table constantly.

If you are happy to let text wrap you can move white-space:nowrap; to the style of the 3rd field
will be the only way to start a new line in that field.

alternatively, you can set a length on the last field ie. width:150px, and leave percentage's on the first 2 fields.

Hope this helps!

Copy array by value

let a = [1,2,3];

Now you can do any one of the following to make a copy of an array.

let b = Array.from(a); 

OR

let b = [...a];

OR

let b = new Array(...a); 

OR

let b = a.slice(); 

OR

let b = a.map(e => e);

Now, if i change a,

a.push(5); 

Then, a is [1,2,3,5] but b is still [1,2,3] as it has different reference.

But i think, in all the methods above Array.from is better and made mainly to copy an array.

Printing an array in C++?

It certainly is! You'll have to loop through the array and print out each item individually.

Chrome Dev Tools - Modify javascript and reload

I know it's not the asnwer to the precise question (Chrome Developer Tools) but I'm using this workaround with success: http://www.telerik.com/fiddler

(pretty sure some of the web devs already know about this tool)

  1. Save the file locally
  2. Edit as required
  3. Profit!

enter image description here

Full docs: http://docs.telerik.com/fiddler/KnowledgeBase/AutoResponder

PS. I would rather have it implemented in Chrome as a flag preserve after reload, cannot do this now, forums and discussion groups blocked on corporate network :)

Single quotes vs. double quotes in C or C++

Use single quote with single char as:

char ch = 'a';

here 'a' is a char constant and is equal to the ASCII value of char a.

Use double quote with strings as:

char str[] = "foo";

here "foo" is a string literal.

Its okay to use "a" but its not okay to use 'foo'

Xcode 'CodeSign error: code signing is required'

In my case, locking and unlocking login-keychain from Keychain Access did the trick enter image description here

Save text file UTF-8 encoded with VBA

I found the answer on the web:

Dim fsT As Object
Set fsT = CreateObject("ADODB.Stream")
fsT.Type = 2 'Specify stream type - we want To save text/string data.
fsT.Charset = "utf-8" 'Specify charset For the source text data.
fsT.Open 'Open the stream And write binary data To the object
fsT.WriteText "special characters: äöüß"
fsT.SaveToFile sFileName, 2 'Save binary data To disk

Certainly not as I expected...

What is the best way to do a substring in a batch file?

As an additional info to Joey's answer, which isn't described in the help of set /? nor for /?.

%~0 expands to the name of the own batch, exactly as it was typed.
So if you start your batch it will be expanded as

%~0   - mYbAtCh
%~n0  - mybatch
%~nx0 - mybatch.bat

But there is one exception, expanding in a subroutine could fail

echo main- %~0
call :myFunction
exit /b

:myFunction
echo func - %~0
echo func - %~n0
exit /b

This results to

main - myBatch
Func - :myFunction
func - mybatch

In a function %~0 expands always to the name of the function, not of the batch file.
But if you use at least one modifier it will show the filename again!

Postman: sending nested JSON object

This is a combination of the above, because I had to read several posts to understand.

  1. In the Headers, add the following key-values:
    1. Content-Type to application/json
    2. and Accept to application/json

enter image description here

  1. In the Body:
    1. change the type to "raw"
    2. confirm "JSON (application/json)" is the text type
    3. put the nested property there: { "Obj1" : { "key1" : "val1" } }

enter image description here

Hope this helps!

Why is datetime.strptime not working in this simple example?

If in the folder with your project you created a file with the name "datetime.py"

Mailto links do nothing in Chrome but work in Firefox?

I also experienced this issue, and eventually tracked it down to the fact that my link was within an iframe, and my web app uses https. Chrome was blocking it due to this (Chrome would open other mailto links outside of the iframe).

In mailto link not working within a frame chrome (over https), kendsnyder mentioned simply changing

<a href="mailto:...">email</a>

to

<a target="_top" href="mailto:...">email</a>

Voila, problem solved. That mailto link now works in all browsers.

Pass variables to AngularJS controller, best practice?

You could use ng-init in an outer div:

<div ng-init="param='value';">
    <div ng-controller="BasketController" >
        <label>param: {{value}}</label>
    </div>
</div>  

The parameter will then be available in your controller's scope:

function BasketController($scope) {
        console.log($scope.param);
}

Setting value of active workbook in Excel VBA

You're probably after Set wbOOR = ThisWorkbook

Just to clarify

ThisWorkbook will always refer to the workbook the code resides in

ActiveWorkbook will refer to the workbook that is active

Be careful how you use this when dealing with multiple workbooks. It really depends on what you want to achieve as to which is the best option.

How many bits or bytes are there in a character?

It depends what is the character and what encoding it is in:

  • An ASCII character in 8-bit ASCII encoding is 8 bits (1 byte), though it can fit in 7 bits.

  • An ISO-8895-1 character in ISO-8859-1 encoding is 8 bits (1 byte).

  • A Unicode character in UTF-8 encoding is between 8 bits (1 byte) and 32 bits (4 bytes).

  • A Unicode character in UTF-16 encoding is between 16 (2 bytes) and 32 bits (4 bytes), though most of the common characters take 16 bits. This is the encoding used by Windows internally.

  • A Unicode character in UTF-32 encoding is always 32 bits (4 bytes).

  • An ASCII character in UTF-8 is 8 bits (1 byte), and in UTF-16 - 16 bits.

  • The additional (non-ASCII) characters in ISO-8895-1 (0xA0-0xFF) would take 16 bits in UTF-8 and UTF-16.

That would mean that there are between 0.03125 and 0.125 characters in a bit.

android: data binding error: cannot find symbol class

this is your code

ContactListActivityBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_list);

Replace this code

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_contact_list);

Change SVN repository URL

If U want commit to a new empty Repo ,You can checkout the new empty Repo and commit to new remote repo.
chekout a new empty Repo won't delete your local files.
try this: for example, remote repo url : https://example.com/SVNTest cd [YOUR PROJECT PATH] rm -rf .svn svn co https://example.com/SVNTest ../[YOUR PROJECT DIR NAME] svn add ./* svn ci -m"changed repo url"

QED symbol in latex

You can use \blacksquare ¦:

When creating TeX, Knuth provided the symbol ¦ (solid black square), also called by mathematicians tombstone or Halmos symbol (after Paul Halmos, who pioneered its use as an equivalent of Q.E.D.). The tombstone is sometimes open: ? (hollow black square).

Finding all objects that have a given property inside a collection

You can use something like JoSQL, and write 'SQL' against your collections: http://josql.sourceforge.net/

Which sounds like what you want, with the added benefit of being able to do more complicated queries.

Jquery, checking if a value exists in array or not

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

if ($.inArray('example', myArray) != -1)
{
  // found it
}

What's causing my java.net.SocketException: Connection reset?

I got this error when the text file I was trying to read contained a string that matched an antivirus signature on our firewall.

Center text in table cell

How about simply (Please note, come up with a better name for the class name this is simply an example):

.centerText{
   text-align: center;
}


<div>
   <table style="width:100%">
   <tbody>
   <tr>
      <td class="centerText">Cell 1</td>
      <td>Cell 2</td>
    </tr>
    <tr>
      <td class="centerText">Cell 3</td>
      <td>Cell 4</td>
    </tr>
    </tbody>
    </table>
</div>

Example here

You can place the css in a separate file, which is recommended. In my example, I created a file called styles.css and placed my css rules in it. Then include it in the html document in the <head> section as follows:

<head>
    <link href="styles.css" rel="stylesheet" type="text/css">
</head>

The alternative, not creating a seperate css file, not recommended at all... Create <style> block in your <head> in the html document. Then just place your rules there.

<head>
 <style type="text/css">
   .centerText{
       text-align: center;
    }
 </style>
</head>

Hide div after a few seconds

we can directly use

$('#selector').delay(5000).fadeOut('slow');

How to style child components from parent component's CSS file?

As the internet updates I've come across a solution.

First some caveats.

  1. Still don't do it. To clarify, I wouldn't plan on child components allowing you to style them. SOC. If you as the component designer want to allow this then all the more power to you.
  2. If your child doesn't live in the shadow dom then this won't work for you.
  3. If you have to support a browser that can't have a shadow dom then this also won't work for you.

First, mark your child component's encapsulation as shadow so it renders in the actual shadow dom. Second, add the part attribute to the element you wish to allow the parent to style. In your parent's component stylesheet you can use the ::part() method to access

Python Dictionary Comprehension

The main purpose of a list comprehension is to create a new list based on another one without changing or destroying the original list.

Instead of writing

l = []
for n in range(1, 11):
    l.append(n)

or

l = [n for n in range(1, 11)]

you should write only

l = range(1, 11)

In the two top code blocks you're creating a new list, iterating through it and just returning each element. It's just an expensive way of creating a list copy.

To get a new dictionary with all keys set to the same value based on another dict, do this:

old_dict = {'a': 1, 'c': 3, 'b': 2}
new_dict = { key:'your value here' for key in old_dict.keys()}

You're receiving a SyntaxError because when you write

d = {}
d[i for i in range(1, 11)] = True

you're basically saying: "Set my key 'i for i in range(1, 11)' to True" and "i for i in range(1, 11)" is not a valid key, it's just a syntax error. If dicts supported lists as keys, you would do something like

d[[i for i in range(1, 11)]] = True

and not

d[i for i in range(1, 11)] = True

but lists are not hashable, so you can't use them as dict keys.

String replacement in batch file

I was able to use Joey's Answer to create a function:

Use it as:

@echo off
SETLOCAL ENABLEDELAYEDEXPANSION

SET "MYTEXT=jump over the chair"
echo !MYTEXT!
call:ReplaceText "!MYTEXT!" chair table RESULT
echo !RESULT!

GOTO:EOF

And these Functions to the bottom of your Batch File.

:FUNCTIONS
@REM FUNCTIONS AREA
GOTO:EOF
EXIT /B

:ReplaceText
::Replace Text In String
::USE:
:: CALL:ReplaceText "!OrginalText!" OldWordToReplace NewWordToUse  Result
::Example
::SET "MYTEXT=jump over the chair"
::  echo !MYTEXT!
::  call:ReplaceText "!MYTEXT!" chair table RESULT
::  echo !RESULT!
::
:: Remember to use the "! on the input text, but NOT on the Output text.
:: The Following is Wrong: "!MYTEXT!" !chair! !table! !RESULT!
:: ^^Because it has a ! around the chair table and RESULT
:: Remember to add quotes "" around the MYTEXT Variable when calling.
:: If you don't add quotes, it won't treat it as a single string
::
set "OrginalText=%~1"
set "OldWord=%~2"
set "NewWord=%~3"
call set OrginalText=%%OrginalText:!OldWord!=!NewWord!%%
SET %4=!OrginalText!
GOTO:EOF

And remember you MUST add "SETLOCAL ENABLEDELAYEDEXPANSION" to the top of your batch file or else none of this will work properly.

SETLOCAL ENABLEDELAYEDEXPANSION
@REM # Remember to add this to the top of your batch file.

How can I check if two segments intersect?

Checking if line segments intersect is very easy with Shapely library using intersects method:

from shapely.geometry import LineString

line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 0)])
print(line.intersects(other))
# True

enter image description here

line = LineString([(0, 0), (1, 1)])
other = LineString([(0, 1), (1, 2)])
print(line.intersects(other))
# False

enter image description here

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

For Devs getting this error in Web API Project -

The GetOwinContext extension method is defined in System.Web.Http.Owin dll and one more package will be needed i.e. Microsoft.Owin.Host.SystemWeb. This package needs to be installed in your project from nuget.

Link To Package: OWIN Package Install Command -

Install-Package Microsoft.AspNet.WebApi.Owin    

Link To System.web Package : Package Install Command -

Install-Package Microsoft.Owin.Host.SystemWeb

In order to resolve this error you need to find why its occurring in your case. Please Cross check below points in your code -

  1. You must have reference to Microsoft.AspNet.Identity.Owin;

    using Microsoft.AspNet.Identity.Owin;

  2. Define GetOwinContext() Under HttpContext.Current as below -

     return _userManager1 ?? HttpContext.Current.GetOwinContext().GetUserManager<ApplicationUserManager>();
    

    OR

    return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
    

Complete Code Where GetOwinContext() is used -

 public ApplicationSignInManager SignInManager
 {
   get
   {
    return _signInManager ?? HttpContext.Current.GetOwinContext().Get<ApplicationSignInManager>();
   }
    private set
    {
     _signInManager = value;
    }
  }

Namespace's I'm Using in Code File where GetOwinContext() Is used

using AngularJSAuthentication.API.Entities;
using AngularJSAuthentication.API.Models;
using HomeCinema.Common;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security.DataProtection;

I got this error while moving my code from my one project to another.

How to replace space with comma using sed?

Inside vim, you want to type when in normal (command) mode:

:%s/ /,/g

On the terminal prompt, you can use sed to perform this on a file:

sed -i 's/\ /,/g' input_file

Note: the -i option to sed means "in-place edit", as in that it will modify the input file.

Notice: Undefined variable: _SESSION in "" on line 9

Add

session_start();

at the beginning of your page before any HTML

You will have something like :

<?php session_start();
include("inc/incfiles/header.inc.php")?>
<html>
<head>
<meta http-equiv="Content-Type" conte...

Don't forget to remove the space you have before

Does java.util.List.isEmpty() check if the list itself is null?

This will throw a NullPointerException - as will any attempt to invoke an instance method on a null reference - but in cases like this you should make an explicit check against null:

if ((test != null) && !test.isEmpty())

This is much better, and clearer, than propagating an Exception.

jQuery UI Dialog OnBeforeUnload

This works for me:

_x000D_
_x000D_
window.addEventListener("beforeunload", function(event) {_x000D_
  event.returnValue = "You may have unsaved Data";_x000D_
});
_x000D_
_x000D_
_x000D_

Attach Authorization header for all axios requests

If you want to call other api routes in the future and keep your token in the store then try using redux middleware.

The middleware could listen for the an api action and dispatch api requests through axios accordingly.

Here is a very basic example:

actions/api.js

export const CALL_API = 'CALL_API';

function onSuccess(payload) {
  return {
    type: 'SUCCESS',
    payload
  };
}

function onError(payload) {
  return {
    type: 'ERROR',
    payload,
    error: true
  };
}

export function apiLogin(credentials) {
  return {
    onSuccess,
    onError,
    type: CALL_API,
    params: { ...credentials },
    method: 'post',
    url: 'login'
  };
}

middleware/api.js

import axios from 'axios';
import { CALL_API } from '../actions/api';

export default ({ getState, dispatch }) => next => async action => {
  // Ignore anything that's not calling the api
  if (action.type !== CALL_API) {
    return next(action);
  }

  // Grab the token from state
  const { token } = getState().session;

  // Format the request and attach the token.
  const { method, onSuccess, onError, params, url } = action;

  const defaultOptions = {
    headers: {
      Authorization: token ? `Token ${token}` : '',
    }
  };

  const options = {
    ...defaultOptions,
    ...params
  };

  try {
    const response = await axios[method](url, options);
    dispatch(onSuccess(response.data));
  } catch (error) {
    dispatch(onError(error.data));
  }

  return next(action);
};

Get individual query parameters from Uri

For isolated projects, where dependencies must be kept to a minimum, I found myself using this implementation:

var arguments = uri.Query
  .Substring(1) // Remove '?'
  .Split('&')
  .Select(q => q.Split('='))
  .ToDictionary(q => q.FirstOrDefault(), q => q.Skip(1).FirstOrDefault());

Do note, however, that I do not handle encoded strings of any kind, as I was using this in a controlled setting, where encoding issues would be a coding error on the server side that should be fixed.

Accessing a value in a tuple that is in a list

a = [(0,2), (4,3), (9,9), (10,-1)]
print(list(map(lambda item: item[1], a)))

Get root password for Google Cloud Engine VM

I tried "ManiIOT"'s solution and it worked surprisingly. I've added another role (Compute Admin Role) for my google user account from IAM admin. Then stopped and restarted the VM. Afterwards 'sudo passwd' let me to generate a new password for the user.

So here are steps.

  1. Go to IAM & Admin
  2. Select IAM
  3. Find your user name service account (basically your google account) and click Edit-member
  4. Add another role --> select 'Compute Engine' - 'Compute Admin'
  5. Restart your Compute VM
  6. open SSH shell and run the command 'sudo passwd'
  7. enter a brand new password. Voilà!

How to stop java process gracefully?

Thanks for you answers. Shutdown hooks seams like something that would work in my case. But I also bumped into the thing called Monitoring and Management beans:
http://java.sun.com/j2se/1.5.0/docs/guide/management/overview.html
That gives some nice possibilities, for remote monitoring, and manipulation of the java process. (Was introduced in Java 5)

Remove NaN from pandas series

If you have a pandas serie with NaN, and want to remove it (without loosing index):

serie = serie.dropna()

# create data for example
data = np.array(['g', 'e', 'e', 'k', 's']) 
ser = pd.Series(data)
ser.replace('e', np.NAN)
print(ser)

0      g
1    NaN
2    NaN
3      k
4      s
dtype: object

# the code
ser = ser.dropna()
print(ser)

0    g
3    k
4    s
dtype: object

How to transfer paid android apps from one google account to another google account

Google has this to say on transferring data between accounts.

http://support.google.com/accounts/bin/answer.py?hl=en&answer=63304

It lists certain types of data that CAN be transferred and certain types of data that CAN NOT be transferred. Unfortunately Google Play Apps falls into the NOT category.

It's conveniently titled: "Moving Product Data"

http://support.google.com/accounts/bin/answer.py?hl=en&answer=58582

jQuery .val() vs .attr("value")

this example may be useful:

_x000D_
_x000D_
<html>_x000D_
  <head>_x000D_
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>_x000D_
  </head>_x000D_
  <body>_x000D_
 <input id="test" type="text"  />_x000D_
 <button onclick="testF()" >click</button>_x000D_
 _x000D_
 _x000D_
 <script>_x000D_
 function testF(){_x000D_
 _x000D_
  alert($('#test').attr('value'));_x000D_
  alert( $('#test').prop('value'));_x000D_
  alert($('#test').val());_x000D_
  }_x000D_
 </script>_x000D_
  </body>_x000D_
 </html>
_x000D_
_x000D_
_x000D_

in above example, everything works perfectly. but if you change the version of jquery to 1.9.1 or newer in script tag you will see "undefined" in the first alert. attr('value') doesn't work with jquery version 1.9.1 or newer.

MySQL "Group By" and "Order By"

A simple solution is to wrap the query into a subselect with the ORDER statement first and applying the GROUP BY later:

SELECT * FROM ( 
    SELECT `timestamp`, `fromEmail`, `subject`
    FROM `incomingEmails` 
    ORDER BY `timestamp` DESC
) AS tmp_table GROUP BY LOWER(`fromEmail`)

This is similar to using the join but looks much nicer.

Using non-aggregate columns in a SELECT with a GROUP BY clause is non-standard. MySQL will generally return the values of the first row it finds and discard the rest. Any ORDER BY clauses will only apply to the returned column value, not to the discarded ones.

IMPORTANT UPDATE Selecting non-aggregate columns used to work in practice but should not be relied upon. Per the MySQL documentation "this is useful primarily when all values in each nonaggregated column not named in the GROUP BY are the same for each group. The server is free to choose any value from each group, so unless they are the same, the values chosen are indeterminate."

As of 5.7.5 ONLY_FULL_GROUP_BY is enabled by default so non-aggregate columns cause query errors (ER_WRONG_FIELD_WITH_GROUP)

As @mikep points out below the solution is to use ANY_VALUE() from 5.7 and above

See http://www.cafewebmaster.com/mysql-order-sort-group https://dev.mysql.com/doc/refman/5.6/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/group-by-handling.html https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_any-value

Date query with ISODate in mongodb doesn't seem to work

I am using robomongo as the mongodb client gui and the below worked for me

db.collectionName.find({"columnWithDateTime" : {
$lt:new ISODate("2016-02-28T00:00:00.000Z")}})

On the app side I am using nodejs based driver mongodb(v1.4.3),the application uses datepicker in the ui which gives date like YYYY-mm-dd, this is then appended with default time like 00:00:00 and then given to the new Date() constructor and then supplied to the mongodb criteria object,I think the driver converts the date to ISO date and the query then works and gives desired output, however the same new Date() constructor does not work or show same output on robo mongo,for the same criteria,which is weird,since I used robomongo to cross check my criteria objects.

Whereas the default cli mongoshell works well with both ISODate and new Date()

Adding a custom header to HTTP request using angular.js

Basic authentication using HTTP POST method:

$http({
    method: 'POST',
    url: '/API/authenticate',
    data: 'username=' + username + '&password=' + password + '&email=' + email,
    headers: {
        "Content-Type": "application/x-www-form-urlencoded",
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

...and GET method call with header:

$http({
    method: 'GET',
    url: '/books',
    headers: {
        'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
        'Accept': 'application/json',
        "X-Login-Ajax-call": 'true'
    }
}).then(function(response) {
    if (response.data == 'ok') {
        // success
    } else {
        // failed
    }
});

Add bottom line to view in SwiftUI / Swift / Objective-C / Xamarin

In SwiftUI, The simplest implementation would be,

struct MyTextField: View {
  var myPlaceHolder: String
  @Binding var text: String

  var underColor: Color
  var height: CGFloat

  var body: some View {
    VStack {
        TextField(self.myPlaceHolder, text: $text)
        .padding(.horizontal, 24)
        .font(.title)

        Rectangle().frame(height: self.height)
            .padding(.horizontal, 24).foregroundColor(self.underColor)
    }
  }
}

Usage:

MyTextField(myPlaceHolder: "PlaceHolder", text: self.$text, underColor: .red, height: 3)

Example Implementation

Get the second highest value in a MySQL table

To get the second highest salary just use the below query

SELECT salary FROM employees
ORDER BY salary DESC LIMIT 1,1;

Problems with entering Git commit message with Vim

Typically, git commit brings up an interactive editor (on Linux, and possibly Cygwin, determined by the contents of your $EDITOR environment variable) for you to edit your commit message in. When you save and exit, the commit completes.

You should make sure that the changes you are trying to commit have been added to the Git index; this determines what is committed. See http://gitref.org/basic/ for details on this.

What is the difference between JavaScript and jQuery?

Javascript is base of jQuery.

jQuery is a wrapper of JavaScript, with much pre-written functionality and DOM traversing.

Executing Batch File in C#

After some great help from steinar this is what worked for me:

public void ExecuteCommand(string command)
{
    int ExitCode;
    ProcessStartInfo ProcessInfo;
    Process process;

    ProcessInfo = new ProcessStartInfo(Application.StartupPath + "\\txtmanipulator\\txtmanipulator.bat", command);
    ProcessInfo.CreateNoWindow = true;
    ProcessInfo.UseShellExecute = false;
    ProcessInfo.WorkingDirectory = Application.StartupPath + "\\txtmanipulator";
    // *** Redirect the output ***
    ProcessInfo.RedirectStandardError = true;
    ProcessInfo.RedirectStandardOutput = true;

    process = Process.Start(ProcessInfo);
    process.WaitForExit();

    // *** Read the streams ***
    string output = process.StandardOutput.ReadToEnd();
    string error = process.StandardError.ReadToEnd();

    ExitCode = process.ExitCode;

    MessageBox.Show("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
    MessageBox.Show("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
    MessageBox.Show("ExitCode: " + ExitCode.ToString(), "ExecuteCommand");
    process.Close();
}

How to zero pad a sequence of integers in bash so that all have the same width?

If you want N digits, add 10^N and delete the first digit.

for (( num=100; num<=105; num++ ))
do
  echo ${num:1:3}
done

Output:

01
02
03
04
05

Get the number of rows in a HTML table

Well it depends on what you have in your table.

its one of the following If you have only one table

var count = $('#gvPerformanceResult tr').length;

If you are concerned about sub tables but this wont work with tbody and thead (if you use them)

var count = $('#gvPerformanceResult>tr').length;

Where by this will work (but is quite frankly overkill.)

var count = $('#gvPerformanceResult>tbody>tr').length;

git rebase merge conflict

When you have a conflict during rebase you have three options:

  • You can run git rebase --abort to completely undo the rebase. Git will return you to your branch's state as it was before git rebase was called.

  • You can run git rebase --skip to completely skip the commit. That means that none of the changes introduced by the problematic commit will be included. It is very rare that you would choose this option.

  • You can fix the conflict as iltempo said. When you're finished, you'll need to call git rebase --continue. My mergetool is kdiff3 but there are many more which you can use to solve conflicts. You only need to set your merge tool in git's settings so it can be invoked when you call git mergetool https://git-scm.com/docs/git-mergetool

If none of the above works for you, then go for a walk and try again :)

how to instanceof List<MyType>?

if(!myList.isEmpty() && myList.get(0) instanceof MyType){
    // MyType object
}

How can I install a local gem?

If you create your gems with bundler:

# do this in the proper directory
bundle gem foobar

You can install them with rake after they are written:

# cd into your gem directory
rake install

Chances are, that your downloaded gem will know rake install, too.

External VS2013 build error "error MSB4019: The imported project <path> was not found"

This is closely related but may or may not fix OPs specific issue. In my case I was trying to automate the deployment of an Azure site using VS2013. Building and deploying via VS works, however, using MSBuild showed a similar error around the "targets". Turns out MSBuild is different under VS2013, and is now part of VS and not the .Net Framework (see http://timrayburn.net/blog/visual-studio-2013-and-msbuild/). Basically, use the correct version of MSBuild:

OLD, VS2012

C:\Windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe

NEW, VS2013

C:\Program Files (x86)\MSBuild\12.0\bin\msbuild.exe

Newer, VS2015

C:\Program Files (x86)\MSBuild\14.0\Bin\msbuild.exe

Newer still, VS2017 (not fully testing but discovered - they've moved things around a bit)

C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\15.0\Bin\msbuild.exe

Displaying a vector of strings in C++

You ask two questions; your title says "Displaying a vector of strings", but you're not actually doing that, you actually build a single string composed of all the strings and output that.

Your question body asks "Why doesn't this work".

It doesn't work because your for loop is constrained by "userString.size()" which is 0, and you test your loop variable for being "userString.size() - 1". The condition of a for() loop is tested before permitting execution of the first iteration.

int n = 1;
for (int i = 1; i < n; ++i) {
    std::cout << i << endl;
}

will print exactly nothing.

So your loop executes exactly no iterations, leaving userString and sentence empty.

Lastly, your code has absolutely zero reason to use a vector. The fact that you used "decltype(userString.size())" instead of "size_t" or "auto", while claiming to be a rookie, suggests you're either reading a book from back to front or you are setting yourself up to fail a class.

So to answer your question at the end of your post: It doesn't work because you didn't step through it with a debugger and inspect the values as it went. While I say it tongue-in-cheek, I'm going to leave it out there.

Set and Get Methods in java?

Having accessor methods is preferred to accessing fields directly, because it controls how fields are accessed (may impose data checking etc) and fits with interfaces (interfaces can not requires fields to be present, only methods).

Getting the parent div of element

This might help you.

ParentID = pDoc.offsetParent;
alert(ParentID.id); 

How do check if a parameter is empty or null in Sql Server stored procedure in IF statement?

that is the right behavior.

if you set @item1 to a value the below expression will be true

IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)

Anyway in SQL Server there is not a such function but you can create your own:

CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
    RETURN 0
ELSE
    RETURN 1
END

Convert named list to vector with values only

purrr::flatten_*() is also a good option. the flatten_* functions add thin sanity checks and ensure type safety.

myList <- list('A'=1, 'B'=2, 'C'=3)

purrr::flatten_dbl(myList)
## [1] 1 2 3

web.xml is missing and <failOnMissingWebXml> is set to true

You can do it also like this:

  1. Right click on Deployment Descriptor in Project Explorer.
  2. Select Generate Deployment Descriptor Stub.

It will generate WEB-INF folder in src/main/webapp and an web.xml in it.

enter image description here

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

IF NOT EXISTS(SELECT * FROM Clock
WHERE clockDate = '08/10/2012') AND userName = 'test')

Has an extra parenthesis. I think it's fine if you remove it:

IF NOT EXISTS(SELECT * FROM Clock WHERE
clockDate = '08/10/2012' AND userName = 'test')

Also, GETDATE() will put the current date in the column, though if you don't want the time you'll have to play a little. I think CONVERT(varchar(8), GETDATE(), 112) would give you just the date (not time) portion.

IF NOT EXISTS(SELECT * FROM Clock WHERE
clockDate = CONVERT(varchar(8), GETDATE(), 112)
AND userName = 'test')

should probably do it.

PS: use a merge statement :)

Eclipse Optimize Imports to Include Static Imports

Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to

Window->Preferences->Java->Editor->Content Assist

and check the checkbox for Use static imports (only 1.5 or higher).

This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.

MongoDB - Update objects in a document's array (nested updating)

For question #1, let's break it into two parts. First, increment any document that has "items.item_name" equal to "my_item_two". For this you'll have to use the positional "$" operator. Something like:

 db.bar.update( {user_id : 123456 , "items.item_name" : "my_item_two" } , 
                {$inc : {"items.$.price" : 1} } , 
                false , 
                true);

Note that this will only increment the first matched subdocument in any array (so if you have another document in the array with "item_name" equal to "my_item_two", it won't get incremented). But this might be what you want.

The second part is trickier. We can push a new item to an array without a "my_item_two" as follows:

 db.bar.update( {user_id : 123456, "items.item_name" : {$ne : "my_item_two" }} , 
                {$addToSet : {"items" : {'item_name' : "my_item_two" , 'price' : 1 }} } ,
                false , 
                true);

For your question #2, the answer is easier. To increment the total and the price of item_three in any document that contains "my_item_three," you can use the $inc operator on multiple fields at the same time. Something like:

db.bar.update( {"items.item_name" : {$ne : "my_item_three" }} ,
               {$inc : {total : 1 , "items.$.price" : 1}} ,
               false ,
               true);

printf not printing on console

As others have pointed out, output can be buffered within your program before a console or shell has a chance to see it.

On unix-like systems, including macs, stdout has line-based buffering by default. This means that your program empties its stdout buffer as soon as it sees a newline.

However, on windows, newlines are no longer special, and full buffering is used. Windows doesn't support line buffering at all; see the msdn page on setvbuf.

So on windows, a good approach is to completely shut off stdout buffering like so:

setvbuf (stdout, NULL, _IONBF, 0);

How to delete a cookie using jQuery?

To delete a cookie with JQuery, set the value to null:

$.cookie("name", null, { path: '/' });

Edit: The final solution was to explicitly specify the path property whenever accessing the cookie, because the OP accesses the cookie from multiple pages in different directories, and thus the default paths were different (this was not described in the original question). The solution was discovered in discussion below, which explains why this answer was accepted - despite not being correct.

For some versions jQ cookie the solution above will set the cookie to string null. Thus not removing the cookie. Use the code as suggested below instead.

$.removeCookie('the_cookie', { path: '/' });

jQuery.parseJSON throws “Invalid JSON” error due to escaped single quote in JSON

I was trying to save a JSON object from a XHR request into a HTML5 data-* attribute. I tried many of above solutions with no success.

What I finally end up doing was replacing the single quote ' with it code &#39; using a regex after the stringify() method call the following way:

var productToString = JSON.stringify(productObject);
var quoteReplaced = productToString.replace(/'/g, "&#39;");
var anchor = '<a data-product=\'' + quoteReplaced + '\' href=\'#\'>' + productObject.name + '</a>';
// Here you can use the "anchor" variable to update your DOM element.

Add CSS to <head> with JavaScript?

Here's a simple way.

/**
 * Add css to the document
 * @param {string} css
 */
function addCssToDocument(css){
  var style = document.createElement('style')
  style.innerText = css
  document.head.appendChild(style)
}

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

The error is caused by the number of class dependencies you have in your app Gradle file. If the classes exceed 72,400, you might want to use multidex as a solution to better handle file indexing. Findout more from here: https://developer.android.com/studio/build/multidex

Angular 4 default radio button checked by default

getting following error

_x000D_
_x000D_
It happens:  Error: 
      ngModel cannot be used to register form controls with a parent formGroup directive.  Try using
      formGroup's partner directive "formControlName" instead.  Example:
_x000D_
_x000D_
_x000D_

Visual Studio 2010 - recommended extensions

CodeMaid seems to be pretty useful - it AutoFormats on save which saves a lot of time between developers and code-diffs. (Are there other tools that can use the VS AutoFormat document?)

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Define static method in source-file with declaration in header-file in C++

Remove static keyword in method definition. Keep it just in your class definition.

static keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.

git rebase: "error: cannot stat 'file': Permission denied"

I've just had this problem. The thing is - if you had opened file, that was removed\replaced after rebase (you had a branch which doesn't have a this file anymore), the git-system corrupts. So i closed all opened files and then tryied to checkout on some other branch

Quick way to list all files in Amazon S3 bucket?

Use plumbum to wrap the cli and you will have a clear syntax:

import plumbum as pb
folders = pb.local['aws']('s3', 'ls')

cordova Android requirements failed: "Could not find an installed version of Gradle"

To answer OP's question:

Since you're on Linux you'll have to install gradle yourself, perhaps following this guide, and then put an entry in PATH to a folder that contains gradle executable.

Cordova has some code to look for gradle if you have Android Studio but only for Mac and Windows, see here:

https://github.com/apache/cordova-android/blob/e13e15d3e9aa4b9a61c6ece434e7c023fa5c3553/bin/templates/cordova/lib/check_reqs.js#L101-L132


Semi-related to OP's question, as I'm on Windows.

After upgrading to Android Studio 2.3.1, [email protected], [email protected] ([email protected]), I had build issues due missing target 25 and gradle.

First issue was solved with comment from X.Zhang (i.e. change android to avdmanager), BTW it seems a commit to fix that has landed on github so cordova-android should fix that in 6.3.0 (but I didn't test).

Second issue was as follows:

The problem turned out to be that process.env['ProgramFiles'] evaluates to 'C:\\Program Files (x86)'; whereas I have Android Studio in C:\\Program Files.

So the quick hack is to either override this value, or install Android Studio to the other place.

// platforms/android/cordova/lib/check_reqs.js

module.exports.get_gradle_wrapper = function() {
    var androidStudioPath;
    var i = 0;
    var foundStudio = false;
    var program_dir;
    if (module.exports.isDarwin()) {
        // ...
    } else if (module.exports.isWindows()) {
        // console.log(process.env['ProgramFiles'])';
        // add one of the lines below to have a quick fix...
        // process.env['ProgramFiles'] = 'C:\\Program Files (x86)';
        // process.env['ProgramFiles'] = 'C:\\Program Files';
        var androidPath = path.join(process.env['ProgramFiles'], 'Android') + '/';

I'm not sure what would be the proper fix to handle both folders in a robust way (other than iterating over both folders).

Obviously this has to be fixed in cordova-android project itself; otherwise whenever you do cordova platform rm your fixes will be gone.

I opened the ticket on Cordova JIRA:

https://issues.apache.org/jira/browse/CB-12677

Convert JS date time to MySQL datetime

I think the solution can be less clunky by using method toISOString(), it has a wide browser compatibility.

So your expression will be a one-liner:

new Date().toISOString().slice(0, 19).replace('T', ' ');

The generated output:

"2017-06-29 17:54:04"

Eclipse reported "Failed to load JNI shared library"

First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).

Second, the -vm argument in eclipse.ini should point to the java executable. See http://wiki.eclipse.org/Eclipse.ini for examples.

If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?

Best data type to store money values in MySQL

If your application needs to handle money values up to a trillion then this should work: 13,2 If you need to comply with GAAP (Generally Accepted Accounting Principles) then use: 13,4

Usually you should sum your money values at 13,4 before rounding of the output to 13,2.

CSS3 selector :first-of-type with class name?

Not sure how to explain this but I ran into something similar today. Not being able to set .user:first-of-type{} while .user:last-of-type{} worked fine. This was fixed after I wrapped them inside a div without any class or styling:

https://codepen.io/adrianTNT/pen/WgEpbE

<style>
.user{
  display:block;
  background-color:#FFCC00;
}

.user:first-of-type{
  background-color:#FF0000;
}
</style>

<p>Not working while this P additional tag exists</p>

<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>

<p>Working while inside a div:</p>

<div>
<p class="user">A</p>
<p class="user">B</p>
<p class="user">C</p>
</div>

(413) Request Entity Too Large | uploadReadAheadSize

For me, setting the uploadReadAheadSize to int.MaxValue also fixed the problem, after also increasing the limits on the WCF binding.

It seems that, when using SSL, the entire request entity body is preloaded, for which this metabase property is used.

For more info, see:

The page was not displayed because the request entity is too large. iis7

How to convert JSON object to JavaScript array?

function json2array(json){
    var result = [];
    var keys = Object.keys(json);
    keys.forEach(function(key){
        result.push(json[key]);
    });
    return result;
}

See this complete explanation: http://book.mixu.net/node/ch5.html

AngularJS Uploading An Image With ng-upload

There's little-no documentation on angular for uploading files. A lot of solutions require custom directives other dependencies (jquery in primis... just to upload a file...). After many tries I've found this with just angularjs (tested on v.1.0.6)

html

<input type="file" name="file" onchange="angular.element(this).scope().uploadFile(this.files)"/>

Angularjs (1.0.6) not support ng-model on "input-file" tags so you have to do it in a "native-way" that pass the all (eventually) selected files from the user.

controller

$scope.uploadFile = function(files) {
    var fd = new FormData();
    //Take the first selected file
    fd.append("file", files[0]);

    $http.post(uploadUrl, fd, {
        withCredentials: true,
        headers: {'Content-Type': undefined },
        transformRequest: angular.identity
    }).success( ...all right!... ).error( ..damn!... );

};

The cool part is the undefined content-type and the transformRequest: angular.identity that give at the $http the ability to choose the right "content-type" and manage the boundary needed when handling multipart data.

How to link a folder with an existing Heroku app

heroku login 

git init

heroku git:remote -a app-name123

then check the remote repo :

git remote -v

Display an image with Python

Your first suggestion works for me

from IPython.display import display, Image
display(Image(filename='path/to/image.jpg'))

linux script to kill java process

If you just want to kill any/all java processes, then all you need is;

killall java

If, however, you want to kill the wskInterface process in particular, then you're most of the way there, you just need to strip out the process id;

PID=`ps -ef | grep wskInterface | awk '{ print $2 }'`
kill -9 $PID

Should do it, there is probably an easier way though...

Validate email with a regex in jQuery

function mailValidation(val) {
    var expr = /^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$/;

    if (!expr.test(val)) {
        $('#errEmail').text('Please enter valid email.');
    }
    else {
        $('#errEmail').hide();
    }
}

Git Commit Messages: 50/72 Formatting

Separation of presentation and data drives my commit messages here.

Your commit message should not be hard-wrapped at any character count and instead line breaks should be used to separate thoughts, paragraphs, etc. as part of the data, not the presentation. In this case, the "data" is the message you are trying to get across and the "presentation" is how the user sees that.

I use a single summary line at the top and I try to keep it short but I don't limit myself to an arbitrary number. It would be far better if Git actually provided a way to store summary messages as a separate entity from the message but since it doesn't I have to hack one in and I use the first line break as the delimiter (luckily, many tools support this means of breaking apart the data).

For the message itself newlines indicate something meaningful in the data. A single newline indicates a start/break in a list and a double newline indicates a new thought/idea.

This is a summary line, try to keep it short and end with a line break.
This is a thought, perhaps an explanation of what I have done in human readable format.  It may be complex and long consisting of several sentences that describe my work in essay format.  It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts.  The user may be reading this on a phone or a wide screen monitor.  Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across?  It is a truly painful experience.  Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph.  Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

Here's what it looks like in a viewer that soft wraps the text.

This is a summary line, try to keep it short and end with a line break.

This is a thought, perhaps an explanation of what I have done in human readable format. It may be complex and long consisting of several sentences that describe my work in essay format. It is not up to me to decide now (at author time) how the user is going to consume this data.

Two line breaks separate these two thoughts. The user may be reading this on a phone or a wide screen monitor. Have you ever tried to read 72 character wrapped text on a device that only displays 60 characters across? It is a truly painful experience. Also, the opening sentence of this paragraph (assuming essay style format) should be an intro into the paragraph so if a tool chooses it may want to not auto-wrap and let you just see the start of each paragraph. Again, it is up to the presentation tool not me (a random author at some point in history) to try to force my particular formatting down everyone else's throat.

Just as an example, here is a list of points:
* Point 1.
* Point 2.
* Point 3.

My suspicion is that the author of Git commit message recommendation you linked has never written software that will be consumed by a wide array of end-users on different devices before (i.e., a website) since at this point in the evolution of software/computing it is well known that storing your data with hard-coded presentation information is a bad idea as far as user experience goes.

Calling a class method raises a TypeError in Python

In python member function of a class need explicit self argument. Same as implicit this pointer in C++. For more details please check out this page.

What should I set JAVA_HOME environment variable on macOS X 10.6?

I tend to use /Library/Java/Home. The way the preferences pane works this should be up to date with your preferred version.

How do I open phone settings when a button is clicked?

Using UIApplication.openSettingsURLString

Update for Swift 5.1

 override func viewDidAppear(_ animated: Bool) {
    let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in

        guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
            return
        }

        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                print("Settings opened: \(success)") // Prints true
            })
        }
    }
    alertController.addAction(settingsAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)
}

Swift 4.2

override func viewDidAppear(_ animated: Bool) {
    let alertController = UIAlertController (title: "Title", message: "Go to Settings?", preferredStyle: .alert)

    let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in

        guard let settingsUrl = URL(string: UIApplicationOpenSettingsURLString) else {
            return
        }

        if UIApplication.shared.canOpenURL(settingsUrl) {
            UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
                print("Settings opened: \(success)") // Prints true
            })
        }
    }
    alertController.addAction(settingsAction)
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(cancelAction)

    present(alertController, animated: true, completion: nil)
}

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

What's the best way to store Phone number in Django models

It all depends in what you understand as phone number. Phone numbers are country specific. The localflavors packages for several countries contains their own "phone number field". So if you are ok being country specific you should take a look at localflavor package (class us.models.PhoneNumberField for US case, etc.)

Otherwise you could inspect the localflavors to get the maximun lenght for all countries. Localflavor also has forms fields you could use in conjunction with the country code to validate the phone number.

Base64: java.lang.IllegalArgumentException: Illegal character

Your encoded text is [B@6499375d. That is not Base64, something went wrong while encoding. That decoding code looks good.

Use this code to convert the byte[] to a String before adding it to the URL:

String encodedEmailString = new String(encodedEmail, "UTF-8");
// ...
String confirmLink = "Complete your registration by clicking on following"
    + "\n<a href='" + confirmationURL + encodedEmailString + "'>link</a>";

Remove duplicated rows using dplyr

Most of the time, the best solution is using distinct() from dplyr, as has already been suggested.

However, here's another approach that uses the slice() function from dplyr.

# Generate fake data for the example
  library(dplyr)
  set.seed(123)
  df <- data.frame(
    x = sample(0:1, 10, replace = T),
    y = sample(0:1, 10, replace = T),
    z = 1:10
  )

# In each group of rows formed by combinations of x and y
# retain only the first row

    df %>%
      group_by(x, y) %>%
      slice(1)

Difference from using the distinct() function

The advantage of this solution is that it makes it explicit which rows are retained from the original dataframe, and it can pair nicely with the arrange() function.

Let's say you had customer sales data and you wanted to retain one record per customer, and you want that record to be the one from their latest purchase. Then you could write:

customer_purchase_data %>%
   arrange(desc(Purchase_Date)) %>%
   group_by(Customer_ID) %>%
   slice(1)

Is it possible to get an Excel document's row count without loading the entire document into memory?

Adding on to what Hubro said, apparently get_highest_row() has been deprecated. Using the max_row and max_column properties returns the row and column count. For example:

    wb = load_workbook(path, use_iterators=True)
    sheet = wb.worksheets[0]

    row_count = sheet.max_row
    column_count = sheet.max_column

Getting Checkbox Value in ASP.NET MVC 4

I read through the other answers and wasn't quite getting it to work - so here's the solution I ended up with.

My form uses the Html.EditorFor(e => e.Property) to generate the checkbox, and using FormCollection in the controller, this passes a string value of 'true,false' in the controller.

When I'm handling the results I use a loop to cycle through them - I also use an InfoProperty instance to represent the current model value being assessed from the form.

So instead I just check if the string returned starts with the word 'true' and then set a boolean variable to true and pass that into the return model.

if (KeyName.EndsWith("OnOff"))
{
    // set on/off flags value to the model instance
    bool keyTrueFalse = false;
    if(values[KeyName].StartsWith("true"))
    {
        keyTrueFalse = true;
    }
    infoProperty.SetValue(processedInfo, keyTrueFalse);
}

How to close current tab in a browser window?

Try this as well. Working for me on all three major browsers.

<!-- saved from url=(0014)about:internet -->
<a href="#" onclick="javascript:window.close();opener.window.focus();" >Close Window</a>

Keep-alive header clarification

Where is this info kept ("this connection is between computer A and server F")?

A TCP connection is recognized by source IP and port and destination IP and port. Your OS, all intermediate session-aware devices and the server's OS will recognize the connection by this.

HTTP works with request-response: client connects to server, performs a request and gets a response. Without keep-alive, the connection to an HTTP server is closed after each response. With HTTP keep-alive you keep the underlying TCP connection open until certain criteria are met.

This allows for multiple request-response pairs over a single TCP connection, eliminating some of TCP's relatively slow connection startup.

When The IIS (F) sends keep alive header (or user sends keep-alive) , does it mean that (E,C,B) save a connection

No. Routers don't need to remember sessions. In fact, multiple TCP packets belonging to same TCP session need not all go through same routers - that is for TCP to manage. Routers just choose the best IP path and forward packets. Keep-alive is only for client, server and any other intermediate session-aware devices.

which is only for my session ?

Does it mean that no one else can use that connection

That is the intention of TCP connections: it is an end-to-end connection intended for only those two parties.

If so - does it mean that keep alive-header - reduce the number of overlapped connection users ?

Define "overlapped connections". See HTTP persistent connection for some advantages and disadvantages, such as:

  • Lower CPU and memory usage (because fewer connections are open simultaneously).
  • Enables HTTP pipelining of requests and responses.
  • Reduced network congestion (fewer TCP connections).
  • Reduced latency in subsequent requests (no handshaking).

if so , for how long does the connection is saved to me ? (in other words , if I set keep alive- "keep" till when?)

An typical keep-alive response looks like this:

Keep-Alive: timeout=15, max=100

See Hypertext Transfer Protocol (HTTP) Keep-Alive Header for example (a draft for HTTP/2 where the keep-alive header is explained in greater detail than both 2616 and 2086):

  • A host sets the value of the timeout parameter to the time that the host will allows an idle connection to remain open before it is closed. A connection is idle if no data is sent or received by a host.

  • The max parameter indicates the maximum number of requests that a client will make, or that a server will allow to be made on the persistent connection. Once the specified number of requests and responses have been sent, the host that included the parameter could close the connection.

However, the server is free to close the connection after an arbitrary time or number of requests (just as long as it returns the response to the current request). How this is implemented depends on your HTTP server.

How to restart remote MySQL server running on Ubuntu linux?

Another way is:

systemctl restart mysql

How to specify jackson to only use fields - preferably globally

for jackson 1.9.10 I use

ObjectMapper mapper = new ObjectMapper();

mapper.setVisibility(JsonMethod.ALL, Visibility.NONE);
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

to turn of auto dedection.

Sending simple message body + file attachment using Linux Mailx

Johnsyweb's answer didn't work for me, but it works for me with Mutt:

echo "Message body" | mutt -s "Message subject" -a myfile.txt [email protected]

How to iterate over array of objects in Handlebars?

Using this and {{this}}. See code below in node.js:

var Handlebars= require("handlebars");
var randomList= ["James Bond", "Dr. No", "Octopussy", "Goldeneye"];
var source= "<ul>{{#each this}}<li>{{this}}</li>{{/each}}</ul>";
var template= Handlebars.compile(source);
console.log(template(randomList));

Console log output:

<ul><li>James Bond</li><li>Dr. No</li><li>Octopussy</li><li>Goldeneye</li></ul>

What's the best practice for primary keys in tables?

All tables should have a primary key. Otherwise, what you have is a HEAP - this, in some situations, might be what you want (heavy insert load when the data is then replicated via a service broker to another database or table for instance).

For lookup tables with a low volume of rows, you can use a 3 CHAR code as the primary key as this takes less room than an INT, but the performance difference is negligible. Other than that, I would always use an INT unless you have a reference table that perhaps has a composite primary key made up from foreign keys from associated tables.

How do I separate an integer into separate digits in an array in JavaScript?

(123456789).toString(10).split("")

^^ this will return an array of strings

(123456789).toString(10).split("").map(function(t){return parseInt(t)})

^^ this will return an array of ints

How to change line color in EditText

Use this method.. and modify it according to ur view names. This code works great.

 private boolean validateMobilenumber() {
            if (mobilenumber.getText().toString().trim().isEmpty() || mobilenumber.getText().toString().length() < 10) {
                input_layout_mobilenumber.setErrorEnabled(true);
                input_layout_mobilenumber.setError(getString(R.string.err_msg_mobilenumber));
               // requestFocus(mobilenumber);
                return false;
            } else {
                input_layout_mobilenumber.setError(null);
                input_layout_mobilenumber.setErrorEnabled(false);
                mobilenumber.setBackground(mobilenumber.getBackground().getConstantState().newDrawable());
            }

Is the LIKE operator case-sensitive with MSSQL Server?

The like operator takes two strings. These strings have to have compatible collations, which is explained here.

In my opinion, things then get complicated. The following query returns an error saying that the collations are incompatible:

select *
from INFORMATION_SCHEMA.TABLES
where 'abc' COLLATE SQL_Latin1_General_CP1_CI_AS like 'ABC' COLLATE SQL_Latin1_General_CP1_CS_AS

On a random machine here, the default collation is SQL_Latin1_General_CP1_CI_AS. The following query is successful, but returns no rows:

select *
from INFORMATION_SCHEMA.TABLES
where 'abc' like 'ABC' COLLATE SQL_Latin1_General_CP1_CS_AS

The values "abc" and "ABC" do not match in a case-sensitve world.

In other words, there is a difference between having no collation and using the default collation. When one side has no collation, then it is "assigned" an explicit collation from the other side.

(The results are the same when the explicit collation is on the left.)

invalid byte sequence for encoding "UTF8"

copy tablename from 'filepath\filename' DELIMITERS '=' ENCODING 'WIN1252';

you can try this to handle UTF8 encoding.

What causes this error? "Runtime error 380: Invalid property value"

I presume your application uses a masked edit box? This is a relatively well known problem, documented by Microsoft here:

http://support.microsoft.com/kb/177088

The article refers to VB4 and 5, but I am pretty sure the same is true for VB6.

EDIT

On further research, I am finding references to this problem with other controls as well. Recompiling your application on Windows XP for users that are running XP will probably produce them a working version, though it's not an ideal solution...

How to take off line numbers in Vi?

If you are talking about show line number command in vi/vim

you could use

set nu

in commandline mode to turn on and

set nonu

will turn off the line number display or

set nu!

to toggle off display of line numbers

jQuery Event Keypress: Which key was pressed?

... this example prevents form submission (regularly the basic intention when capturing keystroke #13):

$('input#search').keypress(function(e) {
  if (e.which == '13') {
     e.preventDefault();
     doSomethingWith(this.value);
   }
});

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

For some databases, you can just explicitly insert a NULL into the auto_increment column:

INSERT INTO table_name VALUES (NULL, 'my name', 'my group')

How can I store HashMap<String, ArrayList<String>> inside a list?

First, let me fix a little bit your declaration:

List<Map<String, List<String>>> listOfMapOfList = 
    new HashList<Map<String, List<String>>>();

Please pay attention that I used concrete class (HashMap) only once. It is important to use interface where you can to be able to change the implementation later.

Now you want to add element to the list, don't you? But the element is a map, so you have to create it:

Map<String, List<String>> mapOfList = new HashMap<String, List<String>>();

Now you want to populate the map. Fortunately you can use utility that creates lists for you, otherwise you have to create list separately:

mapOfList.put("mykey", Arrays.asList("one", "two", "three"));

OK, now we are ready to add the map into the list:

listOfMapOfList.add(mapOfList);

BUT:

Stop creating complicated collections right now! Think about the future: you will probably have to change the internal map to something else or list to set etc. This will probably cause you to re-write significant parts of your code. Instead define class that contains you data and then add it to one-dimentional collection:

Let's call your class Student (just as example):

public Student {
    private String firstName;
    private String lastName;
    private int studentId;

    private Colectiuon<String> courseworks = Collections.emtpyList();

    //constructors, getters, setters etc
}

Now you can define simple collection:

Collection<Student> students = new ArrayList<Student>();

If in future you want to put your students into map where key is the studentId, do it:

Map<Integer, Student> students = new HashMap<Integer, Student>();

Validating file types by regular expression

You can embed case insensitity into the regular expression like so:

\.(?i:)(?:jpg|gif|doc|pdf)$

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

For Swift 3 and Xcode 8:

      var dataTask: URLSessionDataTask?

      if  let url = URL(string: urlString) {
            self.dataTask = URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in

                if let error = error {
                    print(error.localizedDescription)
                } else if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
                     // You can use data received.
                    self.process(data: data as Data?)
                }
            })
        }
     }

//Note: You can always use debugger to check error

PostgreSQL database service

Checking the port may work.

On pgAdmin page at the top, go to Properties and check the port if it is same with the one provided during the setup. If not click the edit button on the top right and change the port.

How to right-align and justify-align in Markdown?

If you want to use justify align in Jupyter Notebook use the following syntax:

<p style='text-align: justify;'> Your Text </p>

For right alignment:

<p style='text-align: right;'> Your Text </p>

Is it wrong to place the <script> tag after the </body> tag?

Modern browsers will take script tags in the body like so:

<body>
    <script src="scripts/main.js"></script>
</body>

Basically, it means that the script will be loaded once the page has finished, which may be useful in certain cases (namely DOM manipulation). However, I highly recommend you take the same script and put it in the head tag with "defer", as it will give the same effect.

<head>
    <script src="scripts/main.js" defer></script>
</head>

Add/delete row from a table

Here's the code JS Bin using jQuery. Tested on all the browsers. Here, we have to click the rows in order to delete it with beautiful effect. Hope it helps.

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

How to get javax.comm API?

Use RXTX.

On Debian install librxtx-java by typing:

sudo apt-get install librxtx-java

On Fedora or Enterprise Linux install rxtx by typing:

sudo yum install rxtx

Laravel 5 Class 'form' not found

Just type the following command in terminal at the project directory and installation is done according the Laravel version:

composer require "laravelcollective/html"

Then add these lines in config/app.php

'providers' => [
    // ...
    Collective\Html\HtmlServiceProvider::class,
    // ...
],

'aliases' => [
    // ...
   'Form' => Collective\Html\FormFacade::class,
   'Html' => Collective\Html\HtmlFacade::class,
    // ...
],

CSS force image resize and keep aspect ratio

I've struggled with this problem quite hard, and eventually arrived at this simple solution:

object-fit: cover;
width: 100%;
height: 250px;

You can adjust the width and height to fit your needs, and the object-fit property will do the cropping for you.

More information about the possible values for the object-fit property and a compatibility table are available here: https://developer.mozilla.org/en-US/docs/Web/CSS/object-fit

Cheers.

What can lead to "IOError: [Errno 9] Bad file descriptor" during os.system()?

You can get this error if you use wrong mode when opening the file. For example:

    with open(output, 'wb') as output_file:
        print output_file.read()

In that code, I want to read the file, but I use mode wb instead of r or r+

Deserializing JSON Object Array with Json.net

For those who don't want to create any models, use the following code:

var result = JsonConvert.DeserializeObject<
  List<Dictionary<string, 
    Dictionary<string, string>>>>(content);

Note: This doesn't work for your JSON string. This is not a general solution for any JSON structure.

How to run different python versions in cmd

Python 3.3 introduces Python Launcher for Windows that is installed into c:\Windows\ as py.exe and pyw.exe by the installer. The installer also creates associations with .py and .pyw. Then add #!python3 or #!python2 as the first lline. No need to add anything to the PATH environment variable.

Update: Just install Python 3.3 from the official python.org/download. It will add also the launcher. Then add the first line to your script that has the .py extension. Then you can launch the script by simply typing the scriptname.py on the cmd line, od more explicitly by py scriptname.py, and also by double clicking on the scipt icon.

The py.exe looks for C:\PythonXX\python.exe where XX is related to the installed versions of Python at the computer. Say, you have Python 2.7.6 installed into C:\Python27, and Python 3.3.3 installed into C:\Python33. The first line in the script will be used by the Python launcher to choose one of the installed versions. The default (i.e. without telling the version explicitly) is to use the highest version of Python 2 that is available on the computer.

phpinfo() - is there an easy way for seeing it?

If you are using WAMP then type the following in the browser
http://localhost/?phpinfo=-1, you will get the phpinfo page.

phpinfo() from localhost

You can also click the localhost icon in the wamp menu from the systray and then find the phpinfo page. WAMP localhost from WAMP Menu

html cellpadding the left side of a cell

I choose to use both methods. Cellpadding on the table as a fallback in case the inline style doesn't stick and inline style for most clients.

_x000D_
_x000D_
<table cellpadding="5">_x000D_
  <tr>_x000D_
    <td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
    <td style='padding:5px 10px 5px 5px'>Content</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to display and hide a div with CSS?

Html Code :

    <a id="f">Show First content!</a>
    <br/>
    <a id="s">Show Second content!!</a>
    <div class="a">Default Content</div>
    <div class="ab hideDiv">First content</div>
    <div class="abc hideDiv">Second content</div>

Script code:

$(document).ready(function() {
    $("#f").mouseover(function(){
        $('.a,.abc').addClass('hideDiv');
        $('.ab').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });

    $("#s").mouseover(function(){
        $('.a,.ab').addClass('hideDiv');
        $('.abc').removeClass('hideDiv');
    }).mouseout(function() {
        $('.a').removeClass('hideDiv');
        $('.ab,.abc').addClass('hideDiv');
    });
});

css code:

.hideDiv
{
    display:none;
}

PHP: How can I determine if a variable has a value that is between two distinct constant values?

if (($value >= 1 && $value <= 10) || ($value >= 20 && $value <= 40)) {
   // A value between 1 to 10, or 20 to 40.
}

Where to find the win32api module for Python?

There is a a new option as well: get it via pip! There is a package pypiwin32 with wheels available, so you can just install with: pip install pypiwin32!

Edit: Per comment from @movermeyer, the main project now publishes wheels at pywin32, and so can be installed with pip install pywin32

How do you truncate all tables in a database using TSQL?

select 'delete from ' +TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_TYPE='BASE TABLE'

where result come.

Copy and paste on query window and run the command

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

Process.start: how to get the output?

When you create your Process object set StartInfo appropriately:

var proc = new Process 
{
    StartInfo = new ProcessStartInfo
    {
        FileName = "program.exe",
        Arguments = "command line arguments to your executable",
        UseShellExecute = false,
        RedirectStandardOutput = true,
        CreateNoWindow = true
    }
};

then start the process and read from it:

proc.Start();
while (!proc.StandardOutput.EndOfStream)
{
    string line = proc.StandardOutput.ReadLine();
    // do something with line
}

You can use int.Parse() or int.TryParse() to convert the strings to numeric values. You may have to do some string manipulation first if there are invalid numeric characters in the strings you read.

403 Forbidden You don't have permission to access /folder-name/ on this server

if permission issue and you have ssh access in root folder

find . -type d -exec chmod 755 {} \;
find . -type f -exec chmod 644 {} \;

will resolve your error

TensorFlow not found using pip

I've found out the problem.

I'm using a Windows computer which has Python 2 installed previously. After Python 3 is installed (without setting the path, I successfully check the version of pip3 - but the python executable file still points to the Python2)

Then I set the path to the python3 executable file (remove all python2 paths) then start a new command prompt, try to reinstall Tensorflow. It works!

I think this problem could happend on MAC OS too since there is a default python which is on the MAC system.

Bootstrap : TypeError: $(...).modal is not a function

I was getting the same error because of jquery CDN (<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>) was added two times in the HTML head.

Java Best Practices to Prevent Cross Site Scripting

Use both. In fact refer a guide like the OWASP XSS Prevention cheat sheet, on the possible cases for usage of output encoding and input validation.

Input validation helps when you cannot rely on output encoding in certain cases. For instance, you're better off validating inputs appearing in URLs rather than encoding the URLs themselves (Apache will not serve a URL that is url-encoded). Or for that matter, validate inputs that appear in JavaScript expressions.

Ultimately, a simple thumb rule will help - if you do not trust user input enough or if you suspect that certain sources can result in XSS attacks despite output encoding, validate it against a whitelist.

Do take a look at the OWASP ESAPI source code on how the output encoders and input validators are written in a security library.

Getting the "real" Facebook profile picture URL from graph API

$url = 'http://graph.facebook.com/100000771470028/picture?type=large';
$rray=get_headers($url);
$hd = $rray[4];
echo(substr($hd,strpos($hd,'http')));

This will return the url that you asked, and the problem of changing the url by facebook doesn't matter because you are dynamically calling the url from the original url.

How to format background color using twitter bootstrap?

Bootstrap default "contextual backgrounds" helper classes to change the background color:

.bg-primary
.bg-default
.bg-info
.bg-warning
.bg-danger

If you need set custom background color then, you can write your own custom classes in style.css( a custom css file) example below

.bg-pink
{
  background-color: #CE6F9E;
}

Test if executable exists in Python?

Use shutil.which() from Python's wonderful standard library. Batteries included!

Javascript to convert UTC to local time

The solutions above are right but might crash in FireFox and Safari! and that's what webility.js is trying to solve. Check the toUTC function, it works on most of the main browers and it returns the time in ISO format

Java Minimum and Maximum values in Array

getMaxValue(array);
// get smallest number
getMinValue(array);

You are calling the methods but not using the returned values.

System.out.println(getMaxValue(array));
System.out.println(getMinValue(array)); 

Tooltips with Twitter Bootstrap

I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:

<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>

Then you can trigger all links with the .link class attached as tooltips like so:

$('.link').tooltip()

Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel attribute. With this attribute you can target all links or elements with the rel property set to tooltip, like so:

$('[rel=tooltip]').tooltip() 

And your links would look like something like this:

<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>

Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:

$('#example').tooltip({
    selector: "a[rel=tooltip]"
})

This selector will target all of your tooltips with the rel attribute "within" your #example div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.

Build a simple HTTP server in C

Mongoose (Formerly Simple HTTP Daemon) is pretty good. In particular, it's embeddable and compiles under Windows, Windows CE, and UNIX.

Error handling in AngularJS http get then construct

You need to add an additional parameter:

$http.get(url).then(
    function(response) {
        console.log('get',response)
    },
    function(data) {
        // Handle error here
    })

Spring Boot, Spring Data JPA with multiple DataSources

don't know why, but it works. Two configuration are the same, just change xxx to your name.

@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
    entityManagerFactoryRef = "xxxEntityManager",
    transactionManagerRef = "xxxTransactionManager",
    basePackages = {"aaa.xxx"})
 public class RepositoryConfig {
@Autowired
private Environment env;

@Bean
@Primary
@ConfigurationProperties(prefix="datasource.xxx")
public DataSource xxxDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
public LocalContainerEntityManagerFactoryBean xxxEntityManager() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(xxxDataSource());
    em.setPackagesToScan(new String[] {"aaa.xxx"});

    HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    HashMap<String, Object> properties = new HashMap<String, Object>();
    properties.put("hibernate.show_sql", env.getProperty("hibernate.show_sql"));
    properties.put("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto"));
    properties.put("hibernate.dialect", env.getProperty("hibernate.dialect"));
    em.setJpaPropertyMap(properties);

    return em;
}

@Bean(name = "xxxTransactionManager")
public PlatformTransactionManager xxxTransactionManager() {
    JpaTransactionManager tm = new JpaTransactionManager();
    tm.setEntityManagerFactory(xxxEntityManager().getObject());
    return tm;
}

}

Field 'browser' doesn't contain a valid alias configuration

I'm building a React server-side renderer and found this can also occur when building a separate server config from scratch. If you're seeing this error, try the following:

  1. Make sure your "entry" value is properly pathed relative to your "context" value. Mine was missing the preceeding "./" before the entry file name.
  2. Make sure you have your "resolve" value included. Your imports on anything in node_modules will default to looking in your "context" folder, otherwise.

Example:

const serverConfig = {
name: 'server',
context: path.join(__dirname, 'src'),
entry: {serverEntry: ['./server-entry.js']},
output: {
    path: path.join(__dirname, 'public'),
    filename: 'server.js',
    publicPath: 'public/',
    libraryTarget: 'commonjs2'
},
module: {
    rules: [/*...*/]
},
resolveLoader: {
    modules: [
        path.join(__dirname, 'node_modules')
    ]
},
resolve: {
    modules: [
        path.join(__dirname, 'node_modules')
    ]
}
};

Eclipse "Server Locations" section disabled and need to change to use Tomcat installation

You can change this by using the VM arguments as well in the launch configuration.

Make a simple fade in animation in Swift?

The problem is that you're trying start the animation too early in the view controller's lifecycle. In viewDidLoad, the view has just been created, and hasn't yet been added to the view hierarchy, so attempting to animate one of its subviews at this point produces bad results.

What you really should be doing is continuing to set the alpha of the view in viewDidLoad (or where you create your views), and then waiting for the viewDidAppear: method to be called. At this point, you can start your animations without any issue.

override func viewDidAppear(_ animated: Bool) {
    super.viewDidAppear(animated)

    UIView.animate(withDuration: 1.5) {
        self.myFirstLabel.alpha = 1.0
        self.myFirstButton.alpha = 1.0
        self.mySecondButton.alpha = 1.0
    }
}

How to convert dataframe into time series?

R has multiple ways of represeting time series. Since you're working with daily prices of stocks, you may wish to consider that financial markets are closed on weekends and business holidays so that trading days and calendar days are not the same. However, you may need to work with your times series in terms of both trading days and calendar days. For example, daily returns are calculated from sequential daily closing prices regardless of whether a weekend intervenes. But you may also want to do calendar-based reporting such as weekly price summaries. For these reasons the xts package, an extension of zoo, is commonly used with financial data in R. An example of how it could be used with your data follows.

Assuming the data shown in your example is in the dataframe df

  library(xts)
  stocks <- xts(df[,-1], order.by=as.Date(df[,1], "%m/%d/%Y"))
#
#  daily returns
#
   returns <- diff(stocks, arithmetic=FALSE ) - 1
#
#  weekly open, high, low, close reports
#
   to.weekly(stocks$Hero_close, name="Hero")

which gives the output

           Hero.Open Hero.High Hero.Low Hero.Close
2013-03-15    1669.1   1684.45   1669.1    1684.45
2013-03-22    1690.5   1690.50   1623.3    1659.60
2013-03-28    1617.7   1617.70   1542.0    1542.00

How can I compare a date and a datetime in Python?

Here is another take, "stolen" from a comment at can't compare datetime.datetime to datetime.date ... convert the date to a datetime using this construct:

datetime.datetime(d.year, d.month, d.day)

Suggestion:

from datetime import datetime

def ensure_datetime(d):
    """
    Takes a date or a datetime as input, outputs a datetime
    """
    if isinstance(d, datetime):
        return d
    return datetime.datetime(d.year, d.month, d.day)

def datetime_cmp(d1, d2):
    """
    Compares two timestamps.  Tolerates dates.
    """
    return cmp(ensure_datetime(d1), ensure_datetime(d2))

Limit String Length

2nd argument is where to start string and 3rd argument how many characters you need to show

$title = "This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string This is for testing string for get limit of string";
    echo substr($title,0,50);

VBScript How can I Format Date?

'for unique file names I use

Dim ts, logfile, thisScript

thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension

ts = timeStamp
logfile = thisScript & "_" & ts

' ======
Function timeStamp() 
    timeStamp = Year(Now) & "-" & _
    Right("0" & Month(Now),2)  & "-" & _
    Right("0" & Day(Now),2)  & "_" & _  
    Right("0" & Hour(Now),2) & _
    Right("0" & Minute(Now),2) '    '& _    Right("0" & Second(Now),2) 
End Function
' ======

change <audio> src with javascript

If you are storing metadata in a tag use data attributes eg.

<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>

Now use the attribute to get the name of the song

var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();

How do I install Python packages in Google's Colab?

You can use !setup.py install to do that.

Colab is just like a Jupyter notebook. Therefore, we can use the ! operator here to install any package in Colab. What ! actually does is, it tells the notebook cell that this line is not a Python code, its a command line script. So, to run any command line script in Colab, just add a ! preceding the line.

For example: !pip install tensorflow. This will treat that line (here pip install tensorflow) as a command prompt line and not some Python code. However, if you do this without adding the ! preceding the line, it'll throw up an error saying "invalid syntax".

But keep in mind that you'll have to upload the setup.py file to your drive before doing this (preferably into the same folder where your notebook is).

Hope this answers your question :)

Comparing mongoose _id and strings

According to the above,i found three ways to solve the problem.

  1. AnotherMongoDocument._id.toString()
  2. JSON.stringify(AnotherMongoDocument._id)
  3. results.userId.equals(AnotherMongoDocument._id)

Way to *ngFor loop defined number of times instead of repeating over array?

Within your component, you can define an array of number (ES6) as described below:

export class SampleComponent {
  constructor() {
    this.numbers = Array(5).fill(0).map((x,i)=>i);
  }
}

See this link for the array creation: Tersest way to create an array of integers from 1..20 in JavaScript.

You can then iterate over this array with ngFor:

@View({
  template: `
    <ul>
      <li *ngFor="let number of numbers">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Or shortly:

@View({
  template: `
    <ul>
      <li *ngFor="let number of [0,1,2,3,4]">{{number}}</li>
    </ul>
  `
})
export class SampleComponent {
  (...)
}

Hope it helps you, Thierry

Edit: Fixed the fill statement and template syntax.

select certain columns of a data table

You can create a method that looks like this:

  public static DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2)
    {
        DataTable TempTable = RecordDT_;

        System.Data.DataView view = new System.Data.DataView(TempTable);
        System.Data.DataTable selected = view.ToTable("Selected", false, col1, col2);
        return selected;
    }

You can return as many columns as possible.. just add the columns as call parameters as shown below:

public DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2,string col3,...)

and also add the parameters to this line:

System.Data.DataTable selected = view.ToTable("Selected", false,col1, col2,col3,...);

Then simply implement the function as:

 DataTable myselectedColumnTable=SelectedColumns(OriginalTable,"Col1","Col2",...);

Thanks...

ArrayAdapter in android to create simple listview

The TextView resource id it needs is for a TextView layout file, so it won't be in the same activity.

You can create it by going to File > New > XML > XML Layout File, and enter the widget type, which is 'TextView' in the root tag field.

Source: https://www.kompulsa.com/the-simplest-way-to-implement-an-android-listview/

How to show google.com in an iframe?

Its not ideal but you can use a proxy server and it works fine. For example go to hidemyass.com put in www.google.com and put the link it goes to in an iframe and it works!

CSS3 Transparency + Gradient

This is some really cool stuff! I needed pretty much the same, but with horizontal gradient from white to transparent. And it is working just fine! Here ist my code:

.gradient{
        /* webkit example */
        background-image: -webkit-gradient(
          linear, right top, left top, from(rgba(255, 255, 255, 1.0)),
          to(rgba(255, 255, 255, 0))
        );

        /* mozilla example - FF3.6+ */
        background-image: -moz-linear-gradient(
          right center,
          rgba(255, 255, 255, 1.0) 20%, rgba(255, 255, 255, 0) 95%
        );

        /* IE 5.5 - 7 */
        filter: progid:DXImageTransform.Microsoft.gradient(
          gradientType=1, startColor=0, endColorStr=#FFFFFF
        );

        /* IE8 uses -ms-filter for whatever reason... */
        -ms-filter: progid:DXImageTransform.Microsoft.gradient(
          gradientType=1, startColor=0, endColoStr=#FFFFFF
        );
    }

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

How to master AngularJS?

For a comprehensive and continually growing collection of links check AngularJS-Learning, a github repo that collects resources, links and interesting blog posts.

I've found very helpful the tutorials and videos on the AngularJS youtube channel. They go from the mostly basic stuff to some advanced topics, a good way to start.

The official twitter and google+ accounts are a good way to follow news and get some nice links. Also check the AngularJS Mailing list.

A nice aggregator of news/link is angularjsdaily.com.

Also there're some new books out there, so you can keep an eye on your favourite online library.

Using Panel or PlaceHolder

I weird bug* in visual studio 2010, if you put controls inside a Placeholder it does not render them in design view mode.

This is especially true for Hidenfields and Empty labels.

I would love to use placeholders instead of panels but I hate the fact I cant put other controls inside placeholders at design time in the GUI.

Difference between Inheritance and Composition

In Simple Word Aggregation means Has A Relationship ..

Composition is a special case of aggregation. In a more specific manner, a restricted aggregation is called composition. When an object contains the other object, if the contained object cannot exist without the existence of container object, then it is called composition. Example: A class contains students. A student cannot exist without a class. There exists composition between class and students.

Why Use Aggregation

Code Reusability

When Use Aggregation

Code reuse is also best achieved by aggregation when there is no is a Relation ship

Inheritance

Inheritance is a Parent Child Relationship Inheritance Means Is A RelationShip

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

Using inheritance in Java 1 Code Reusability. 2 Add Extra Feature in Child Class as well as Method Overriding (so runtime polymorphism can be achieved).

Elegant Python function to convert CamelCase to snake_case?

Not in the standard library, but I found this module that appears to contain the functionality you need.

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

Select all occurrences of selected word in VSCode

I needed to extract all the matched search lines (using regex) in a file

  1. Ctrl+F Open find. Select regex icon and enter search pattern
  2. (optional) Enable select highlights by opening settings and search for selectHighlights (Ctrl+,, selectHighlights)
  3. Ctrl+L Select all search items
  4. Ctrl+C Copy all selected lines
  5. Ctrl+N Open new document
  6. Ctrl+V Paste all searched lines.

Are HTTP cookies port specific?

The current cookie specification is RFC 6265, which replaces RFC 2109 and RFC 2965 (both RFCs are now marked as "Historic") and formalizes the syntax for real-world usages of cookies. It clearly states:

  1. Introduction

...

For historical reasons, cookies contain a number of security and privacy infelicities. For example, a server can indicate that a given cookie is intended for "secure" connections, but the Secure attribute does not provide integrity in the presence of an active network attacker. Similarly, cookies for a given host are shared across all the ports on that host, even though the usual "same-origin policy" used by web browsers isolates content retrieved via different ports.

And also:

8.5. Weak Confidentiality

Cookies do not provide isolation by port. If a cookie is readable by a service running on one port, the cookie is also readable by a service running on another port of the same server. If a cookie is writable by a service on one port, the cookie is also writable by a service running on another port of the same server. For this reason, servers SHOULD NOT both run mutually distrusting services on different ports of the same host and use cookies to store security sensitive information.

Difference between Big-O and Little-O Notation

The big-O notation has a companion called small-o notation. The big-O notation says the one function is asymptotical no more than another. To say that one function is asymptotically less than another, we use small-o notation. The difference between the big-O and small-o notations is analogous to the difference between <= (less than equal) and < (less than).

How to upgrade pip3?

What worked for me was the following command:

python -m pip install --upgrade pip

hadoop copy a local file system folder to HDFS

In Short

hdfs dfs -put <localsrc> <dest>

In detail with example:

Checking source and target before placing files into HDFS

[cloudera@quickstart ~]$ ll files/
total 132
-rwxrwxr-x 1 cloudera cloudera  5387 Nov 14 06:33 cloudera-manager
-rwxrwxr-x 1 cloudera cloudera  9964 Nov 14 06:33 cm_api.py
-rw-rw-r-- 1 cloudera cloudera   664 Nov 14 06:33 derby.log
-rw-rw-r-- 1 cloudera cloudera 53655 Nov 14 06:33 enterprise-deployment.json
-rw-rw-r-- 1 cloudera cloudera 50515 Nov 14 06:33 express-deployment.json

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 1 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging

Copy files HDFS using -put or -copyFromLocal command

[cloudera@quickstart ~]$ hdfs dfs -put files/ files

Verify the result in HDFS

[cloudera@quickstart ~]$ hdfs dfs -ls
Found 2 items
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 00:45 .sparkStaging
drwxr-xr-x   - cloudera cloudera          0 2017-11-14 06:34 files

[cloudera@quickstart ~]$ hdfs dfs -ls files
Found 5 items
-rw-r--r--   1 cloudera cloudera       5387 2017-11-14 06:34 files/cloudera-manager
-rw-r--r--   1 cloudera cloudera       9964 2017-11-14 06:34 files/cm_api.py
-rw-r--r--   1 cloudera cloudera        664 2017-11-14 06:34 files/derby.log
-rw-r--r--   1 cloudera cloudera      53655 2017-11-14 06:34 files/enterprise-deployment.json
-rw-r--r--   1 cloudera cloudera      50515 2017-11-14 06:34 files/express-deployment.json

How to add \newpage in Rmarkdown in a smart way?

In the initialization chunk I define a function

pagebreak <- function() {
  if(knitr::is_latex_output())
    return("\\newpage")
  else
    return('<div style="page-break-before: always;" />')
}

In the markdown part where I want to insert a page break, I type

`r pagebreak()`

Getting all names in an enum as a String[]

If you can use Java 8, this works nicely (alternative to Yura's suggestion, more efficient):

public static String[] names() {
    return Stream.of(State.values()).map(State::name).toArray(String[]::new);
}

Javascript set img src

Also, one way to solve this is to use document.createElement and create your html img and set its attributes like this.

var image = document.createElement("img");
var imageParent = document.getElementById("Id of HTML element to append the img");
image.id = "Id";
image.className = "class";
image.src = searchPic.src;
imageParent.appendChild(image);

REMARK: One point is that Javascript community right now encourages developers to use document selectors such as querySelector, getElementById and getElementsByClassName rather than document["pic1"].

Android: ProgressDialog.show() crashes with getApplicationContext

For using dialogs inside activities, do it this way:

private Context mContext;
private AlertDialog.Builder mBuilder;

@Override
protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     mContext = this;

     //using mContext here refering to activity context
     mBuilder = new AlertDialog.Builder(mContext);
     //...
     //rest of the code
     //...
}

For using dialogs inside fragments, do it this way:

private Context mContext;
private AlertDialog.Builder mBuilder;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      View mRootView = inflater.inflate(R.layout.fragment_layout, container, false);
      mContext = getActivity();

      //using mContext here refering to fragment's hosting activity context
      mBuilder = new AlertDialog.Builder(mContext);
      //...
      //rest of the code
      //...
      return mRootView;
}

That's it ^_^

Why am I getting error CS0246: The type or namespace name could not be found?

This is the problem:

C:\Users\Noob\csharp>csc test.cs

You haven't added a reference to the DLL. You need something like:

C:\Users\Noob\csharp>csc test.cs /r:SnarlNetwork.dll

(or whatever the assembly is called).

Alternatively, if you haven't got it as a separate library, just compile both files:

C:\Users\Noob\csharp>csc test.cs SnarlNetwork.cs

If you haven't compiled an assembly but want to, you can use:

csc /target:library /out:SnarlNetwork.dll SnarlNetwork.cs

csc Test.cs /r:SnarlNetwork.dll

(In fact, specifying the output file is unnecessary in this particular case, but it's still clearer...)