Programs & Examples On #Samba

Samba is the standard Windows interoperability suite of programs for Linux and Unix.

Cannot bulk load because the file could not be opened. Operating System Error Code 3

I dont know if you solved this issue, but i had same issue, if the instance is local you must check the permission to access the file, but if you are accessing from your computer to a server (remote access) you have to specify the path in the server, so that means to include the file in a server directory, that solved my case

example:

BULK INSERT Table
FROM 'C:\bulk\usuarios_prueba.csv' -- This is server path not local
WITH 
  (
     FIELDTERMINATOR =',',
     ROWTERMINATOR ='\n'
  );

How do you force a CIFS connection to unmount

I had a very similar problem with davfs. In the man page of umount.davfs, I found that the -f -l -n -r -v options are ignored by umount.davfs. To force-unmount my davfs mount, I had to use umount -i -f -l /media/davmount.

html select option separator

I elected to conditionally alternate color and background. Setting a sort order and with vue.js, I did something like this:

<style>
    .altgroup_1 {background:gray; color:white;}
    .altgroup_2{background:white; color:black;}
</style>

<option :class = {
    'altgroup_1': (country.sort_order > 25),
    'altgroup_2': (country.sort_order > 50 }"
    value="{{ country.iso_short }}">
    {{ country.short_name }}
</option

How do I find which transaction is causing a "Waiting for table metadata lock" state?

I had a similar issue with Datagrip and none of these solutions worked.

Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.

Python write line by line to a text file

Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n and you use \n.

Check if a string contains a string in C++

Starting from C++23 you can use std::string::contains

#include <string>

const auto haystack = std::string("haystack with needles");
const auto needle = std::string("needle");

if (haystack.contains(needle))
{
    // found!
}

How to Generate unique file names in C#

How about using Guid.NewGuid() to create a GUID and use that as the filename (or part of the filename together with your time stamp if you like).

Append Char To String in C?

C does not have strings per se -- what you have is a char pointer pointing to some read-only memory containing the characters "blablabla\0". In order to append a character there, you need a) writable memory and b) enough space for the string in its new form. The string literal "blablabla\0" has neither.

The solutions are:

1) Use malloc() et al. to dynamically allocate memory. (Don't forget to free() afterwards.)
2) Use a char array.

When working with strings, consider using strn* variants of the str* functions -- they will help you stay within memory bounds.

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
</style>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>
</style>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>
</style>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.

Link: http://developer.android.com/design/style/typography.html

"Eliminate render-blocking CSS in above-the-fold content"

Hi For jQuery You can only use like this

Use async and type="text/javascript" only

Retrofit 2: Get JSON from Response body

If you don't have idea about What could be the response from the API. Follow the steps to convert the responsebody response value into bytes and print in the String format You can get the entire response printed in the console.

Then you can convert string to JSONObject easily.

      apiService.getFeeds(headerMap, map).enqueue(object : Callback, retrofit2.Callback<ResponseBody> {
            override fun onFailure(call: Call<ResponseBody>?, t: Throwable?) {
            }

            override fun onResponse(call: Call<ResponseBody>?, response: Response<ResponseBody>?) {
                val bytes = (response!!.body()!!.bytes())
                Log.d("Retrofit Success : ", ""+ String(bytes))
            }
        })

How to empty a redis database?

Be careful here.

FlushDB deletes all keys in the current database while FlushALL deletes all keys in all databases on the current host.

MySQL - force not to use cache for testing speed of query

Try using the SQL_NO_CACHE (MySQL 5.7) option in your query. (MySQL 5.6 users click HERE )

eg.

SELECT SQL_NO_CACHE * FROM TABLE

This will stop MySQL caching the results, however be aware that other OS and disk caches may also impact performance. These are harder to get around.

Session variables not working php

The other important reason sessions can not work is playing with the session cookie settings, eg. setting session cookie lifetime to 0 or other low values because of simple mistake or by other developer for a reason.

session_set_cookie_params(0)

System.Net.WebException: The operation has timed out

proxy issue can cause this. IIS webconfig put this in

<defaultProxy useDefaultCredentials="true" enabled="true">
          <proxy usesystemdefault="True" />
        </defaultProxy>

php resize image on upload

If you want to use Imagick out of the box (included with most PHP distributions), it's as easy as...

$image = new Imagick();
$image_filehandle = fopen('some/file.jpg', 'a+');
$image->readImageFile($image_filehandle);

$image->scaleImage(100,200,FALSE);

$image_icon_filehandle = fopen('some/file-icon.jpg', 'a+');
$image->writeImageFile($image_icon_filehandle);

You will probably want to calculate width and height more dynamically based on the original image. You can get an image's current width and height, using the above example, with $image->getImageHeight(); and $image->getImageWidth();

Passing a method as a parameter in Ruby

You have to call the method "call" of the function object:

weight = weightf.call( dist )

EDIT: as explained in the comments, this approach is wrong. It would work if you're using Procs instead of normal functions.

How do I run a program with commandline arguments using GDB within a Bash script?

Much too late, but here is a method that works during gdb session.

gdb <executable>

then

(gdb) apropos argument

This will return lots of matches, the useful one is set args.

set args -- Set argument list to give program being debugged when it is started.

set args arg1 arg2 ...

then

r

This will run the program, passing to main(argc, argv) the arguments and the argument count.

Label axes on Seaborn Barplot

You can also set the title of your chart by adding the title parameter as follows

ax.set(xlabel='common xlabel', ylabel='common ylabel', title='some title')

Turn Pandas Multi-Index into column

As @cs95 mentioned in a comment, to drop only one level, use:

df.reset_index(level=[...])

This avoids having to redefine your desired index after reset.

Cookies vs. sessions

I will select Session, first of all session is more secure then cookies, cookies is client site data and session is server site data. Cookies is used to identify a user, because it is small pieces of code that is embedded my server with user computer browser. On the other hand Session help you to secure you identity because web server don’t know who you are because HTTP address changes the state 192.168.0.1 to 765487cf34ert8ded…..or something else numbers with the help of GET and POST methods. Session stores data of user in unique ID session that even user ID can’t match with each other. Session stores single user information in all pages of one application. Cookies expire is set with the help of setcookies() whereas session expire is not set it is expire when user turn off browsers.

C# Dictionary get item by index

You can take keys or values per index:

int value = _dict.Values.ElementAt(5);//ElementAt value should be <= _dict.Count - 1
string key = _dict.Keys.ElementAt(5);//ElementAt value should be  < =_dict.Count - 1

How to clear Flutter's Build cache?

Or you can delete the /build folder under your /app-project folder manually if you cannot run flutter command.

Adding background image to div using CSS

To use an image for body background in CSS

body {
  background-image: url("image.jpg");
}

How to check if a network port is open on linux?

If you only care about the local machine, you can rely on the psutil package. You can either:

  1. Check all ports used by a specific pid:

    proc = psutil.Process(pid)
    print proc.connections()
    
  2. Check all ports used on the local machine:

    print psutil.net_connections()
    

It works on Windows too.

https://github.com/giampaolo/psutil

How to convert a GUID to a string in C#?

Here are examples of output from each of the format specifiers:

N: cd26ccf675d64521884f1693c62ed303
D: cd26ccf6-75d6-4521-884f-1693c62ed303
B: {cd26ccf6-75d6-4521-884f-1693c62ed303}
P: (cd26ccf6-75d6-4521-884f-1693c62ed303)
X: {0xcd26ccf6,0x75d6,0x4521,{0x88,0x4f,0x16,0x93,0xc6,0x2e,0xd3,0x03}}

The default is D.

Run this yourself.

How do I copy to the clipboard in JavaScript?

ZeroClipboard is the best cross-browser solution I've found:

<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>
<script src="ZeroClipboard.js"></script>
<script>
  var clip = new ZeroClipboard( document.getElementById('copy') );
</script>

If you need non-Flash support for iOS you just add a fall-back:

clip.on( 'noflash', function ( client, args ) {
    $("#copy").click(function(){
        var txt = $(this).attr('data-clipboard-text');
        prompt ("Copy link, then click OK.", txt);
    });
});

http://zeroclipboard.org/

https://github.com/zeroclipboard/ZeroClipboard

How to get complete month name from DateTime

It should be just DateTime.ToString( "MMMM" )

You don't need all the extra Ms.

Change one value based on another value in pandas

You can use map, it can map vales from a dictonairy or even a custom function.

Suppose this is your df:

    ID First_Name Last_Name
0  103          a         b
1  104          c         d

Create the dicts:

fnames = {103: "Matt", 104: "Mr"}
lnames = {103: "Jones", 104: "X"}

And map:

df['First_Name'] = df['ID'].map(fnames)
df['Last_Name'] = df['ID'].map(lnames)

The result will be:

    ID First_Name Last_Name
0  103       Matt     Jones
1  104         Mr         X

Or use a custom function:

names = {103: ("Matt", "Jones"), 104: ("Mr", "X")}
df['First_Name'] = df['ID'].map(lambda x: names[x][0])

How to make a script wait for a pressed key?

The python manual provides the following:

import termios, fcntl, sys, os
fd = sys.stdin.fileno()

oldterm = termios.tcgetattr(fd)
newattr = termios.tcgetattr(fd)
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO
termios.tcsetattr(fd, termios.TCSANOW, newattr)

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL)
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK)

try:
    while 1:
        try:
            c = sys.stdin.read(1)
            print "Got character", repr(c)
        except IOError: pass
finally:
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm)
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags)

which can be rolled into your use case.

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

How to pretty print nested dictionaries?

By this way you can print it in pretty way for example your dictionary name is yasin

import json

print (json.dumps(yasin, indent=2))

or, safer:

print (json.dumps(yasin, indent=2, default=str))

Use HTML5 to resize an image before upload

If some of you, like me, encounter orientation problems I have combined the solutions here with a exif orientation fix

https://gist.github.com/SagiMedina/f00a57de4e211456225d3114fd10b0d0

How to iterate through a list of dictionaries in Jinja template?

Just a side note for similar problem (If we don't want to loop through):

How to lookup a dictionary using a variable key within Jinja template?

Here is an example:

{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}

It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)

Alternatively, you can simply do

{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}

But it will spit an error when no key is found. So better to use get in Jinja.

How do I calculate square root in Python?

sqrt=x**(1/2) is doing integer division. 1/2 == 0.

So you're computing x(1/2) in the first instance, x(0) in the second.

So it's not wrong, it's the right answer to a different question.

Character reading from file in Python

Actually, U+2018 is the Unicode representation of the special character ‘ . If you want, you can convert instances of that character to U+0027 with this code:

text = text.replace (u"\u2018", "'")

In addition, what are you using to write the file? f1.read() should return a string that looks like this:

'I don\xe2\x80\x98t like this'

If it's returning this string, the file is being written incorrectly:

'I don\u2018t like this'

What's the difference between echo, print, and print_r in PHP?

**Echocan accept multiple expressions while print cannot. The Print_r () PHP function is used to return an array in a human readable form. It is simply written as

![Print_r ($your_array)][1]

Android: how to make an activity return results to the activity which calls it?

If you want to finish and just add a resultCode (without data), you can call setResult(int resultCode) before finish().

For example:

...
if (everything_OK) {
    setResult(Activity.RESULT_OK); // OK! (use whatever code you want)
    finish();
}
else {
   setResult(Activity.RESULT_CANCELED); // some error ...
   finish();
}
...

Then in your calling activity, check the resultCode, to see if we're OK.

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == someCustomRequestCode) {
        if (resultCode == Activity.RESULT_OK) {
            // OK!
        }
        else if (resultCode = Activity.RESULT_CANCELED) {
            // something went wrong :-(
        }
    }
}

Don't forget to call the activity with startActivityForResult(intent, someCustomRequestCode).

Delete last char of string

As an alternate to adding a comma for each item you could just using String.Join:

var strgroupids = String.Join(",",  groupIds);

This will add the seperator ("," in this instance) between each element in the array.

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

I was unsatisfied that until know Google hasn't yet released their new designs as font or svg icon set. Therefore I put together a small npm package to solve the problem.

https://www.npmjs.com/package/ts-material-icons-svg

Simply import the icons you wanna use and add them to your registry. This also supports tree shaking since only those icons are added to your project that you really want and/or need.

npm i --save https://github.com/MarcusCalidus/ts-material-icons-svg.git

to use two tone icons for example

import {icon_edit} from 'ts-material-icons-svg/dist/twotone';

matIconRegistry.addSvgIcon(
            'edit',
            domSanitizer.bypassSecurityTrustResourceUrl(icon_edit),
        );

In your html template you now can use the new icon

<mat-icon svgIcon="edit"></mat-icon>

Pandas DataFrame to List of Lists

If the data has column and index labels that you want to preserve, there are a few options.

Example data:

>>> df = pd.DataFrame([[1,2,3],[3,4,5]], \
       columns=('first', 'second', 'third'), \
       index=('alpha', 'beta')) 
>>> df
       first  second  third
alpha      1       2      3
beta       3       4      5

The tolist() method described in other answers is useful but yields only the core data - which may not be enough, depending on your needs.

>>> df.values.tolist()
[[1, 2, 3], [3, 4, 5]]

One approach is to convert the DataFrame to json using df.to_json() and then parse it again. This is cumbersome but does have some advantages, because the to_json() method has some useful options.

>>> df.to_json()
{
  "first":{"alpha":1,"beta":3},
  "second":{"alpha":2,"beta":4},"third":{"alpha":3,"beta":5}
}

>>> df.to_json(orient='split')
{
 "columns":["first","second","third"],
 "index":["alpha","beta"],
 "data":[[1,2,3],[3,4,5]]
}

Cumbersome but may be useful.

The good news is that it's pretty straightforward to build lists for the columns and rows:

>>> columns = [df.index.name] + [i for i in df.columns]
>>> rows = [[i for i in row] for row in df.itertuples()]

This yields:

>>> print(f"columns: {columns}\nrows: {rows}") 
columns: [None, 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]

If the None as the name of the index is bothersome, rename it:

df = df.rename_axis('stage')

Then:

>>> columns = [df.index.name] + [i for i in df.columns]
>>> print(f"columns: {columns}\nrows: {rows}") 

columns: ['stage', 'first', 'second', 'third']
rows: [['alpha', 1, 2, 3], ['beta', 3, 4, 5]]

How does cookie based authentication work?

I realize this is years late, but I thought I could expand on Conor's answer and add a little bit more to the discussion.

Can someone give me a step by step description of how cookie based authentication works? I've never done anything involving either authentication or cookies. What does the browser need to do? What does the server need to do? In what order? How do we keep things secure?

Step 1: Client > Signing up

Before anything else, the user has to sign up. The client posts a HTTP request to the server containing his/her username and password.

Step 2: Server > Handling sign up

The server receives this request and hashes the password before storing the username and password in your database. This way, if someone gains access to your database they won't see your users' actual passwords.

Step 3: Client > User login

Now your user logs in. He/she provides their username/password and again, this is posted as a HTTP request to the server.

Step 4: Server > Validating login

The server looks up the username in the database, hashes the supplied login password, and compares it to the previously hashed password in the database. If it doesn't check out, we may deny them access by sending a 401 status code and ending the request.

Step 5: Server > Generating access token

If everything checks out, we're going to create an access token, which uniquely identifies the user's session. Still in the server, we do two things with the access token:

  1. Store it in the database associated with that user
  2. Attach it to a response cookie to be returned to the client. Be sure to set an expiration date/time to limit the user's session

Henceforth, the cookies will be attached to every request (and response) made between the client and server.

Step 6: Client > Making page requests

Back on the client side, we are now logged in. Every time the client makes a request for a page that requires authorization (i.e. they need to be logged in), the server obtains the access token from the cookie and checks it against the one in the database associated with that user. If it checks out, access is granted.

This should get you started. Be sure to clear the cookies upon logout!

Raise an event whenever a property's value changed?

If you change your property to use a backing field (instead of an automatic property), you can do the following:

public event EventHandler ImageFullPath1Changed;
private string _imageFullPath1 = string.Empty;

public string ImageFullPath1 
{
  get
  {
    return imageFullPath1 ;
  }
  set
  {
    if (_imageFullPath1 != value)
    { 
      _imageFullPath1 = value;

      EventHandler handler = ImageFullPathChanged;
      if (handler != null)
        handler(this, e);
    }
  }
}

What type of hash does WordPress use?

The best way to do this is using WordPress class to authenticate users. Here is my solutions:

1. Include following WordPress PHP file:

include_once(dirname(dirname(dirname(__FILE__))) . DIRECTORY_SEPARATOR . "wp-includes" . DIRECTORY_SEPARATOR . "class-phpass.php");

2. Create an object of PasswordHash class:

$wp_hasher = new PasswordHash(8, true);

3. call CheckPassword function to authenticate user:

$check = $wp_hasher->CheckPassword($password, $row['user_pass']);

4. check $check variable:

if($check) {
   echo "password is correct";
} else {
   echo "password is incorrect";
}

Please Note that: $password is the un-hashed password in clear text whereas $row['user_pass'] is the hashed password that you need to fetch from the database.

Best way to format multiple 'or' conditions in an if statement (Java)

You could look for the presence of a map key or see if it's in a set.

Depending on what you're actually doing, though, you might be trying to solve the problem wrong :)

json_encode is returning NULL?

The PHP.net recommended way of setting the charset is now this:

mysqli_set_charset('utf8')

A potentially dangerous Request.Path value was detected from the client (*)

This exception occurred in my application and was rather misleading.

It was thrown when I was calling an .aspx page Web Method using an ajax method call, passing a JSON array object. The Web Page method signature contained an array of a strongly-typed .NET object, OrderDetails. The Actual_Qty property was defined as an int, and the JSON object Actual_Qty property contained "4 " (extra space character). After removing the extra space, the conversion was made possible, the Web Page method was successfully reached by the ajax call.

How can I require at least one checkbox be checked before a form can be submitted?

The issue with the accepted solution above is that is does not allow for the else condition on form submit (if a box has been selected), thereby preventing form submission - at least when I tried it.

I discovered another solution that effects the desired result more completely IMHO, here:

Making sure at least one checkbox is checked

Code as follows:

function valthis() {
var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'At least one checkbox checked!' );
        } else {
            alert( 'Please, check at least one checkbox!' );
        }   
}

Fiddle

That code & answer by Vell

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

1) In some cases, yes. If the WSDL contains things like Policies and such that direct the runtime behavior, then the WSDL may be required at runtime. Artifacts are not generated for policy related things and such. Also, in some obscure RPC/Literal cases, not all the namespaces that are needed are output in the generated code (per spec). Thus, the wsdl would be needed for them. Obscure cases though.

2) I thought something like would work. What version of CXF? That sounds like a bug. You can try an empty string in there (just spaces). Not sure if that works or not. That said, in your code, you can use the constructor that takes the WSDL URL and just pass null. The wsdl wouldn't be used.

3) Just the limitations above.

Are list-comprehensions and functional functions faster than "for loops"?

I wrote a simple script that test the speed and this is what I found out. Actually for loop was fastest in my case. That really suprised me, check out bellow (was calculating sum of squares).

from functools import reduce
import datetime


def time_it(func, numbers, *args):
    start_t = datetime.datetime.now()
    for i in range(numbers):
        func(args[0])
    print (datetime.datetime.now()-start_t)

def square_sum1(numbers):
    return reduce(lambda sum, next: sum+next**2, numbers, 0)


def square_sum2(numbers):
    a = 0
    for i in numbers:
        i = i**2
        a += i
    return a

def square_sum3(numbers):
    sqrt = lambda x: x**2
    return sum(map(sqrt, numbers))

def square_sum4(numbers):
    return(sum([int(i)**2 for i in numbers]))


time_it(square_sum1, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum2, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum3, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
time_it(square_sum4, 100000, [1, 2, 5, 3, 1, 2, 5, 3])
0:00:00.302000 #Reduce
0:00:00.144000 #For loop
0:00:00.318000 #Map
0:00:00.390000 #List comprehension

Why does a base64 encoded string have an = sign at the end

From Wikipedia:

The final '==' sequence indicates that the last group contained only one byte, and '=' indicates that it contained two bytes.

Thus, this is some sort of padding.

AttributeError: 'module' object has no attribute 'urlopen'

To get 'dataX = urllib.urlopen(url).read()' working in python3 (this would have been correct for python2) you must just change 2 little things.

1: The urllib statement itself (add the .request in the middle):

dataX = urllib.request.urlopen(url).read()

2: The import statement preceding it (change from 'import urlib' to:

import urllib.request

And it should work in python3 :)

How to customise file type to syntax associations in Sublime Text?

for ST3

$language = "language u wish"

if exists,

go to ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

else

create ~/.config/sublime-text-3/Packages/User/$language.sublime-settings

and set

{ "extensions": [ "yourextension" ] }

This way allows you to enable syntax for composite extensions (e.g. sql.mustache, js.php, etc ... )

JQuery ajax call default timeout value

There doesn't seem to be a standardized default value. I have the feeling the default is 0, and the timeout event left totally dependent on browser and network settings.

For IE, there is a timeout property for XMLHTTPRequests here. It defaults to null, and it says the network stack is likely to be the first to time out (which will not generate an ontimeout event by the way).

How to include a font .ttf using CSS?

I know this is an old post but this solved my problem.

_x000D_
_x000D_
@font-face{_x000D_
  font-family: "Font Name";_x000D_
  src: url("../fonts/font-name.ttf") format("truetype");_x000D_
}
_x000D_
_x000D_
_x000D_

notice src:url("../fonts/font-name.ttf"); we use two periods to go back to the root directory and then into the fonts folder or wherever your file is located.

hope this helps someone down the line:) happy coding

How can I convert string to datetime with format specification in JavaScript?

@Christoph Mentions using a regex to tackle the problem. Here's what I'm using:

var dateString = "2010-08-09 01:02:03";
var reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/;
var dateArray = reggie.exec(dateString); 
var dateObject = new Date(
    (+dateArray[1]),
    (+dateArray[2])-1, // Careful, month starts at 0!
    (+dateArray[3]),
    (+dateArray[4]),
    (+dateArray[5]),
    (+dateArray[6])
);

It's by no means intelligent, just configure the regex and new Date(blah) to suit your needs.

Edit: Maybe a bit more understandable in ES6 using destructuring:

let dateString = "2010-08-09 01:02:03"
  , reggie = /(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/
  , [, year, month, day, hours, minutes, seconds] = reggie.exec(dateString)
  , dateObject = new Date(year, month-1, day, hours, minutes, seconds);

But in all honesty these days I reach for something like Moment

Can I change the color of Font Awesome's icon color?

HTML:

    <i class="icon-cog blackiconcolor">

css :

    .blackiconcolor {color:black;}

you can also add extra class to the button icon...

Why can't I shrink a transaction log file, even after backup?

Try creating another full backup after you backup the log w/ truncate_only (IIRC you should do this anyway to maintain the log chain). In simple recovery mode, your log shouldn't grow much anyway since it's effectively truncated after every transaction. Then try specifying the size you want the logfile to be, e.g.

-- shrink log file to c. 1 GB
DBCC SHRINKFILE (Wxlog0, 1000);

The TRUNCATEONLY option doesn't rearrange the pages inside the log file, so you might have an active page at the "end" of your file, which could prevent it from being shrunk.

You can also use DBCC SQLPERF(LOGSPACE) to make sure that there really is space in the log file to be freed.

List all column except for one in R

In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

How do I plot in real-time in a while loop using matplotlib?

The top (and many other) answers were built upon plt.pause(), but that was an old way of animating the plot in matplotlib. It is not only slow, but also causes focus to be grabbed upon each update (I had a hard time stopping the plotting python process).

TL;DR: you may want to use matplotlib.animation (as mentioned in documentation).

After digging around various answers and pieces of code, this in fact proved to be a smooth way of drawing incoming data infinitely for me.

Here is my code for a quick start. It plots current time with a random number in [0, 100) every 200ms infinitely, while also handling auto rescaling of the view:

from datetime import datetime
from matplotlib import pyplot
from matplotlib.animation import FuncAnimation
from random import randrange

x_data, y_data = [], []

figure = pyplot.figure()
line, = pyplot.plot_date(x_data, y_data, '-')

def update(frame):
    x_data.append(datetime.now())
    y_data.append(randrange(0, 100))
    line.set_data(x_data, y_data)
    figure.gca().relim()
    figure.gca().autoscale_view()
    return line,

animation = FuncAnimation(figure, update, interval=200)

pyplot.show()

You can also explore blit for even better performance as in FuncAnimation documentation.

An example from the blit documentation:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

fig, ax = plt.subplots()
xdata, ydata = [], []
ln, = plt.plot([], [], 'ro')

def init():
    ax.set_xlim(0, 2*np.pi)
    ax.set_ylim(-1, 1)
    return ln,

def update(frame):
    xdata.append(frame)
    ydata.append(np.sin(frame))
    ln.set_data(xdata, ydata)
    return ln,

ani = FuncAnimation(fig, update, frames=np.linspace(0, 2*np.pi, 128),
                    init_func=init, blit=True)
plt.show()

Clear text from textarea with selenium

I ran into a field where .clear() did not work. Using a combination of the first two answers worked for this field.

from selenium.webdriver.common.keys import Keys

#...your code (I was using python 3)

driver.find_element_by_id('foo').send_keys(Keys.CONTROL + "a");
driver.find_element_by_id('foo').send_keys(Keys.DELETE);

How many values can be represented with n bits?

There's an easier way to think about this. Start with 1 bit. This can obviously represent 2 values (0 or 1). What happens when we add a bit? We can now represent twice as many values: the values we could represent before with a 0 appended and the values we could represent before with a 1 appended.

So the the number of values we can represent with n bits is just 2^n (2 to the power n)

Download history stock prices automatically from yahoo finance in python

Extending @Def_Os's answer with an actual demo...

As @Def_Os has already said - using Pandas Datareader makes this task a real fun

In [12]: from pandas_datareader import data

pulling all available historical data for AAPL starting from 1980-01-01

#In [13]: aapl = data.DataReader('AAPL', 'yahoo', '1980-01-01')

# yahoo api is inconsistent for getting historical data, please use google instead.
In [13]: aapl = data.DataReader('AAPL', 'google', '1980-01-01')

first 5 rows

In [14]: aapl.head()
Out[14]:
                 Open       High     Low   Close     Volume  Adj Close
Date
1980-12-12  28.750000  28.875000  28.750  28.750  117258400   0.431358
1980-12-15  27.375001  27.375001  27.250  27.250   43971200   0.408852
1980-12-16  25.375000  25.375000  25.250  25.250   26432000   0.378845
1980-12-17  25.875000  25.999999  25.875  25.875   21610400   0.388222
1980-12-18  26.625000  26.750000  26.625  26.625   18362400   0.399475

last 5 rows

In [15]: aapl.tail()
Out[15]:
                 Open       High        Low      Close    Volume  Adj Close
Date
2016-06-07  99.250000  99.870003  98.959999  99.029999  22366400  99.029999
2016-06-08  99.019997  99.559998  98.680000  98.940002  20812700  98.940002
2016-06-09  98.500000  99.989998  98.459999  99.650002  26419600  99.650002
2016-06-10  98.529999  99.349998  98.480003  98.830002  31462100  98.830002
2016-06-13  98.690002  99.120003  97.099998  97.339996  37612900  97.339996

save all data as CSV file

In [16]: aapl.to_csv('d:/temp/aapl_data.csv')

d:/temp/aapl_data.csv - 5 first rows

Date,Open,High,Low,Close,Volume,Adj Close
1980-12-12,28.75,28.875,28.75,28.75,117258400,0.431358
1980-12-15,27.375001,27.375001,27.25,27.25,43971200,0.408852
1980-12-16,25.375,25.375,25.25,25.25,26432000,0.378845
1980-12-17,25.875,25.999999,25.875,25.875,21610400,0.38822199999999996
1980-12-18,26.625,26.75,26.625,26.625,18362400,0.399475
...

How to set default value for column of new created table from select statement in 11g

The reason is that CTAS (Create table as select) does not copy any metadata from the source to the target table, namely

  • no primary key
  • no foreign keys
  • no grants
  • no indexes
  • ...

To achieve what you want, I'd either

  • use dbms_metadata.get_ddl to get the complete table structure, replace the table name with the new name, execute this statement, and do an INSERT afterward to copy the data
  • or keep using CTAS, extract the not null constraints for the source table from user_constraints and add them to the target table afterwards

Difference between Relative path and absolute path in javascript

The path with reference to root directory is called absolute. The path with reference to current directory is called relative.

How do you find out the type of an object (in Swift)?

If a parameter is passed as Any to your function, you can test on a special type like so :

   func isADate ( aValue : Any?) -> Bool{
        if (aValue as? Date) != nil {
            print ("a Date")
            return true
        }
        else {
            print ("This is not a date ")
            return false
        }
    }

Javascript - validation, numbers only

This one worked for me :

function validateForm(){

  var z = document.forms["myForm"]["num"].value;

  if(!/^[0-9]+$/.test(z)){
    alert("Please only enter numeric characters only for your Age! (Allowed input:0-9)")
  }

}

Find files in created between a date range

List files between 2 dates

find . -type f -newermt "2019-01-01" ! -newermt "2019-05-01"

or

find path -type f -newermt "2019-01-01" ! -newermt "2019-05-01"

Java Can't connect to X11 window server using 'localhost:10.0' as the value of the DISPLAY variable

For me, the problem was that xorg-x11-xauth wasn't installed. I installed it and then it worked.

The packages that I have now are:

  • libX11-common-1.6.3-2.el6.noarch
  • libX11-1.6.3-2.el6.i686
  • libX11-1.6.3-2.el6.x86_64
  • xorg-x11-drv-ati-firware-7.6.1-2.el6.noarch
  • xorg-x11-xauth-1.0.9-1.el6.x86_64

Installing specific laravel version with composer create-project

Have a look:

Laravel 4.2 Documentation

Syntax (Via Composer):

composer create-project laravel/laravel {directory} 4.2 --prefer-dist

Example:

composer create-project laravel/laravel my_laravel_dir 4.2

Where 4.2 is your version of laravel.

Note: It will take the latest version of Laravel automatically If you will not provide any version.

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

How to get URI from an asset File?

Worked for me Try this code

   uri = Uri.fromFile(new File("//assets/testdemo.txt"));
   String testfilepath = uri.getPath();
    File f = new File(testfilepath);
    if (f.exists() == true) {
    Toast.makeText(getApplicationContext(),"valid :" + testfilepath, 2000).show();
    } else {
   Toast.makeText(getApplicationContext(),"invalid :" + testfilepath, 2000).show();
 }

PHP - regex to allow letters and numbers only

try this way .eregi("[^A-Za-z0-9.]", $value)

C split a char array into different variables

I came up with this.This seems to work best for me.It converts a string of number and splits it into array of integer:

void splitInput(int arr[], int sizeArr, char num[])
{
    for(int i = 0; i < sizeArr; i++)
        // We are subtracting 48 because the numbers in ASCII starts at 48.
        arr[i] = (int)num[i] - 48;
}

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

What are the differences between if, else, and else if?

What the if says:

Whether I'm true or not, always check other conditions too.

What the else if says:

Only check other conditions if i wasn't true.

Printing chars and their ASCII-code in C

Chars within single quote ('XXXXXX'), when printed as decimal should output its ASCII value.

int main(){

    printf("D\n");
    printf("The ASCII of D is %d\n",'D');

    return 0;

}

Output:

% ./a.out
>> D
>> The ASCII of D is 68

How to handle a lost KeyStore password in Android?

Just encountered this problem myself - luckily I was able to find the password in some Gradle's temporary file. Just in case anyone lands here:

try looking for this file

..Project\.gradle\2.4\taskArtifacts\taskArtifacts.bin

or

.gradle/3.5/taskHistory/taskHistory.bin
.gradle/5.1.1/executionHistory/executionHistory.bin
.gradle/caches/5.1.1/executionHistory/executionHistory.bin
.gradle/5.1.1/executionHistory/executionHistory.bin
.gradle/3.5/taskHistory/taskHistory.bin
.gradle/2.10/taskArtifacts/taskArtifacts.bin

and search for

storePassword

It was there in cleartext. In general, if you do remember at least a part of your password, try searching for a file containing this substring and hopefully you will fish out something.

Wanted to throw it out here, maybe it will eventually help someone.


Edit: Added new insight from comments, just to be more visible. Edit 2: Added some more locations reported in comments.

Thanks to Vivek Bansal, Amar Ilindra and Uzbekjon for these.

Convert string to title case with JavaScript

A method use reduce

_x000D_
_x000D_
function titleCase(str) {_x000D_
  const arr = str.split(" ");_x000D_
  const result = arr.reduce((acc, cur) => {_x000D_
    const newStr = cur[0].toUpperCase() + cur.slice(1).toLowerCase();_x000D_
    return acc += `${newStr} `_x000D_
  },"")_x000D_
  return result.slice(0, result.length-1);_x000D_
}
_x000D_
_x000D_
_x000D_

Linux: where are environment variables stored?

That variable isn't stored in some script. It's simply set by the X server scripts. You can check the environment variables currently set using set.

Loop inside React JSX

To provide a more straightforward solution in case you want to use a specific row count which is stored as Integer-value.

With the help of typedArrays we could achieve the desired solution in the following manner.

// Let's create a typedArray with length of `numrows`-value
const typedArray = new Int8Array(numrows); // typedArray.length is now 2
const rows = []; // Prepare rows-array
for (let arrKey in typedArray) { // Iterate keys of typedArray
  rows.push(<ObjectRow key={arrKey} />); // Push to an rows-array
}
// Return rows
return <tbody>{rows}</tbody>;

How to use unicode characters in Windows command line?

Try:

chcp 65001

which will change the code page to UTF-8. Also, you need to use Lucida console fonts.

What is the difference between docker-compose ports vs expose

Ports

The ports section will publish ports on the host. Docker will setup a forward for a specific port from the host network into the container. By default this is implemented with a userspace proxy process (docker-proxy) that listens on the first port, and forwards into the container, which needs to listen on the second point. If the container is not listening on the destination port, you will still see something listening on the host, but get a connection refused if you try to connect to that host port, from the failed forward into your container.

Note, the container must be listening on all network interfaces since this proxy is not running within the container's network namespace and cannot reach 127.0.0.1 inside the container. The IPv4 method for that is to configure your application to listen on 0.0.0.0.

Also note that published ports do not work in the opposite direction. You cannot connect to a service on the host from the container by publishing a port. Instead you'll find docker errors trying to listen to the already-in-use host port.

Expose

Expose is documentation. It sets metadata on the image, and when running, on the container too. Typically you configure this in the Dockerfile with the EXPOSE instruction, and it serves as documentation for the users running your image, for them to know on which ports by default your application will be listening. When configured with a compose file, this metadata is only set on the container. You can see the exposed ports when you run a docker inspect on the image or container.

There are a few tools that rely on exposed ports. In docker, the -P flag will publish all exposed ports onto ephemeral ports on the host. There are also various reverse proxies that will default to using an exposed port when sending traffic to your application if you do not explicitly set the container port.

Other than those external tools, expose has no impact at all on the networking between containers. You only need a common docker network, and connecting to the container port, to access one container from another. If that network is user created (e.g. not the default bridge network named bridge), you can use DNS to connect to the other containers.

How do I auto size columns through the Excel interop objects?

This method opens already created excel file, Autofit all columns of all sheets based on 3rd Row. As you can see Range is selected From "A3 to K3" in excel.

 public static void AutoFitExcelSheets()
    {
        Microsoft.Office.Interop.Excel.Application _excel = null;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
        try
        {
            string ExcelPath = ApplicationData.PATH_EXCEL_FILE;
            _excel = new Microsoft.Office.Interop.Excel.Application();
            _excel.Visible = false;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            excelWorkbook = _excel.Workbooks.Open(ExcelPath,
                   0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                   true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
            {
                string Name = currentSheet.Name;
                Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
                Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
                excelCells.Columns.AutoFit();
            }
        }
        catch (Exception ex)
        {
            ProjectLog.AddError("EXCEL ERROR: Can not AutoFit: " + ex.Message);
        }
        finally
        {
            excelWorkbook.Close(true, Type.Missing, Type.Missing);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            releaseObject(excelWorkbook);
            releaseObject(_excel);
        }
    }

How can I pass POST parameters in a URL?

No, you cannot do that. I invite you to read a POST definition.

Or this page: HTTP, request methods

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

The declarative and simpler solution would be :

yourMutableMap.replaceAll((key, val) -> return_value_of_bi_your_function); Nb. be aware your modifying your map state. So this may not be what you want.

Cheers to : http://www.deadcoderising.com/2017-02-14-java-8-declarative-ways-of-modifying-a-map-using-compute-merge-and-replace/

Cleanest way to build an SQL string in Java

For arbitrary SQL, use jOOQ. jOOQ currently supports SELECT, INSERT, UPDATE, DELETE, TRUNCATE, and MERGE. You can create SQL like this:

String sql1 = DSL.using(SQLDialect.MYSQL)  
                 .select(A, B, C)
                 .from(MY_TABLE)
                 .where(A.equal(5))
                 .and(B.greaterThan(8))
                 .getSQL();

String sql2 = DSL.using(SQLDialect.MYSQL)  
                 .insertInto(MY_TABLE)
                 .values(A, 1)
                 .values(B, 2)
                 .getSQL();

String sql3 = DSL.using(SQLDialect.MYSQL)  
                 .update(MY_TABLE)
                 .set(A, 1)
                 .set(B, 2)
                 .where(C.greaterThan(5))
                 .getSQL();

Instead of obtaining the SQL string, you could also just execute it, using jOOQ. See

http://www.jooq.org

(Disclaimer: I work for the company behind jOOQ)

How to extract the decision rules from scikit-learn decision-tree?

I believe that this answer is more correct than the other answers here:

from sklearn.tree import _tree

def tree_to_code(tree, feature_names):
    tree_ = tree.tree_
    feature_name = [
        feature_names[i] if i != _tree.TREE_UNDEFINED else "undefined!"
        for i in tree_.feature
    ]
    print "def tree({}):".format(", ".join(feature_names))

    def recurse(node, depth):
        indent = "  " * depth
        if tree_.feature[node] != _tree.TREE_UNDEFINED:
            name = feature_name[node]
            threshold = tree_.threshold[node]
            print "{}if {} <= {}:".format(indent, name, threshold)
            recurse(tree_.children_left[node], depth + 1)
            print "{}else:  # if {} > {}".format(indent, name, threshold)
            recurse(tree_.children_right[node], depth + 1)
        else:
            print "{}return {}".format(indent, tree_.value[node])

    recurse(0, 1)

This prints out a valid Python function. Here's an example output for a tree that is trying to return its input, a number between 0 and 10.

def tree(f0):
  if f0 <= 6.0:
    if f0 <= 1.5:
      return [[ 0.]]
    else:  # if f0 > 1.5
      if f0 <= 4.5:
        if f0 <= 3.5:
          return [[ 3.]]
        else:  # if f0 > 3.5
          return [[ 4.]]
      else:  # if f0 > 4.5
        return [[ 5.]]
  else:  # if f0 > 6.0
    if f0 <= 8.5:
      if f0 <= 7.5:
        return [[ 7.]]
      else:  # if f0 > 7.5
        return [[ 8.]]
    else:  # if f0 > 8.5
      return [[ 9.]]

Here are some stumbling blocks that I see in other answers:

  1. Using tree_.threshold == -2 to decide whether a node is a leaf isn't a good idea. What if it's a real decision node with a threshold of -2? Instead, you should look at tree.feature or tree.children_*.
  2. The line features = [feature_names[i] for i in tree_.feature] crashes with my version of sklearn, because some values of tree.tree_.feature are -2 (specifically for leaf nodes).
  3. There is no need to have multiple if statements in the recursive function, just one is fine.

How to write to a JSON file in the correct format

To make this work on Ubuntu Linux:

  1. I installed the Ubuntu package ruby-json:

    apt-get install ruby-json
    
  2. I wrote the script in ${HOME}/rubybin/jsonDEMO

  3. $HOME/.bashrc included:

    ${HOME}/rubybin:${PATH}
    

(On this occasion I also typed the above on the bash command line.)

Then it worked when I entered on the command line:

jsonDemo

Fragment onResume() & onPause() is not called on backstack

What i do in child fragment:

@Override
public void onDetach() {
   super.onDetach();
   ParentFragment pf = (ParentFragment) this.getParentFragment();
   pf.onResume();
}

And then override onResume on ParentFragment

Why does intellisense and code suggestion stop working when Visual Studio is open?

One of the thing that just helped me is

  1. Deleting every project file that is out there. My project has 10 folder, 30+ files.
  2. Recreating the project.

This takes about 5 mins - but saves a lot of time as intellisense actually started working.

One thing to note was that the memory usage (right top corner of VS 2013 ultimate) shows about 40% drop.

How do I convert a list into a string with spaces in Python?

" ".join(my_list)

you need to join with a space not an empty string ...

How to get certain commit from GitHub project

Sivan's answer in gif enter image description here

1.Click on commits in github

2.Select Browse code on the right side of each commit

3.Click on download zip , which will download source code at that point of time of commit

Maven does not find JUnit tests to run

junitArtifactName might also be the case if the JUnit in use isn't the standard (junit:junit) but for instance...

<dependency>
    <groupId>org.eclipse.orbit</groupId>
    <artifactId>org.junit</artifactId>
    <version>4.11.0</version>
    <type>bundle</type>
    <scope>test</scope>
</dependency>

Two Divs on the same row and center align both of them

Please take a look on flex it will help you make things right,

on the main div set css display :flex

the div's that inside set css: flex:1 1 auto;

attached jsfiddle link as example enjoy :)

https://jsfiddle.net/hodca/v1uLsxbg/

html select option SELECTED

You're missing quotes for $_GET['sel'] - fixing this might help solving your issue sooner :)

What is the printf format specifier for bool?

You can't, but you can print 0 or 1

_Bool b = 1;
printf("%d\n", b);

source

What is time_t ultimately a typedef to?

Under Visual Studio 2008, it defaults to an __int64 unless you define _USE_32BIT_TIME_T. You're better off just pretending that you don't know what it's defined as, since it can (and will) change from platform to platform.

How to get the first column of a pandas DataFrame as a Series?

>>> import pandas as pd
>>> df = pd.DataFrame({'x' : [1, 2, 3, 4], 'y' : [4, 5, 6, 7]})
>>> df
   x  y
0  1  4
1  2  5
2  3  6
3  4  7
>>> s = df.ix[:,0]
>>> type(s)
<class 'pandas.core.series.Series'>
>>>

===========================================================================

UPDATE

If you're reading this after June 2017, ix has been deprecated in pandas 0.20.2, so don't use it. Use loc or iloc instead. See comments and other answers to this question.

Random string generation with upper case letters and digits

I thought no one had answered this yet lol! But hey, here's my own go at it:

import random

def random_alphanumeric(limit):
    #ascii alphabet of all alphanumerals
    r = (range(48, 58) + range(65, 91) + range(97, 123))
    random.shuffle(r)
    return reduce(lambda i, s: i + chr(s), r[:random.randint(0, len(r))], "")

Maven: Failed to retrieve plugin descriptor error

I had a similar issue with Eclipse and the same steps as Sanders did solve it. It happens because the proxy restricts call to maven repository

  1. Go to D:\Maven\apache-maven-3.0.4-bin\apache-maven-3.0.4\conf (ie your maven installation folder)
  2. Copy settings.xml and paste it in .m2 folder, which is in the users folder of your windows machine.
  3. Add the proxy setting

Something like this:

 <proxies>
    <!-- proxy
      Specification for one proxy, to be used in connecting to the network.
     -->
    <proxy>      
      <active>true</active>
      <protocol>http</protocol>
      <username>your username</username>
      <password>password</password>    
      <host>proxy.host.net</host>
      <port>80</port>  
    </proxy>

  </proxies>

how to get the base url in javascript

Base URL in JavaScript

You can access the current url quite easily in JavaScript with window.location

You have access to the segments of that URL via this locations object. For example:

// This article:
// https://stackoverflow.com/questions/21246818/how-to-get-the-base-url-in-javascript

var base_url = window.location.origin;
// "http://stackoverflow.com"

var host = window.location.host;
// stackoverflow.com

var pathArray = window.location.pathname.split( '/' );
// ["", "questions", "21246818", "how-to-get-the-base-url-in-javascript"]

In Chrome Dev Tools, you can simply enter window.location in your console and it will return all of the available properties.


Further reading is available on this Stack Overflow thread

What is the difference between a stored procedure and a view?

A SQL View is a virtual table, which is based on SQL SELECT query. A view references one or more existing database tables or other views. It is the snap shot of the database whereas a stored procedure is a group of Transact-SQL statements compiled into a single execution plan.

View is simple showcasing data stored in the database tables whereas a stored procedure is a group of statements that can be executed.

A view is faster as it displays data from the tables referenced whereas a store procedure executes sql statements.

Check this article : View vs Stored Procedures . Exactly what you are looking for

How to add an Android Studio project to GitHub

First of all, create a Github account and project in Github. Go to the root folder and follow steps.

The most important thing we forgot here is ignoring the file. Every time we run Gradle or build it creates new files that are changeable from build to build and pc to pc. We do not want all the files from Android Studio to be added to Git. Files like generated code, binary files (executables) should not be added to Git (version control). So please use .gitignore file while uploading projects to Github. It also reduces the size of the project uploaded to the server.

  1. Go to root folder.
  2. git init
  3. Create .gitignore txt file in root folder. Place these content in the file. (this step not required if the file is auto-generated)

    *.iml .gradle /local.properties /.idea/workspace.xml /.idea/libraries .idea .DS_Store /build /captures .externalNativeBuild

  4. git add .
  5. git remote add origin https://github.com/username/project.git
  6. git commit - m "My First Commit"
  7. git push -u origin master

Note : As per suggestion from different developers, they always suggest to use git from the command line. It is up to you.

importing go files in same folder

I just wanted something really basic to move some files out of the main folder, like user2889485's reply, but his specific answer didnt work for me. I didnt care if they were in the same package or not.

My GOPATH workspace is c:\work\go and under that I have

/src/pg/main.go      (package main)
/src/pg/dbtypes.go   (pakage dbtypes)

in main.go I import "/pg/dbtypes"

Rounding a variable to two decimal places C#

You should use a form of Math.Round. Be aware that Math.Round defaults to banker's rounding (rounding to the nearest even number) unless you specify a MidpointRounding value. If you don't want to use banker's rounding, you should use Math.Round(decimal d, int decimals, MidpointRounding mode), like so:

Math.Round(pay, 2, MidpointRounding.AwayFromZero); // .005 rounds up to 0.01
Math.Round(pay, 2, MidpointRounding.ToEven);       // .005 rounds to nearest even (0.00) 
Math.Round(pay, 2);    // Defaults to MidpointRounding.ToEven

(Why does .NET use banker's rounding?)

Copying an array of objects into another array in javascript

A great way for cloning an array is with an array literal and the spread syntax. This is made possible by ES2015.

const objArray = [{name:'first'}, {name:'second'}, {name:'third'}, {name:'fourth'}];

const clonedArr = [...objArray];

console.log(clonedArr) // [Object, Object, Object, Object]

You can find this copy option in MDN's documentation: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator#Copy_an_array

It is also an Airbnb's best practice. https://github.com/airbnb/javascript#es6-array-spreads

Note: The spread syntax in ES2015 goes one level deep while copying an array. Therefore, they are unsuitable for copying multidimensional arrays.

How to convert an int array to String with toString method in Java

System.out.println(array.toString());

should be:

System.out.println(Arrays.toString(array));

Could not resolve placeholder in string value

My solution was to add a space between the $ and the {.

For example:

@Value("${project.ftp.adresse}")

becomes

@Value("$ {project.ftp.adresse}")

Python, Unicode, and the Windows console

James Sulak asked,

Is there any way I can make Python automatically print a ? instead of failing in this situation?

Other solutions recommend we attempt to modify the Windows environment or replace Python's print() function. The answer below comes closer to fulfilling Sulak's request.

Under Windows 7, Python 3.5 can be made to print Unicode without throwing a UnicodeEncodeError as follows:

    In place of:    print(text)
    substitute:     print(str(text).encode('utf-8'))

Instead of throwing an exception, Python now displays unprintable Unicode characters as \xNN hex codes, e.g.:

  Halmalo n\xe2\x80\x99\xc3\xa9tait plus qu\xe2\x80\x99un point noir

Instead of

  Halmalo n’était plus qu’un point noir

Granted, the latter is preferable ceteris paribus, but otherwise the former is completely accurate for diagnostic messages. Because it displays Unicode as literal byte values the former may also assist in diagnosing encode/decode problems.

Note: The str() call above is needed because otherwise encode() causes Python to reject a Unicode character as a tuple of numbers.

How to set upload_max_filesize in .htaccess?

If your web server is running php5, I believe you must use php5_value. This resolved the same error I received when using php_value.

Where does git config --global get written to?

I am running Windows 7 and using git as setup by following the instructions on GitHub (a year or two back). A rather common use-case I would have thought. None of the answers above helped me, and after much frustration I eventually found my 'real' gitconfig file in the following directory;

C:\Users\Bill\AppData\Local\GitHub\PortableGit_054f2e797ebafd44a30203088cd 3d58663c627ef\etc

Obviously substitute your user name and presumably the suffix after PortableGit_ is a unique GUID or similar.

Relative instead of Absolute paths in Excel VBA

if current directory of the operating system is the path of the workbook you are using, Workbooks.Open FileName:= "TRICATEndurance Summary.html" would suffice. if you are making calculations with the path, you can refer to current directory as . and then \ to tell the file is in that dir, and in case you have to change the os's current directory to your workbook's path, you can use ChDrive and ChDir to do so.

ChDrive ThisWorkbook.Path
ChDir ThisWorkbook.Path
Workbooks.Open FileName:= ".\TRICATEndurance Summary.html"

How to create a dynamic array of integers

Since C++11, there's a safe alternative to new[] and delete[] which is zero-overhead unlike std::vector:

std::unique_ptr<int[]> array(new int[size]);

In C++14:

auto array = std::make_unique<int[]>(size);

Both of the above rely on the same header file, #include <memory>

Javascript geocoding from address to latitude and longitude numbers not working

You're accessing the latitude and longitude incorrectly.

Try

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">

var geocoder = new google.maps.Geocoder();
var address = "new york";

geocoder.geocode( { 'address': address}, function(results, status) {

  if (status == google.maps.GeocoderStatus.OK) {
    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();
    alert(latitude);
  } 
}); 
</script>

keytool error bash: keytool: command not found

In Windows 10, you need to add a double slash

./keytool -genkey -v -keystore c:\\Users\\USERNAME\\youralias.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias youralias

Return number of rows affected by UPDATE statements

This is exactly what the OUTPUT clause in SQL Server 2005 onwards is excellent for.

EXAMPLE

CREATE TABLE [dbo].[test_table](
    [LockId] [int] IDENTITY(1,1) NOT NULL,
    [StartTime] [datetime] NULL,
    [EndTime] [datetime] NULL,
PRIMARY KEY CLUSTERED 
(
    [LockId] ASC
) ON [PRIMARY]
) ON [PRIMARY]

INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 07','2009 JUL 07')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 08','2009 JUL 08')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 09','2009 JUL 09')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 10','2009 JUL 10')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 11','2009 JUL 11')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 12','2009 JUL 12')
INSERT INTO test_table(StartTime, EndTime)
VALUES('2009 JUL 13','2009 JUL 13')

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* -- INSERTED reflect the value after the UPDATE, INSERT, or MERGE statement is completed 
WHERE
    StartTime > '2009 JUL 09'

Results in the following being returned

    LockId StartTime                EndTime
-------------------------------------------------------
4      2011-07-01 00:00:00.000  2009-07-10 00:00:00.000
5      2011-07-01 00:00:00.000  2009-07-11 00:00:00.000
6      2011-07-01 00:00:00.000  2009-07-12 00:00:00.000
7      2011-07-01 00:00:00.000  2009-07-13 00:00:00.000

In your particular case, since you cannot use aggregate functions with OUTPUT, you need to capture the output of INSERTED.* in a table variable or temporary table and count the records. For example,

DECLARE @temp TABLE (
  [LockId] [int],
  [StartTime] [datetime] NULL,
  [EndTime] [datetime] NULL 
)

UPDATE test_table
    SET StartTime = '2011 JUL 01'
    OUTPUT INSERTED.* INTO @temp
WHERE
    StartTime > '2009 JUL 09'


-- now get the count of affected records
SELECT COUNT(*) FROM @temp

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

Sometimes you just need to suppress only some warnings and you want to keep other warnings, just to be safe. In your code, you can suppress the warnings for variables and even formal parameters by using GCC's unused attribute. Lets say you have this code snippet:

void func(unsigned number, const int version)
{
  unsigned tmp;
  std::cout << number << std::endl;
}

There might be a situation, when you need to use this function as a handler - which (imho) is quite common in C++ Boost library. Then you need the second formal parameter version, so the function's signature is the same as the template the handler requires, otherwise the compilation would fail. But you don't really need it in the function itself either...

The solution how to mark variable or the formal parameter to be excluded from warnings is this:

void func(unsigned number, const int version __attribute__((unused)))
{
  unsigned tmp __attribute__((unused));
  std::cout << number << std::endl;
}

GCC has many other parameters, you can check them in the man pages. This also works for the C programs, not only C++, and I think it can be used in almost every function, not just handlers. Go ahead and try it! ;)

P.S.: Lately I used this to suppress warnings of Boosts' serialization in template like this:

template <typename Archive>
void serialize(Archive &ar, const unsigned int version __attribute__((unused)))

EDIT: Apparently, I didn't answer your question as you needed, drak0sha done it better. It's because I mainly followed the title of the question, my bad. Hopefully, this might help other people, who get here because of that title... :)

How to show an empty view with a RecyclerView?

For my projects I made this solution (RecyclerView with setEmptyView method):

public class RecyclerViewEmptySupport extends RecyclerView {
    private View emptyView;

    private AdapterDataObserver emptyObserver = new AdapterDataObserver() {


        @Override
        public void onChanged() {
            Adapter<?> adapter =  getAdapter();
            if(adapter != null && emptyView != null) {
                if(adapter.getItemCount() == 0) {
                    emptyView.setVisibility(View.VISIBLE);
                    RecyclerViewEmptySupport.this.setVisibility(View.GONE);
                }
                else {
                    emptyView.setVisibility(View.GONE);
                    RecyclerViewEmptySupport.this.setVisibility(View.VISIBLE);
                }
            }

        }
    };

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

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

    public RecyclerViewEmptySupport(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    public void setAdapter(Adapter adapter) {
        super.setAdapter(adapter);

        if(adapter != null) {
            adapter.registerAdapterDataObserver(emptyObserver);
        }

        emptyObserver.onChanged();
    }

    public void setEmptyView(View emptyView) {
        this.emptyView = emptyView;
    }
}

And you should use it instead of RecyclerView class:

<com.maff.utils.RecyclerViewEmptySupport android:id="@+id/list1"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    />

<TextView android:id="@+id/list_empty"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Empty"
    />

and

RecyclerViewEmptySupport list = 
    (RecyclerViewEmptySupport)rootView.findViewById(R.id.list1);
list.setLayoutManager(new LinearLayoutManager(context));
list.setEmptyView(rootView.findViewById(R.id.list_empty));

Compile to stand alone exe for C# app in Visual Studio 2010

You can get single file EXE after build the console application

your Application folder - > bin folder -> there will have lot of files there is need 2 files must and other referenced dlls

1. IMG_PDF_CONVERSION [this is my application name, take your application name]
2. IMG_PDF_CONVERSION.exe [this is supporting configure file]
3. your refered dll's

then you can move that 3(exe, configure file, refered dll's) dll to any folder that's it

if you click on 1st IMG_PDF_CONVERSION it will execute the application cool way

any calcification please ask your queries.

Detected both log4j-over-slf4j.jar AND slf4j-log4j12.jar on the class path, preempting StackOverflowError.

Encountered a similar error, this how I resolved it:

  1. Access Project explorer view on Netbeans IDE 8.2. Proceed to your project under Dependencies hover the cursor over the log4j-over-slf4j.jar to view the which which dependencies have indirectly imported as shown below. enter image description here

  2. Right click an import jar file and select Exclude Dependency enter image description here

  3. To confirm, open your pom.xml file you will notice the exclusion element as below.

enter image description here 4. Initiate maven clean install and run your project. Good luck!

How to use parameters with HttpPost

To set parameters to your HttpPostRequest you can use BasicNameValuePair, something like this :

    HttpClient httpclient;
    HttpPost httpPost;
    ArrayList<NameValuePair> postParameters;
    httpclient = new DefaultHttpClient();
    httpPost = new HttpPost("your login link");


    postParameters = new ArrayList<NameValuePair>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    httpPost.setEntity(new UrlEncodedFormEntity(postParameters, "UTF-8"));

    HttpResponse response = httpclient.execute(httpPost);

how to define ssh private key for servers fetched by dynamic inventory in files

I'm using the following configuration:

#site.yml:
- name: Example play
  hosts: all
  remote_user: ansible
  become: yes
  become_method: sudo
  vars:
    ansible_ssh_private_key_file: "/home/ansible/.ssh/id_rsa"

How to implement "Access-Control-Allow-Origin" header in asp.net

Configuring the CORS response headers on the server wasn't really an option. You should configure a proxy in client side.

Sample to Angular - So, I created a proxy.conf.json file to act as a proxy server. Below is my proxy.conf.json file:

{
  "/api": {
    "target": "http://localhost:49389",
    "secure": true,
    "pathRewrite": {
      "^/api": "/api"
    },
    "changeOrigin": true
  }
}

Put the file in the same directory the package.json then I modified the start command in the package.json file like below

"start": "ng serve --proxy-config proxy.conf.json"

now, the http call from the app component is as follows:

return this.http.get('/api/customers').map((res: Response) => res.json());

Lastly to run use npm start or ng serve --proxy-config proxy.conf.json

Which Python memory profiler is recommended?

My module memory_profiler is capable of printing a line-by-line report of memory usage and works on Unix and Windows (needs psutil on this last one). Output is not very detailed but the goal is to give you an overview of where the code is consuming more memory, not an exhaustive analysis on allocated objects.

After decorating your function with @profile and running your code with the -m memory_profiler flag it will print a line-by-line report like this:

Line #    Mem usage  Increment   Line Contents
==============================================
     3                           @profile
     4      5.97 MB    0.00 MB   def my_func():
     5     13.61 MB    7.64 MB       a = [1] * (10 ** 6)
     6    166.20 MB  152.59 MB       b = [2] * (2 * 10 ** 7)
     7     13.61 MB -152.59 MB       del b
     8     13.61 MB    0.00 MB       return a

Bad Request - Invalid Hostname IIS7

Did you check the binding is IIS? (inetmgr.exe) It may not be registered to accept all hostnames on 8080.

For example, if you set it up for mysite.com:8080 and hit it at localhost:8080, IIS will get the request but not have a hostname binding to match so it rejects.

Outside of that, you should check the IIS logs (C:\inetpub\logs\wmsvc#) on the server and see if you are seeing your request. Then you'll know if its a problem on your client or on the server itself.

how can I login anonymously with ftp (/usr/bin/ftp)?

As others point out, the user name is usually anonymous, and the password is usually your e-mail address, but this is not universally true, and has been found not to work for certain anonymous FTP sites. For example, at least some cPanel sites seem to deviate from the norm, and if given the traditional user name without domain, one of various errors may result:

If the server uses Pure-FTP as the FTP server:

421 Can't change directory to /var/ftp/ error message.

If the server uses ProFTP as the FTP server:

530 Login Authentication Failed error message.

When one of the aforementioned errors occurs when attempting anonymous access, try including a domain with the username. For example, where example.com is the domain used in your e-mail address:

User name: [email protected]

In the specific case of a cPanel site, the password value is unimportant, and may be left blank, but there is no harm in providing a "traditional" anonymous password formatted as an e-mail address.

For reference, this answer is based on content found on a documentation.cpanel.net Anonymous FTP page. At the time of this writing, it stated:

When users log in to FTP anonymously, they must format usernames as [email protected], where example.com represents the user's domain name. This requirement directs your server to the correct public_ftp directory.

How do I fix a NoSuchMethodError?

For me it happened because I changed argument type in function, from Object a, to String a. I could resolve it with clean and build again

How do multiple clients connect simultaneously to one port, say 80, on a server?

First off, a "port" is just a number. All a "connection to a port" really represents is a packet which has that number specified in its "destination port" header field.

Now, there are two answers to your question, one for stateful protocols and one for stateless protocols.

For a stateless protocol (ie UDP), there is no problem because "connections" don't exist - multiple people can send packets to the same port, and their packets will arrive in whatever sequence. Nobody is ever in the "connected" state.

For a stateful protocol (like TCP), a connection is identified by a 4-tuple consisting of source and destination ports and source and destination IP addresses. So, if two different machines connect to the same port on a third machine, there are two distinct connections because the source IPs differ. If the same machine (or two behind NAT or otherwise sharing the same IP address) connects twice to a single remote end, the connections are differentiated by source port (which is generally a random high-numbered port).

Simply, if I connect to the same web server twice from my client, the two connections will have different source ports from my perspective and destination ports from the web server's. So there is no ambiguity, even though both connections have the same source and destination IP addresses.

Ports are a way to multiplex IP addresses so that different applications can listen on the same IP address/protocol pair. Unless an application defines its own higher-level protocol, there is no way to multiplex a port. If two connections using the same protocol simultaneously have identical source and destination IPs and identical source and destination ports, they must be the same connection.

Format date in a specific timezone

Just came acreoss this, and since I had the same issue, I'd just post the results I came up with

when parsing, you could update the offset (ie I am parsing a data (1.1.2014) and I only want the date, 1st Jan 2014. On GMT+1 I'd get 31.12.2013. So I offset the value first.

moment(moment.utc('1.1.2014').format());

Well, came in handy for me to support across timezones

B

Retrieve specific commit from a remote Git repository

In a project we had a problem so that we had to revert back to a certain commit. We made it with the following command successfully:

git reset --hard <commitID>

Unable to set variables in bash script

folder = "ABC" tries to run a command named folder with arguments = and "ABC". The format of command in bash is:

command arguments separated with space

while assignment is done with:

variable=something

  • In [ -f $newfoldername/Primetime.eyetv], [ is a command (test) and -f and $newfoldername/Primetime.eyetv] are two arguments. It expects a third argument (]) which it can't find (arguments must be separated with space) and thus will show error.
  • [-f $newfoldername/Primetime.eyetv] tries to run a command [-f with argument $newfoldername/Primetime.eyetv]

Generally for cases like this, paste your code in shellcheck and see the feedback.

Rails filtering array of objects by attribute value

If your attachments are

@attachments = Job.find(1).attachments

This will be array of attachment objects

Use select method to filter based on file_type.

@logos = @attachments.select { |attachment| attachment.file_type == 'logo' }
@images = @attachments.select { |attachment| attachment.file_type == 'image' }

This will not trigger any db query.

Why is setTimeout(fn, 0) sometimes useful?

In the question, there existed a race condition between:

  1. The browser's attempt to initialize the drop-down list, ready to have its selected index updated, and
  2. Your code to set the selected index

Your code was consistently winning this race and attempting to set drop-down selection before the browser was ready, meaning that the bug would appear.

This race existed because JavaScript has a single thread of execution that is shared with page rendering. In effect, running JavaScript blocks the updating of the DOM.

Your workaround was:

setTimeout(callback, 0)

Invoking setTimeout with a callback, and zero as the second argument will schedule the callback to be run asynchronously, after the shortest possible delay - which will be around 10ms when the tab has focus and the JavaScript thread of execution is not busy.

The OP's solution, therefore was to delay by about 10ms, the setting of the selected index. This gave the browser an opportunity to initialize the DOM, fixing the bug.

Every version of Internet Explorer exhibited quirky behaviors and this kind of workaround was necessary at times. Alternatively it might have been a genuine bug in the OP's codebase.


See Philip Roberts talk "What the heck is the event loop?" for more thorough explanation.

Java: Finding the highest value in an array

You have your print() statement in the for() loop, It should be after so that it only prints once. the way it currently is, every time the max changes it prints a max.

How can I use delay() with show() and hide() in Jquery

from jquery api

Added to jQuery in version 1.4, the .delay() method allows us to delay the execution of functions that follow it in the queue. It can be used with the standard effects queue or with a custom queue. Only subsequent events in a queue are delayed; for example this will not delay the no-arguments forms of .show() or .hide() which do not use the effects queue.

http://api.jquery.com/delay/

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

How to force Selenium WebDriver to click on element which is not currently visible?

Or you may use Selenium Action Class to simulate user interaction -- For example

    WebDriver = new FirefoxDriver();

    WebElement menu = driver.findElement(By.xpath("")); // the triger event element

    Actions build = new Actions(driver); // heare you state ActionBuider
    build.moveToElement(menu).build().perform(); // Here you perform hover mouse over the needed elemnt to triger the visibility of the hidden
    WebElement m2m= driver.findElement(By.xpath(""));//the previous non visible element
    m2m.click();

How do I change button size in Python?

I've always used .place() for my tkinter widgets. place syntax

You can specify the size of it just by changing the keyword arguments!

Of course, you will have to call .place() again if you want to change it.

Works in python 3.8.2, if you're wondering.

How to get last key in an array?

I would also like to offer an alternative solution to this problem.

Assuming all your keys are numeric without any gaps, my preferred method is to count the array then minus 1 from that value (to account for the fact that array keys start at 0.

$array = array(0=>'dog', 1=>'cat');

$lastKey = count($array)-1;
$lastKeyValue = $array[$lastKey];

var_dump($lastKey);
print_r($lastKeyValue);

This would give you:

int(1) cat

Running Node.js in apache?

If you're using PHP you can funnel your request to Node scripts via shell_exec, passing arguments to scripts as JSON strings in the command line. Example call:

<?php
    shell_exec("node nodeScript.js"); // without arguments
    shell_exec("node nodeScript.js '{[your JSON here]}'"); //with arguments
?>

The caveat is you need to be very careful about handling user data when it goes anywhere near a command line. Example nightmare:

<?php
    $evilUserData = "'; [malicious commands here];";
    shell_exec("node nodeScript.js '{$evilUserData}'");
?>

jQuery UI themes and HTML tables

Why noy just use the theme styles in the table? i.e.

<table>
  <thead class="ui-widget-header">
    <tr>
      <th>Id</th>
      <th>Description</th>
    </td>
  </thead>
  <tbody class="ui-widget-content">
    <tr>
      <td>...</td>
      <td>...</td>
    </tr>
      .
      .
      .
  </tbody>
</table>

And you don't need to use any code...

How do I supply an initial value to a text field?

(From the mailing list. I didn't come up with this answer.)

class _FooState extends State<Foo> {
  TextEditingController _controller;

  @override
  void initState() {
    super.initState();
    _controller = new TextEditingController(text: 'Initial value');
  }

  @override
  Widget build(BuildContext context) {
    return new Column(
      children: <Widget>[
        new TextField(
          // The TextField is first built, the controller has some initial text,
          // which the TextField shows. As the user edits, the text property of
          // the controller is updated.
          controller: _controller,
        ),
        new RaisedButton(
          onPressed: () {
            // You can also use the controller to manipuate what is shown in the
            // text field. For example, the clear() method removes all the text
            // from the text field.
            _controller.clear();
          },
          child: new Text('CLEAR'),
        ),
      ],
    );
  }
}

In R, how to find the standard error of the mean?

You can use the function stat.desc from pastec package.

library(pastec)
stat.desc(x, BASIC =TRUE, NORMAL =TRUE)

you can find more about it from here: https://www.rdocumentation.org/packages/pastecs/versions/1.3.21/topics/stat.desc

from list of integers, get number closest to a given value

Iterate over the list and compare the current closest number with abs(currentNumber - myNumber):

def takeClosest(myList, myNumber):
    closest = myList[0]
    for i in range(1, len(myList)):
        if abs(i - myNumber) < closest:
            closest = i
    return closest

Encrypt & Decrypt using PyCrypto AES 256

You can get a passphrase out of an arbitrary password by using a cryptographic hash function (NOT Python's builtin hash) like SHA-1 or SHA-256. Python includes support for both in its standard library:

import hashlib

hashlib.sha1("this is my awesome password").digest() # => a 20 byte string
hashlib.sha256("another awesome password").digest() # => a 32 byte string

You can truncate a cryptographic hash value just by using [:16] or [:24] and it will retain its security up to the length you specify.

remove all variables except functions

The posted setdiff answer is nice. I just thought I'd post this related function I wrote a while back. Its usefulness is up to the reader :-).

lstype<-function(type='closure'){ 
    inlist<-ls(.GlobalEnv)
    if (type=='function') type <-'closure'
    typelist<-sapply(sapply(inlist,get),typeof)
    return(names(typelist[typelist==type]))
}

How to find the index of an element in an int array?

You can use modern Java to solve this problem. Please use the code below:

static int findIndexOf(int V, int[] arr) {
    return IntStream.range(0, arr.length)
                    .filter(i->arr[i]==V)
                    .findFirst()
                    .getAsInt();
}

Compute row average in pandas

I think this is what you are looking for:

df.drop('Region', axis=1).apply(lambda x: x.mean(), axis=1)

how to use javascript Object.defineProperty

get is a function that is called when you try to read the value player.health, like in:

console.log(player.health);

It's effectively not much different than:

player.getHealth = function(){
  return 10 + this.level*15;
}
console.log(player.getHealth());

The opposite of get is set, which would be used when you assign to the value. Since there is no setter, it seems that assigning to the player's health is not intended:

player.health = 5; // Doesn't do anything, since there is no set function defined

A very simple example:

_x000D_
_x000D_
var player = {_x000D_
  level: 5_x000D_
};_x000D_
_x000D_
Object.defineProperty(player, "health", {_x000D_
  get: function() {_x000D_
    return 10 + (player.level * 15);_x000D_
  }_x000D_
});_x000D_
_x000D_
console.log(player.health); // 85_x000D_
player.level++;_x000D_
console.log(player.health); // 100_x000D_
_x000D_
player.health = 5; // Does nothing_x000D_
console.log(player.health); // 100
_x000D_
_x000D_
_x000D_

"Parameter not valid" exception loading System.Drawing.Image

Which line is throwing the exception? The new MemoryStream(...)? or the Image.FromStream(...)? And what is the byteArrayIn? Is it a byte[]? I only ask because of the comment "And none of value in it is not greater than 255" - which of course is automatic for a byte[].

As a more obvious question: does the binary actually contain an image in a sensible format?

For example, the following (although not great code) works fine:

    byte[] data = File.ReadAllBytes(@"d:\extn.png"); // not a good idea...
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    Console.WriteLine(img.Width);
    Console.WriteLine(img.Height);

git push: permission denied (public key)

I just had to deal with this issue. @user3445140's answer helped me, but was much more than I needed to do.

  1. Get your public SSH key with cat ~/.ssh/id_rsa.pub
  2. Copy the key, including the "ssh-rsa" but excluding your computer name at the end
  3. Go to https://github.com/settings/ssh
  4. Add your SSH key

Easy way of running the same junit test over and over?

The easiest (as in least amount of new code required) way to do this is to run the test as a parametrized test (annotate with an @RunWith(Parameterized.class) and add a method to provide 10 empty parameters). That way the framework will run the test 10 times.

This test would need to be the only test in the class, or better put all test methods should need to be run 10 times in the class.

Here is an example:

@RunWith(Parameterized.class)
public class RunTenTimes {

    @Parameterized.Parameters
    public static Object[][] data() {
        return new Object[10][0];
    }

    public RunTenTimes() {
    }

    @Test
    public void runsTenTimes() {
        System.out.println("run");
    }
}

With the above, it is possible to even do it with a parameter-less constructor, but I'm not sure if the framework authors intended that, or if that will break in the future.

If you are implementing your own runner, then you could have the runner run the test 10 times. If you are using a third party runner, then with 4.7, you can use the new @Rule annotation and implement the MethodRule interface so that it takes the statement and executes it 10 times in a for loop. The current disadvantage of this approach is that @Before and @After get run only once. This will likely change in the next version of JUnit (the @Before will run after the @Rule), but regardless you will be acting on the same instance of the object (something that isn't true of the Parameterized runner). This assumes that whatever runner you are running the class with correctly recognizes the @Rule annotations. That is only the case if it is delegating to the JUnit runners.

If you are running with a custom runner that does not recognize the @Rule annotation, then you are really stuck with having to write your own runner that delegates appropriately to that Runner and runs it 10 times.

Note that there are other ways to potentially solve this (such as the Theories runner) but they all require a runner. Unfortunately JUnit does not currently support layers of runners. That is a runner that chains other runners.

Check if multiple strings exist in another string

any() is by far the best approach if all you want is True or False, but if you want to know specifically which string/strings match, you can use a couple things.

If you want the first match (with False as a default):

match = next((x for x in a if x in str), False)

If you want to get all matches (including duplicates):

matches = [x for x in a if x in str]

If you want to get all non-duplicate matches (disregarding order):

matches = {x for x in a if x in str}

If you want to get all non-duplicate matches in the right order:

matches = []
for x in a:
    if x in str and x not in matches:
        matches.append(x)

Execution failed for task ':app:compileDebugJavaWithJavac' Android Studio 3.1 Update

This problem is commonly related to compiler errors in the Java code. Sometimes Android Studio does not show these errors in the Project explorer. However, when a problematic .java file is opened, errors are shown. Try to resolve errors and rebuild the project.

Iterating over dictionaries using 'for' loops

Iterating over dictionaries using 'for' loops

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:
    ...

How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?

It's not just for loops. The important word here is "iterating".

A dictionary is a mapping of keys to values:

d = {'x': 1, 'y': 2, 'z': 3} 

Any time we iterate over it, we iterate over the keys. The variable name key is only intended to be descriptive - and it is quite apt for the purpose.

This happens in a list comprehension:

>>> [k for k in d]
['x', 'y', 'z']

It happens when we pass the dictionary to list (or any other collection type object):

>>> list(d)
['x', 'y', 'z']

The way Python iterates is, in a context where it needs to, it calls the __iter__ method of the object (in this case the dictionary) which returns an iterator (in this case, a keyiterator object):

>>> d.__iter__()
<dict_keyiterator object at 0x7fb1747bee08>

We shouldn't use these special methods ourselves, instead, use the respective builtin function to call it, iter:

>>> key_iterator = iter(d)
>>> key_iterator
<dict_keyiterator object at 0x7fb172fa9188>

Iterators have a __next__ method - but we call it with the builtin function, next:

>>> next(key_iterator)
'x'
>>> next(key_iterator)
'y'
>>> next(key_iterator)
'z'
>>> next(key_iterator)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
StopIteration

When an iterator is exhausted, it raises StopIteration. This is how Python knows to exit a for loop, or a list comprehension, or a generator expression, or any other iterative context. Once an iterator raises StopIteration it will always raise it - if you want to iterate again, you need a new one.

>>> list(key_iterator)
[]
>>> new_key_iterator = iter(d)
>>> list(new_key_iterator)
['x', 'y', 'z']

Returning to dicts

We've seen dicts iterating in many contexts. What we've seen is that any time we iterate over a dict, we get the keys. Back to the original example:

d = {'x': 1, 'y': 2, 'z': 3} 
for key in d:

If we change the variable name, we still get the keys. Let's try it:

>>> for each_key in d:
...     print(each_key, '=>', d[each_key])
... 
x => 1
y => 2
z => 3

If we want to iterate over the values, we need to use the .values method of dicts, or for both together, .items:

>>> list(d.values())
[1, 2, 3]
>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]

In the example given, it would be more efficient to iterate over the items like this:

for a_key, corresponding_value in d.items():
    print(a_key, corresponding_value)

But for academic purposes, the question's example is just fine.

Reference alias (calculated in SELECT) in WHERE clause

It's actually possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.

A cross join doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does - and treats nulls more transparently.

SELECT
    vars.BalanceDue
FROM
    Entity e
OUTER APPLY (
    SELECT
        -- variables   
        BalanceDue = e.EntityTypeId,
        Variable2 = ...some..long..complex..expression..etc...
    ) vars
WHERE
    vars.BalanceDue > 0

Kudos to Syed Mehroz Alam.

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

How to increase heap size for jBoss server

You can set it as JVM arguments the usual way, e.g. -Xms1024m -Xmx2048m for a minimum heap of 1GB and maximum heap of 2GB. JBoss will use the JAVA_OPTS environment variable to include additional JVM arguments, you could specify it in the /bin/run.conf.bat file:

set "JAVA_OPTS=%JAVA_OPTS% -Xms1024m -Xmx2048m"

However, this is more a workaround than a real solution. If multiple users concurrently uploads big files, you'll hit the same problem sooner or later. You would need to keep increasing memory for nothing. You should rather configure your file upload parser to store the uploaded file on temp disk instead of entirely in memory. As long as it's unclear which parser you're using, no suitable answer can be given. However, more than often Apache Commons FileUpload is used under the covers, you should then read the documentation with "threshold size" as keyword to configure the memory limit for uploaded files. When the file size is beyond the threshold, it would then be written to disk.

Why javascript getTime() is not a function?

To use this function/method,you need an instance of the class Date .

This method is always used in conjunction with a Date object.

See the code below :

var d = new Date();
d.getTime();

Link : http://www.w3schools.com/jsref/jsref_getTime.asp

jQuery text() and newlines

Try this:

$(someElem).html('this<br> has<br> newlines);

How to pass parameters to the DbContext.Database.ExecuteSqlCommand method?

You can either:

1) Pass raw arguments and use the {0} syntax. E.g:

DbContext.Database.SqlQuery("StoredProcedureName {0}", paramName);

2) Pass DbParameter subclass arguments and use @ParamName syntax.

DbContext.Database.SqlQuery("StoredProcedureName @ParamName", 
                                   new SqlParameter("@ParamName", paramValue);

If you use the first syntax, EF will actually wrap your arguments with DbParamater classes, assign them names, and replace {0} with the generated parameter name.

The first syntax if preferred because you don't need to use a factory or know what type of DbParamaters to create (SqlParameter, OracleParamter, etc.).

C pointer to array/array of pointers disambiguation

I don't know if it has an official name, but I call it the Right-Left Thingy(TM).

Start at the variable, then go right, and left, and right...and so on.

int* arr1[8];

arr1 is an array of 8 pointers to integers.

int (*arr2)[8];

arr2 is a pointer (the parenthesis block the right-left) to an array of 8 integers.

int *(arr3[8]);

arr3 is an array of 8 pointers to integers.

This should help you out with complex declarations.

Set default syntax to different filetype in Sublime Text 2

In the current version of Sublime Text 2 (Build: 2139), you can set the syntax for all files of a certain file extension using an option in the menu bar. Open a file with the extension you want to set a default for and navigate through the following menus: View -> Syntax -> Open all with current extension as... ->[your syntax choice].

Updated 2012-06-28: Recent builds of Sublime Text 2 (at least since Build 2181) have allowed the syntax to be set by clicking the current syntax type in the lower right corner of the window. This will open the syntax selection menu with the option to Open all with current extension as... at the top of the menu.

Updated 2016-04-19: As of now, this also works for Sublime Text 3.

Install specific branch from github using Npm

The Doc of the npm defines that only tag/version can be specified after repo_url.

Here is the Doc: https://docs.npmjs.com/cli/install

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

How do you automatically set text box to Uppercase?

This will both show the input in uppercase and send the input data through post in uppercase.

HTML

<input type="text" id="someInput">

JavaScript

var someInput = document.querySelector('#someInput');
someInput.addEventListener('input', function () {
    someInput.value = someInput.value.toUpperCase();
});

How do I split a string, breaking at a particular character?

Even though this is not the simplest way, you could do this:

var addressString = "~john smith~123 Street~Apt 4~New York~NY~12345~",
    keys = "name address1 address2 city state zipcode".split(" "),
    address = {};

// clean up the string with the first replace
// "abuse" the second replace to map the keys to the matches
addressString.replace(/^~|~$/g).replace(/[^~]+/g, function(match){
    address[ keys.unshift() ] = match;
});

// address will contain the mapped result
address = {
    address1: "123 Street"
    address2: "Apt 4"
    city: "New York"
    name: "john smith"
    state: "NY"
    zipcode: "12345"
}

Update for ES2015, using destructuring

const [address1, address2, city, name, state, zipcode] = addressString.match(/[^~]+/g);

// The variables defined above now contain the appropriate information:

console.log(address1, address2, city, name, state, zipcode);
// -> john smith 123 Street Apt 4 New York NY 12345

SSRS Conditional Formatting Switch or IIF

To dynamically change the color of a text box goto properties, goto font/Color and set the following expression

=SWITCH(Fields!CurrentRiskLevel.Value = "Low", "Green",
Fields!CurrentRiskLevel.Value = "Moderate", "Blue",
Fields!CurrentRiskLevel.Value = "Medium", "Yellow",
Fields!CurrentRiskLevel.Value = "High", "Orange",
Fields!CurrentRiskLevel.Value = "Very High", "Red"
)

Same way for tolerance

=SWITCH(Fields!Tolerance.Value = "Low", "Red",
Fields!Tolerance.Value = "Moderate", "Orange",
Fields!Tolerance.Value = "Medium", "Yellow",
Fields!Tolerance.Value = "High", "Blue",
Fields!Tolerance.Value = "Very High", "Green")

Java regex email

You can use this method for validating email address in java.

public class EmailValidator {
    private Pattern pattern;
    private Matcher matcher;

    private static final String EMAIL_PATTERN = 
        "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
        + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

    public EmailValidator() {
        pattern = Pattern.compile(EMAIL_PATTERN);
    }

    /**
    * Validate hex with regular expression
    * 
    * @param hex
    *            hex for validation
    * @return true valid hex, false invalid hex
    */
    public boolean validate(final String hex) {

    matcher = pattern.matcher(hex);
    return matcher.matches();

    }
}

Deleting elements from std::set while iterating

C++20 will have "uniform container erasure", and you'll be able to write:

std::erase_if(numbers, [](int n){ return n % 2 == 0 });

And that will work for vector, set, deque, etc. See cppReference for more info.

How can I check the size of a collection within a Django template?

If you're using a recent Django, changelist 9530 introduced an {% empty %} block, allowing you to write

{% for athlete in athlete_list %}
  ...
{% empty %}
  No athletes
{% endfor %}

Useful when the something that you want to do involves special treatment for lists that might be empty.

"Find next" in Vim

If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.

File tree view in Notepad++

open notepad++, then drag and drop the folder you want to open as tree view.

OR

File ->open folder as workspace , select the file you want.

How to automate browsing using python?

Internet Explorer specific, but rather good:

http://pamie.sourceforge.net/

The advantage compared to urllib/BeautifulSoup is that it executes Javascript as well since it uses IE.

Calling ASP.NET MVC Action Methods from JavaScript

You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d

jQuery post is the short version of jQuery ajax.

function addToCart(id)
{
  $.post('@Url.Action("Add","Cart")',{id:id } function(data) {
    //do whatever with the result.
  });
}

If you want more options like success callbacks and error handling, use jQuery ajax,

function addToCart(id)
{
  $.ajax({
  url: '@Url.Action("Add","Cart")',
  data: { id: id },
  success: function(data){
    //call is successfully completed and we got result in data
  },
  error:function (xhr, ajaxOptions, thrownError){
                  //some errror, some show err msg to user and log the error  
                  alert(xhr.responseText);

                }    
  });
}

When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.

This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.

Twitter Bootstrap onclick event on buttons-radio

This is a really annoying one. What I ended up using is this:

First, create a group of simple buttons with no data-toggle attribute.

<div id="selector" class="btn-group">
    <button type="button" class="btn active">Day</button>
    <button type="button" class="btn">Week</button>
    <button type="button" class="btn">Month</button>
    <button type="button" class="btn">Year</button>
</div>

Next, write an event handler that simulates the radio button effect by 'activating' the clicked one and 'deactivating' all other buttons. (EDIT: Integrated Nick's cleaner version from the comments.)

$('#selector button').click(function() {
    $(this).addClass('active').siblings().removeClass('active');

    // TODO: insert whatever you want to do with $(this) here
});

Pure CSS scroll animation

And for webkit enabled browsers I've had good results with:

.myElement {
    -webkit-overflow-scrolling: touch;
    scroll-behavior: smooth; // Added in from answer from Felix
    overflow-x: scroll;
}

This makes scrolling behave much more like the standard browser behavior - at least it works well on the iPhone we were testing on!

Hope that helps,

Ed

What is the height of iPhone's onscreen keyboard?

iPhone

KeyboardSizes:

  1. 5S, SE, 5, 5C (320 × 568) keyboardSize = (0.0, 352.0, 320.0, 216.0) keyboardSize = (0.0, 315.0, 320.0, 253.0)

2.6S,6,7,8:(375 × 667) : keyboardSize = (0.0, 407.0, 375.0, 260.

3.6+,6S+, 7+ , 8+ : (414 × 736) keyboardSize = (0.0, 465.0, 414.0, 271.0)

4.XS, X :(375 X 812) keyboardSize = (0.0, 477.0, 375.0, 335.0)

5.XR,XSMAX((414 x 896) keyboardSize = (0.0, 550.0, 414.0, 346.0)

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

What is the difference between ApplicationContext and WebApplicationContext in Spring MVC?

The accepted answer is through but there is official explanation on this:

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes (see Using themes), and that it knows which Servlet it is associated with (by having a link to the ServletContext). The WebApplicationContext is bound in the ServletContext, and by using static methods on the RequestContextUtils class you can always look up the WebApplicationContext if you need access to it.

Cited from Spring web framework reference

By the way servlet and root context are both webApplicationContext:

Typical context hierarchy in Spring Web MVC

How to wait in bash for several subprocesses to finish and return exit code !=0 when any subprocess ends with code !=0?

I almost fell into the trap of using jobs -p to collect PIDs, which does not work if the child has already exited, as shown in the script below. The solution I picked was simply calling wait -n N times, where N is the number of children I have, which I happen to know deterministically.

#!/usr/bin/env bash

sleeper() {
    echo "Sleeper $1"
    sleep $2
    echo "Exiting $1"
    return $3
}

start_sleepers() {
    sleeper 1 1 0 &
    sleeper 2 2 $1 &
    sleeper 3 5 0 &
    sleeper 4 6 0 &
    sleep 4
}

echo "Using jobs"
start_sleepers 1

pids=( $(jobs -p) )

echo "PIDS: ${pids[*]}"

for pid in "${pids[@]}"; do
    wait "$pid"
    echo "Exit code $?"
done

echo "Clearing other children"
wait -n; echo "Exit code $?"
wait -n; echo "Exit code $?"

echo "Waiting for N processes"
start_sleepers 2

for ignored in $(seq 1 4); do
    wait -n
    echo "Exit code $?"
done

Output:

Using jobs
Sleeper 1
Sleeper 2
Sleeper 3
Sleeper 4
Exiting 1
Exiting 2
PIDS: 56496 56497
Exiting 3
Exit code 0
Exiting 4
Exit code 0
Clearing other children
Exit code 0
Exit code 1
Waiting for N processes
Sleeper 1
Sleeper 2
Sleeper 3
Sleeper 4
Exiting 1
Exiting 2
Exit code 0
Exit code 2
Exiting 3
Exit code 0
Exiting 4
Exit code 0

How to run only one task in ansible playbook?

This can be easily done using the tags

The example of tags is defined below:

---
hosts: localhost
tasks:
 - name: Creating s3Bucket
   s3_bucket:
        name: ansiblebucket1234567890
   tags: 
       - createbucket

 - name: Simple PUT operation
   aws_s3:
       bucket: ansiblebucket1234567890
       object: /my/desired/key.txt
       src: /etc/ansible/myfile.txt
       mode: put
   tags:
      - putfile

 - name: Create an empty bucket
   aws_s3:
       bucket: ansiblebucket12345678901234
       mode: create
       permission: private
   tags:
       - emptybucket

to execute the tags we use the command

ansible-playbook creates3bucket.yml --tags "createbucket,putfile"

Reading data from DataGridView in C#

 private void HighLightGridRows()
 {            
     Debugger.Launch();
     for (int i = 0; i < dtgvAppSettings.Rows.Count; i++)
     {
         String key = dtgvAppSettings.Rows[i].Cells["Key"].Value.ToString();
         if (key.ToLower().Contains("applicationpath") == true)
         {
             dtgvAppSettings.Rows[i].DefaultCellStyle.BackColor = Color.Yellow;
         }
     }
 }

Best Way to Refresh Adapter/ListView on Android

Simply add these code before setting Adapter it's working for me:

    listView.destroyDrawingCache();
    listView.setVisibility(ListView.INVISIBLE);
    listView.setVisibility(ListView.VISIBLE);

Or Directly you can use below method after change Data resource.

   adapter.notifyDataSetChanged()

./configure : /bin/sh^M : bad interpreter

Or if you want to do this with a script:

sed -i 's/\r//' filename

How do I select an element that has a certain class?

The element.class selector is for styling situations such as this:

<span class="large"> </span>
<p class="large"> </p>

.large {
    font-size:150%; font-weight:bold;
}

p.large {
    color:blue;
}

Both your span and p will be assigned the font-size and font-weight from .large, but the color blue will only be assigned to p.

As others have pointed out, what you're working with is descendant selectors.

Where will log4net create this log file?

If you want your log file to be place at a specified location which will be decided at run time may be your project output directory then you can configure your .config file entry in that way

<file type="log4net.Util.PatternString" value="%property{LogFileName}.txt" />

and then in the code before calling log4net configure, set the new path like below

 log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
 log4net.Config.XmlConfigurator.Configure();

How simple is it? :)

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

C# Reflection: How to get class reference from string?

We can use

Type.GetType()

to get class name and can also create object of it using Activator.CreateInstance(type);

using System;
using System.Reflection;

namespace MyApplication
{
    class Application
    {
        static void Main()
        {
            Type type = Type.GetType("MyApplication.Action");
            if (type == null)
            {
                throw new Exception("Type not found.");
            }
            var instance = Activator.CreateInstance(type);
            //or
            var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
        }
    }

    public class Action
    {
        public string key { get; set; }
        public string Value { get; set; }
    }
}

js 'types' can only be used in a .ts file - Visual Studio Code using @ts-check

Just default the variable to the expected type:

(number=1) => ...
(number=1.0) => ...
(string='str') ...

Gets byte array from a ByteBuffer in java

If one does not know anything about the internal state of the given (Direct)ByteBuffer and wants to retrieve the whole content of the buffer, this can be used:

ByteBuffer byteBuffer = ...;
byte[] data = new byte[byteBuffer.capacity()];
((ByteBuffer) byteBuffer.duplicate().clear()).get(data);

How to analyze disk usage of a Docker container

You can use

docker history IMAGE_ID

to see how the image size is ditributed between its various sub-components.

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
}
else {
    print "Access denied!";
}

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

If you're on Mac OS X, you can install the ca-cert-bundle via homebrew:

$ brew install curl-ca-bundle
$ git config --system http.sslcainfo /usr/local/share/ca-bundle.crt

The formula installs the cert bundle to your share via:

share.install 'ca-bundle.crt'

The share method is just an alias to /usr/local/share, and the curl-ca-bundle is provided by Mozilla. It's what you see being referenced in a lot of issues. Hope this helps as it's not very straightforward about how to approach this on Mac OS X. brew install curl isn't going to get you much either as it's keg only and will not be linked (running which curl will always output /usr/bin/curl, which is the default that ships with your OS). This post may also be of some value.

You'll of course need to disable SSL before you install homebrew since it's a git repo. Just do what curl says when it errors out during SSL verification and:

$ echo insecure >> ~/.curlrc

Once you get homebrew installed along with the curl-ca-bundle, delete .curlrc and try cloning a repo out on github. Ensure that there are no errors and you'll be good to go.

NOTE: If you do resort to .curlrc, please remove it from your system the moment you're done testing. This file can cause major issues, so use it for temporary purposes and with caution. brew doctor will complain in case you forget to purge it from your system).

NOTE: If you update your version of git, you'll need to rerun this command since your system settings will be wiped out (they're stored relative to the git binary based on version).

So after running:

$ brew update
$ brew upgrade

If you get a new version of git, then just rerun:

$ git config --system http.sslcainfo /usr/local/share/ca-bundle.crt

And you'll be all set.

Lastly if you have a new version of git, running:

$ git config -l --system

should give you an error along the lines of

fatal: unable to read config file '/usr/local/Cellar/git/1.8.2.2/etc/gitconfig'

that's your tip that you need to tell git where the Mozilla ca-bundle is.

UPDATE:

.curlrc may or may not be the remedy to your problem. In any case, just get the Mozilla ca-bundle installed on your machine whether you have to manually download it or not. That's what's important here. Once you get the ca-bundle, you're good to go. Just run the git config command and point git to the the ca-bundle.

UPDATE

I recently had to add:

export CURL_CA_BUNDLE=/usr/local/share/ca-bundle.crt to my .zshenv dot file since I'm using zsh. the git config option worked for most cases, but when hitting github over SSL (rvm get stable for example), I still ran into certificate issues. @Maverick pointed this out in his comment, but just in case someone misses it or assumes they don't necessarily need to export this environment variable in addition to running the git config --system.... command. Thanks and hope this helps.

UPDATE

It looks like the curl-ca-bundle was recently removed from homebrew. There is a recommendation here.

You will want to drop some files into:

$(brew --prefix)/etc/openssl/certs

pass post data with window.location.href

I use a very different approach to this. I set browser cookies in the client that expire a second after I set window.location.href.

This is way more secure than embedding your parameters in the URL.

The server receives the parameters as cookies, and the browser deletes the cookies right after they are sent.

const expires = new Date(Date.now() + 1000).toUTCString()
document.cookie = `oauth-username=user123; expires=${expires}`
window.location.href = `https:foo.com/oauth/google/link`