Programs & Examples On #Crichedit

UNIX nonblocking I/O: O_NONBLOCK vs. FIONBIO

As @Sean said, fcntl() is largely standardized, and therefore available across platforms. The ioctl() function predates fcntl() in Unix, but is not standardized at all. That the ioctl() worked for you across all the platforms of relevance to you is fortunate, but not guaranteed. In particular, the names used for the second argument are arcane and not reliable across platforms. Indeed, they are often unique to the particular device driver that the file descriptor references. (The ioctl() calls used for a bit-mapped graphics device running on an ICL Perq running PNX (Perq Unix) of twenty years ago never translated to anything else anywhere else, for example.)

Automatically start forever (node) on system restart

Copied answer from the attached question.

You can use PM2, it's a production process manager for Node.js applications with a built-in load balancer.

Install PM2

$ npm install pm2 -g

Start an application

$ pm2 start app.js

If you using express then you can start your app like

pm2 start ./bin/www --name="app"

Listing all running processes:

$ pm2 list

It will list all process. You can then stop / restart your service by using ID or Name of the app with following command.

$ pm2 stop all                  
$ pm2 stop 0                    
$ pm2 restart all               

To display logs

$ pm2 logs ['all'|app_name|app_id]

CSS property to pad text inside of div

Padding is a way to add kind of a margin inside the Div.
Just Use

div { padding-left: 20px; }

And to mantain the size, you would have to -20px from the original width of the Div.

Named colors in matplotlib

Matplotlib uses a dictionary from its colors.py module.

To print the names use:

# python2:

import matplotlib
for name, hex in matplotlib.colors.cnames.iteritems():
    print(name, hex)

# python3:

import matplotlib
for name, hex in matplotlib.colors.cnames.items():
    print(name, hex)

This is the complete dictionary:

cnames = {
'aliceblue':            '#F0F8FF',
'antiquewhite':         '#FAEBD7',
'aqua':                 '#00FFFF',
'aquamarine':           '#7FFFD4',
'azure':                '#F0FFFF',
'beige':                '#F5F5DC',
'bisque':               '#FFE4C4',
'black':                '#000000',
'blanchedalmond':       '#FFEBCD',
'blue':                 '#0000FF',
'blueviolet':           '#8A2BE2',
'brown':                '#A52A2A',
'burlywood':            '#DEB887',
'cadetblue':            '#5F9EA0',
'chartreuse':           '#7FFF00',
'chocolate':            '#D2691E',
'coral':                '#FF7F50',
'cornflowerblue':       '#6495ED',
'cornsilk':             '#FFF8DC',
'crimson':              '#DC143C',
'cyan':                 '#00FFFF',
'darkblue':             '#00008B',
'darkcyan':             '#008B8B',
'darkgoldenrod':        '#B8860B',
'darkgray':             '#A9A9A9',
'darkgreen':            '#006400',
'darkkhaki':            '#BDB76B',
'darkmagenta':          '#8B008B',
'darkolivegreen':       '#556B2F',
'darkorange':           '#FF8C00',
'darkorchid':           '#9932CC',
'darkred':              '#8B0000',
'darksalmon':           '#E9967A',
'darkseagreen':         '#8FBC8F',
'darkslateblue':        '#483D8B',
'darkslategray':        '#2F4F4F',
'darkturquoise':        '#00CED1',
'darkviolet':           '#9400D3',
'deeppink':             '#FF1493',
'deepskyblue':          '#00BFFF',
'dimgray':              '#696969',
'dodgerblue':           '#1E90FF',
'firebrick':            '#B22222',
'floralwhite':          '#FFFAF0',
'forestgreen':          '#228B22',
'fuchsia':              '#FF00FF',
'gainsboro':            '#DCDCDC',
'ghostwhite':           '#F8F8FF',
'gold':                 '#FFD700',
'goldenrod':            '#DAA520',
'gray':                 '#808080',
'green':                '#008000',
'greenyellow':          '#ADFF2F',
'honeydew':             '#F0FFF0',
'hotpink':              '#FF69B4',
'indianred':            '#CD5C5C',
'indigo':               '#4B0082',
'ivory':                '#FFFFF0',
'khaki':                '#F0E68C',
'lavender':             '#E6E6FA',
'lavenderblush':        '#FFF0F5',
'lawngreen':            '#7CFC00',
'lemonchiffon':         '#FFFACD',
'lightblue':            '#ADD8E6',
'lightcoral':           '#F08080',
'lightcyan':            '#E0FFFF',
'lightgoldenrodyellow': '#FAFAD2',
'lightgreen':           '#90EE90',
'lightgray':            '#D3D3D3',
'lightpink':            '#FFB6C1',
'lightsalmon':          '#FFA07A',
'lightseagreen':        '#20B2AA',
'lightskyblue':         '#87CEFA',
'lightslategray':       '#778899',
'lightsteelblue':       '#B0C4DE',
'lightyellow':          '#FFFFE0',
'lime':                 '#00FF00',
'limegreen':            '#32CD32',
'linen':                '#FAF0E6',
'magenta':              '#FF00FF',
'maroon':               '#800000',
'mediumaquamarine':     '#66CDAA',
'mediumblue':           '#0000CD',
'mediumorchid':         '#BA55D3',
'mediumpurple':         '#9370DB',
'mediumseagreen':       '#3CB371',
'mediumslateblue':      '#7B68EE',
'mediumspringgreen':    '#00FA9A',
'mediumturquoise':      '#48D1CC',
'mediumvioletred':      '#C71585',
'midnightblue':         '#191970',
'mintcream':            '#F5FFFA',
'mistyrose':            '#FFE4E1',
'moccasin':             '#FFE4B5',
'navajowhite':          '#FFDEAD',
'navy':                 '#000080',
'oldlace':              '#FDF5E6',
'olive':                '#808000',
'olivedrab':            '#6B8E23',
'orange':               '#FFA500',
'orangered':            '#FF4500',
'orchid':               '#DA70D6',
'palegoldenrod':        '#EEE8AA',
'palegreen':            '#98FB98',
'paleturquoise':        '#AFEEEE',
'palevioletred':        '#DB7093',
'papayawhip':           '#FFEFD5',
'peachpuff':            '#FFDAB9',
'peru':                 '#CD853F',
'pink':                 '#FFC0CB',
'plum':                 '#DDA0DD',
'powderblue':           '#B0E0E6',
'purple':               '#800080',
'red':                  '#FF0000',
'rosybrown':            '#BC8F8F',
'royalblue':            '#4169E1',
'saddlebrown':          '#8B4513',
'salmon':               '#FA8072',
'sandybrown':           '#FAA460',
'seagreen':             '#2E8B57',
'seashell':             '#FFF5EE',
'sienna':               '#A0522D',
'silver':               '#C0C0C0',
'skyblue':              '#87CEEB',
'slateblue':            '#6A5ACD',
'slategray':            '#708090',
'snow':                 '#FFFAFA',
'springgreen':          '#00FF7F',
'steelblue':            '#4682B4',
'tan':                  '#D2B48C',
'teal':                 '#008080',
'thistle':              '#D8BFD8',
'tomato':               '#FF6347',
'turquoise':            '#40E0D0',
'violet':               '#EE82EE',
'wheat':                '#F5DEB3',
'white':                '#FFFFFF',
'whitesmoke':           '#F5F5F5',
'yellow':               '#FFFF00',
'yellowgreen':          '#9ACD32'}

You could plot them like this:

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.colors as colors
import math


fig = plt.figure()
ax = fig.add_subplot(111)

ratio = 1.0 / 3.0
count = math.ceil(math.sqrt(len(colors.cnames)))
x_count = count * ratio
y_count = count / ratio
x = 0
y = 0
w = 1 / x_count
h = 1 / y_count

for c in colors.cnames:
    pos = (x / x_count, y / y_count)
    ax.add_patch(patches.Rectangle(pos, w, h, color=c))
    ax.annotate(c, xy=pos)
    if y >= y_count-1:
        x += 1
        y = 0
    else:
        y += 1

plt.show()

Commenting out code blocks in Atom

Pressing (Cmd + /) will create a single line comment. i.e. // Single line comment

Type (/** and press the Tab key) to create a block comment ala

/** * Comment block */

How can I see if a Perl hash already has a certain key?

I believe to check if a key exists in a hash you just do

if (exists $strings{$string}) {
    ...
} else {
    ...
}

Spring MVC - How to get all request params in a map in Spring controller?

I might be late to the party, but as per my understanding , you're looking for something like this :

for(String params : Collections.list(httpServletRequest.getParameterNames())) {
    // Whatever you want to do with your map
    // Key : params
    // Value : httpServletRequest.getParameter(params)                
}

Replacing some characters in a string with another character

read filename ;
sed -i 's/letter/newletter/g' "$filename" #letter

^use as many of these as you need, and you can make your own BASIC encryption

C programming: Dereferencing pointer to incomplete type error

the case above is for a new project. I hit upon this error while editing a fork of a well established library.

the typedef was included in the file I was editing but the struct wasn't.

The end result being that I was attempting to edit the struct in the wrong place.

If you run into this in a similar way look for other places where the struct is edited and try it there.

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Your syntax isn't quite right: you need to list the fields in order before the INTO, and the corresponding target variables after:

SELECT Id, dateCreated
INTO iId, dCreate
FROM products
WHERE pName = iName

How to change background color in the Notepad++ text editor?

Notepad++ changed in the past couple of years, and it requires a few extra steps to set up a dark theme.

The answer by Amit-IO is good, but the example theme that is needed has stopped being maintained. The DraculaTheme is active. Just download the XML and put it in a themes folder. You may need Admin access in Windows.

C:\Users\YOUR_USER\AppData\Roaming\Notepad++\themes

https://draculatheme.com/notepad-plus-plus

How can I convert NSDictionary to NSData and vice versa?

NSDictionary -> NSData:

NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:yourDictionary forKey:@"Some Key Value"];
[archiver finishEncoding];
[archiver release];

// Here, data holds the serialized version of your dictionary
// do what you need to do with it before you:
[data release];

NSData -> NSDictionary

NSData *data = [[NSMutableData alloc] initWithContentsOfFile:[self dataFilePath]];
NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:data];
NSDictionary *myDictionary = [[unarchiver decodeObjectForKey:@"Some Key Value"] retain];
[unarchiver finishDecoding];
[unarchiver release];
[data release];

You can do that with any class that conforms to NSCoding.

source

Python error: "IndexError: string index out of range"

There were several problems in your code. Here you have a functional version you can analyze (Lets set 'hello' as the target word):

word = 'hello'
so_far = "-" * len(word)       # Create variable so_far to contain the current guess

while word != so_far:          # if still not complete
    print(so_far)
    guess = input('>> ')       # get a char guess

    if guess in word:
        print("\nYes!", guess, "is in the word!")

        new = ""
        for i in range(len(word)):  
            if guess == word[i]:
                new += guess        # fill the position with new value
            else:
                new += so_far[i]    # same value as before
        so_far = new
    else:
        print("try_again")

print('finish')

I tried to write it for py3k with a py2k ide, be careful with errors.

Where can I find the assembly System.Web.Extensions dll?

EDIT:

The info below is only applicable to VS2008 and the 3.5 framework. VS2010 has a new registry location. Further details can be found on MSDN: How to Add or Remove References in Visual Studio.

ORIGINAL

It should be listed in the .NET tab of the Add Reference dialog. Assemblies that appear there have paths in registry keys under:

HKLM\Software\Microsoft\.NETFramework\AssemblyFolders\

I have a key there named Microsoft .NET Framework 3.5 Reference Assemblies with a string value of:

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\

Navigating there I can see the actual System.Web.Extensions dll.

EDIT:

I found my .NET 4.0 version in:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.Extensions.dll

I'm running Win 7 64 bit, so if you're on a 32 bit OS drop the (x86).

How to validate Google reCAPTCHA v3 on server side?

To verify at server side using PHP. Two most important thing you need to consider.

1. $_POST['g-recaptcha-response']

2.$secretKey = '6LeycSQTAAAAAMM3AeG62pBslQZwBTwCbzeKt06V';

$verifydata = file_get_contents('https://www.google.com/recaptcha/api/siteverify?secret='.$secretKey.'&response='.$_POST['g-recaptcha-response']);
        $response= json_decode($verifydata);

If you get $verifydata true, You done.
For more check out this
Google reCaptcha Using PHP | Only 2 Step Integration

How to get a tab character?

As mentioned, for efficiency reasons sequential spaces are consolidated into one space the browser actually displays. Remember what the ML in HTML stand for. It's a Mark-up Language, designed to control how text is displayed.. not whitespace :p

Still, you can pretend the browser respects tabs since all the TAB does is prepend 4 spaces, and that's easy with CSS. either in line like ...

 <div style="padding-left:4.00em;">Indenented text </div>

Or as a regular class in a style sheet

.tabbed {padding-left:4.00em;}

Then the HTML might look like

<p>regular paragraph regular paragraph regular paragraph</p>
<p class="tabbed">Indented text Indented text Indented text</p>
<p>regular paragraph regular paragraph regular paragraph</p>

Need to make a clickable <div> button

There are two solutions posted on that page. The one with lower votes I would recommend if possible.

If you are using HTML5 then it is perfectly valid to put a div inside of a. As long as the div doesn't also contain some other specific elements like other link tags.

<a href="Music.html">
  <div id="music" class="nav">
    Music I Like
  </div>
</a>

The solution you are confused about actually makes the link as big as its container div. To make it work in your example you just need to add position: relative to your div. You also have a small syntax error which is that you have given the span a class instead of an id. You also need to put your span inside the link because that is what the user is clicking on. I don't think you need the z-index at all from that example.

div { position: relative; }
.hyperspan {
    position:absolute;
    width:100%;
    height:100%;
    left:0;
    top:0;
}

<div id="music" class="nav">Music I Like 
    <a href="http://www.google.com"> 
        <span class="hyperspan"></span>
    </a>   
</div>

http://jsfiddle.net/rBKXM/9

When you give absolute positioning to an element it bases its location and size after the first parent it finds that is relatively positioned. If none, then it uses the document. By adding relative to the parent div you tell the span to only be as big as that.

Linux configure/make, --prefix?

In my situation, --prefix= failed to update the path correctly under some warnings or failures. please see the below link for the answer. https://stackoverflow.com/a/50208379/1283198

Accessing dictionary value by index in python

Let us take an example of dictionary:

numbers = {'first':0, 'second':1, 'third':3}

When I did

numbers.values()[index]

I got an error:'dict_values' object does not support indexing

When I did

numbers.itervalues()

to iterate and extract the values it is also giving an error:'dict' object has no attribute 'iteritems'

Hence I came up with new way of accessing dictionary elements by index just by converting them to tuples.

tuple(numbers.items())[key_index][value_index]

for example:

tuple(numbers.items())[0][0] gives 'first'

if u want to edit the values or sort the values the tuple object does not allow the item assignment. In this case you can use

list(list(numbers.items())[index])

Postgres ERROR: could not open file for reading: Permission denied

I had the same error message but was using psycopg2 to communicate with PostgreSQL. I fixed the permission issues by using the functions copy_from and copy_expert that will open the file on the client side as the user running the python script and feed the data to the database over STDIN.

Refer to this link for further information.

Removing Conda environment

Because you can only deactivate the active environment, so conda deactivate does not need nor accept arguments. The error message is very explicit here.

Just call conda deactivate https://github.com/conda/conda/issues/7296#issuecomment-389504269

Calculate correlation for more than two variables?

Use the same function (cor) on a data frame, e.g.:

> cor(VADeaths)
             Rural Male Rural Female Urban Male Urban Female
Rural Male    1.0000000    0.9979869  0.9841907    0.9934646
Rural Female  0.9979869    1.0000000  0.9739053    0.9867310
Urban Male    0.9841907    0.9739053  1.0000000    0.9918262
Urban Female  0.9934646    0.9867310  0.9918262    1.0000000

Or, on a data frame also holding discrete variables, (also sometimes referred to as factors), try something like the following:

> cor(mtcars[,unlist(lapply(mtcars, is.numeric))])
            mpg        cyl       disp         hp        drat         wt        qsec         vs          am       gear        carb
mpg   1.0000000 -0.8521620 -0.8475514 -0.7761684  0.68117191 -0.8676594  0.41868403  0.6640389  0.59983243  0.4802848 -0.55092507
cyl  -0.8521620  1.0000000  0.9020329  0.8324475 -0.69993811  0.7824958 -0.59124207 -0.8108118 -0.52260705 -0.4926866  0.52698829
disp -0.8475514  0.9020329  1.0000000  0.7909486 -0.71021393  0.8879799 -0.43369788 -0.7104159 -0.59122704 -0.5555692  0.39497686
hp   -0.7761684  0.8324475  0.7909486  1.0000000 -0.44875912  0.6587479 -0.70822339 -0.7230967 -0.24320426 -0.1257043  0.74981247
drat  0.6811719 -0.6999381 -0.7102139 -0.4487591  1.00000000 -0.7124406  0.09120476  0.4402785  0.71271113  0.6996101 -0.09078980
wt   -0.8676594  0.7824958  0.8879799  0.6587479 -0.71244065  1.0000000 -0.17471588 -0.5549157 -0.69249526 -0.5832870  0.42760594
qsec  0.4186840 -0.5912421 -0.4336979 -0.7082234  0.09120476 -0.1747159  1.00000000  0.7445354 -0.22986086 -0.2126822 -0.65624923
vs    0.6640389 -0.8108118 -0.7104159 -0.7230967  0.44027846 -0.5549157  0.74453544  1.0000000  0.16834512  0.2060233 -0.56960714
am    0.5998324 -0.5226070 -0.5912270 -0.2432043  0.71271113 -0.6924953 -0.22986086  0.1683451  1.00000000  0.7940588  0.05753435
gear  0.4802848 -0.4926866 -0.5555692 -0.1257043  0.69961013 -0.5832870 -0.21268223  0.2060233  0.79405876  1.0000000  0.27407284
carb -0.5509251  0.5269883  0.3949769  0.7498125 -0.09078980  0.4276059 -0.65624923 -0.5696071  0.05753435  0.2740728  1.00000000

SQL Server 2008: How to query all databases sizes?

sometimes SECURITY issues prevent from asking for all the db's and you need to query one by one with the db prefix, for those cases i created this dynamic query

go
declare @Results table ([Name] nvarchar(max), [DataFileSizeMB] int, [LogFileSizeMB] int);

declare @QaQuery nvarchar(max)
declare @name nvarchar(max)

declare MY_CURSOR cursor 
  local static read_only forward_only
for 
select name from master.dbo.sysdatabases where name not in ('master', 'tempdb', 'model', 'msdb', 'rdsadmin');

open MY_CURSOR
fetch next from MY_CURSOR into @name
while @@FETCH_STATUS = 0
begin 
    if(len(@name)>0)
    begin
        print @name + ' Column Exist'
        set @QaQuery = N'select 
                            '''+@name+''' as Name
                            ,sum(case when type = 0 then size else 0 end) as DataFileSizeMB
                            ,sum(case when type = 1 then size else 0 end) as LogFileSizeMB
                        from ['+@name+'].sys.database_files
                        group by replace(name, ''_log'', '''')';

        insert @Results exec sp_executesql @QaQuery;
    end
  fetch next from MY_CURSOR into @name
end
close MY_CURSOR
deallocate MY_CURSOR

select * from @Results order by DataFileSizeMB desc
go

How to find out the number of CPUs using python

Can't figure out how to add to the code or reply to the message but here's support for jython that you can tack in before you give up:

# jython
try:
    from java.lang import Runtime
    runtime = Runtime.getRuntime()
    res = runtime.availableProcessors()
    if res > 0:
        return res
except ImportError:
    pass

What's the advantage of a Java enum versus a class with public static final fields?

There is less confusion. Take Font for instance. It has a constructor that takes the name of the Font you want, its size and its style (new Font(String, int, int)). To this day I cannot remember if style or size goes first. If Font had used an enum for all of its different styles (PLAIN, BOLD, ITALIC, BOLD_ITALIC), its constructor would look like Font(String, Style, int), preventing any confusion. Unfortunately, enums weren't around when the Font class was created, and since Java has to maintain reverse compatibility, we will always be plagued by this ambiguity.

Of course, this is just an argument for using an enum instead of public static final constants. Enums are also perfect for singletons and implementing default behavior while allowing for later customization (I.E. the strategy pattern). An example of the latter is java.nio.file's OpenOption and StandardOpenOption: if a developer wanted to create his own non-standard OpenOption, he could.

Android refresh current activity

You can use this to refresh an Activity from within itself.

finish();
startActivity(getIntent());

How can I use MS Visual Studio for Android Development?

If you want to create an Android application using c# language you can use Xamarin.
they created this great Cross Platform development tool which enables developers to develop iOS and Android apps in C# language.

Xamarin is offered in different licenses from free to enterprise levels but for not I will be using the starter version which is the free version. It includes the Xamarin Studio which is great start for those who want to try out creating their first apps for Android, they also offer a Business license which lets you develop in Visual Studio so you can use that rich experience similar to developing Web Apps or Windows Apps, then they have this Enterprise which contains everything

mysqli_real_connect(): (HY000/2002): No such file or directory

If above solutions doesn't work, try to change the default por from 3306, to another one (i.e. 3307)

Simpler way to create dictionary of separate variables?

In python 3 this is easy

myVariable = 5
for v in locals():
  if id(v) == id("myVariable"):
    print(v, locals()[v])

this will print:

myVariable 5

Print a file, skipping the first X lines, in Bash

A less verbose version with AWK:

awk 'NR > 1e6' myfile.txt

But I would recommend using integer numbers.

Error when deploying an artifact in Nexus

If any of the above answers worked out, You can create new artifact directly from the admin side of (NEXUS Screen shot attached below).

  1. Login to nexus UI http://YOUR_URL:8081/nexus( username: admin default password: admin123 )
  2. Click repositories on the left side then click the repo, For eg: click release.
  3. Choose artifact Upload (last tab).
  4. Choose GAV definition as GAV Param- Then enter your groupid , artifact id and version .
  5. Choose Jar file.
  6. Click upload artifact. Thats it !

Now you will be able to add the corrsponding in your project.(screenshot below)

enter image description here

How to stop (and restart) the Rails Server?

In case that doesn't work there is another way that works especially well in Windows: Kill localhost:3000 process from Windows command line

Jquery to change form action

To change action value of form dynamically, you can try below code:

below code is if you are opening some dailog box and inside that dailog box you have form and you want to change the action of it. I used Bootstrap dailog box and on opening of that dailog box I am assigning action value to the form.

$('#your-dailog-id').on('show.bs.modal', function (event) {
    var link = $(event.relatedTarget);// Link that triggered the modal
    var cURL= link.data('url');// Extract info from data-* attributes
    $("#delUserform").attr("action", cURL);
});

If you are trying to change the form action on regular page, use below code

$("#yourElementId").change(function() { 
  var action = <generate_action>;
  $("#formId").attr("action", action);
});

Cordova : Requirements check failed for JDK 1.8 or greater

Uninstalling older versions of JDK would have worked. But it may be a workaround i guess. I faced the same issue and noticed that both new version of JDK and older version JDK path has been mentioned in 'path' environmental variable.

Removing the older version JDK path from 'path' environmental variable did the trick for me. Hope it helps someone too.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Suppose a 9800GT GPU:

  • it has 14 multiprocessors (SM)
  • each SM has 8 thread-processors (AKA stream-processors, SP or cores)
  • allows up to 512 threads per block
  • warpsize is 32 (which means each of the 14x8=112 thread-processors can schedule up to 32 threads)

https://www.tutorialspoint.com/cuda/cuda_threads.htm

A block cannot have more active threads than 512 therefore __syncthreads can only synchronize limited number of threads. i.e. If you execute the following with 600 threads:

func1();
__syncthreads();
func2();
__syncthreads();

then the kernel must run twice and the order of execution will be:

  1. func1 is executed for the first 512 threads
  2. func2 is executed for the first 512 threads
  3. func1 is executed for the remaining threads
  4. func2 is executed for the remaining threads

Note:

The main point is __syncthreads is a block-wide operation and it does not synchronize all threads.


I'm not sure about the exact number of threads that __syncthreads can synchronize, since you can create a block with more than 512 threads and let the warp handle the scheduling. To my understanding it's more accurate to say: func1 is executed at least for the first 512 threads.

Before I edited this answer (back in 2010) I measured 14x8x32 threads were synchronized using __syncthreads.

I would greatly appreciate if someone test this again for a more accurate piece of information.

Can't load AMD 64-bit .dll on a IA 32-bit platform

If you are still getting that error after installing the 64 bit JRE, it means that the JVM running Gurobi package is still using the 32 bit JRE.

Check that you have updated the PATH and JAVA_HOME globally and in the command shell that you are using. (Maybe you just need to exit and restart it.)

Check that your command shell runs the right version of Java by running "java -version" and checking that it says it is a 64bit JRE.

If you are launching the example via a wrapper script / batch file, make sure that the script is using the right JRE. Modify as required ...

Section vs Article HTML5

also, for syndicated content "Authors are encouraged to use the article element instead of the section element when it would make sense to syndicate the contents of the element."

Could not find a version that satisfies the requirement <package>

After 2 hours of searching, I found a way to fix it with just one line of command. You need to know the version of the package (Just search up PACKAGE version).

Command:

python3 -m pip install --pre --upgrade PACKAGE==VERSION.VERSION.VERSION

ValueError: object too deep for desired array while using convolution

You could try using scipy.ndimage.convolve it allows convolution of multidimensional images. here is the docs

Parsing query strings on Android

Origanally answered here

On Android, there is Uri class in package android.net . Note that Uri is part of android.net, while URI is part of java.net .

Uri class has many functions to extract query key-value pairs. enter image description here

Following function returns key-value pairs in the form of HashMap.

In Java:

Map<String, String> getQueryKeyValueMap(Uri uri){
    HashMap<String, String> keyValueMap = new HashMap();
    String key;
    String value;

    Set<String> keyNamesList = uri.getQueryParameterNames();
    Iterator iterator = keyNamesList.iterator();

    while (iterator.hasNext()){
        key = (String) iterator.next();
        value = uri.getQueryParameter(key);
        keyValueMap.put(key, value);
    }
    return keyValueMap;
}

In Kotlin:

fun getQueryKeyValueMap(uri: Uri): HashMap<String, String> {
        val keyValueMap = HashMap<String, String>()
        var key: String
        var value: String

        val keyNamesList = uri.queryParameterNames
        val iterator = keyNamesList.iterator()

        while (iterator.hasNext()) {
            key = iterator.next() as String
            value = uri.getQueryParameter(key) as String
            keyValueMap.put(key, value)
        }
        return keyValueMap
    }

How do I measure execution time of a command on the Windows command line?

If you have a command window open and call the commands manually, you can display a timestamp on each prompt, e.g.

prompt $d $t $_$P$G

It gives you something like:

23.03.2009 15:45:50,77

C:\>

If you have a small batch script that executes your commands, have an empty line before each command, e.g.

(empty line)

myCommand.exe

(next empty line)

myCommand2.exe

You can calculate the execution time for each command by the time information in the prompt. The best would probably be to pipe the output to a textfile for further analysis:

MyBatchFile.bat > output.txt

How to disable the back button in the browser using JavaScript

history.pushState(null, null, document.title);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.title);
});

This script will overwrite attempts to navigate back and forth with the state of the current page.


Update:

Some users have reported better success with using document.URL instead of document.title:

history.pushState(null, null, document.URL);
window.addEventListener('popstate', function () {
    history.pushState(null, null, document.URL);
});

How can I loop through a List<T> and grab each item?

foreach:

foreach (var money in myMoney) {
    Console.WriteLine("Amount is {0} and type is {1}", money.amount, money.type);
}

MSDN Link

Alternatively, because it is a List<T>.. which implements an indexer method [], you can use a normal for loop as well.. although its less readble (IMO):

for (var i = 0; i < myMoney.Count; i++) {
    Console.WriteLine("Amount is {0} and type is {1}", myMoney[i].amount, myMoney[i].type);
}

How to convert a set to a list in python?

It is already a list

type(my_set)
>>> <type 'list'>

Do you want something like

my_set = set([1,2,3,4])
my_list = list(my_set)
print my_list
>> [1, 2, 3, 4]

EDIT : Output of your last comment

>>> my_list = [1,2,3,4]
>>> my_set = set(my_list)
>>> my_new_list = list(my_set)
>>> print my_new_list
[1, 2, 3, 4]

I'm wondering if you did something like this :

>>> set=set()
>>> set([1,2])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'set' object is not callable

How to get the date 7 days earlier date from current date in Java

Or use JodaTime:

DateTime lastWeek = new DateTime().minusDays(7);

How to convert string to Title Case in Python?

def capitalizeWords(s):
  return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)

re.sub can take a function for the "replacement" (rather than just a string, which is the usage most people seem to be familiar with). This repl function will be called with an re.Match object for each match of the pattern, and the result (which should be a string) will be used as a replacement for that match.

A longer version of the same thing:

WORD_RE = re.compile(r'\w+')

def capitalizeMatch(m):
  return m.group(0).capitalize()

def capitalizeWords(s):
  return WORD_RE.sub(capitalizeMatch, s)

This pre-compiles the pattern (generally considered good form) and uses a named function instead of a lambda.

How to add an action to a UIAlertView button using Swift iOS

The Swifty way is to use the new UIAlertController and closures:

    // Create the alert controller
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .Alert)

    // Create the actions
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default) {
        UIAlertAction in
        NSLog("OK Pressed")
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }

    // Add the actions
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)

    // Present the controller
    self.presentViewController(alertController, animated: true, completion: nil)

Swift 3:

    // Create the alert controller
    let alertController = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert)

    // Create the actions
    let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.default) {
        UIAlertAction in
        NSLog("OK Pressed")
    }
    let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.cancel) {
        UIAlertAction in
        NSLog("Cancel Pressed")
    }

    // Add the actions
    alertController.addAction(okAction)
    alertController.addAction(cancelAction)

    // Present the controller
    self.present(alertController, animated: true, completion: nil)

What is the size of a pointer?

They can be different on word-addressable machines (e.g., Cray PVP systems).

Most computers today are byte-addressable machines, where each address refers to a byte of memory. There, all data pointers are usually the same size, namely the size of a machine address.

On word-adressable machines, each machine address refers instead to a word larger than a byte. On these, a (char *) or (void *) pointer to a byte of memory has to contain both a word address plus a byte offset within the addresed word.

http://docs.cray.com/books/004-2179-001/html-004-2179-001/rvc5mrwh.html

How to install Android SDK Build Tools on the command line?

As stated in other responses, the build tools requires the --all flag to be installed. You also better use a -t filter flag to avoid installing ALL the packages but there is no way to filter all the build tools.

There are already features requests for these two points in AOSP bug tracker. Feel free to vote for them, this might make them happen some day:

How to export table as CSV with headings on Postgresql?

I am posting this answer because none of the other answers given here actually worked for me. I could not use COPY from within Postgres, because I did not have the correct permissions. So I chose "Export grid rows" and saved the output as UTF-8.

The psql version given by @Brian also did not work for me, for a different reason. The reason it did not work is that apparently the Windows command prompt (I was using Windows) was meddling around with the encoding on its own. I kept getting this error:

ERROR: character with byte sequence 0x81 in encoding "WIN1252" has no equivalent in encoding "UTF8"

The solution I ended up using was to write a short JDBC script (Java) which read the CSV file and issued insert statements directly into my Postgres table. This worked, but the command prompt also would have worked had it not been altering the encoding.

Using Custom Domains With IIS Express

The invalid hostname indicates that the actual site you configured in the IIS Express configuration file is (most likely) not running. IIS Express doesn't have a process model like IIS does.


For your site to run it would need to be started explicitly (either by opening and accessing from webmatrix, or from command line calling iisexpress.exe (from it's installation directory) with the /site parameter.


In general, the steps to allow fully qualified DNS names to be used for local access are Let's use your example of the DNS name dev.example.com

  1. edit %windows%\system32\drivers\etc\hosts file to map dev.example.com to 127.0.0.1 (admin privilege required). If you control DNS server (like in Nick's case) then the DNS entry is sufficient as this step is not needed.
  2. If you access internet through proxy, make sure the dev.example.com will not be forwared to proxy (you have to put in on the exception list in your browser (for IE it would be Tools/Internet Options/Connections/Lan Settings, then go to Proxy Server/Advanced and put dev.example.com on the exeption list.
  3. Configure IIS Express binding for your site (eg:Site1) to include dev.example.com. Administrative privilege will be needed to use the binding. Alternatively, a one-time URL reservation can be made with http.sys using

    netsh http add urlacl url=http://dev.example.com:<port>/ user=<user_name>

  4. start iisexpress /site:Site1 or open Site1 in WebMatrix

How do I include a Perl module that's in a different directory?

I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.

#!/usr/bin/perl
use FindBin::libs;
use <your lib>;

Can I update a JSF component from a JSF backing bean method?

I also tried to update a component from a jsf backing bean/class

You need to do the following after manipulating the UI component:

FacesContext.getCurrentInstance().getPartialViewContext().getRenderIds().add(componentToBeRerendered.getClientId())

It is important to use the clientId instead of the (server-side) componentId!!

How do I find the absolute position of an element using jQuery?

Note that $(element).offset() tells you the position of an element relative to the document. This works great in most circumstances, but in the case of position:fixed you can get unexpected results.

If your document is longer than the viewport and you have scrolled vertically toward the bottom of the document, then your position:fixed element's offset() value will be greater than the expected value by the amount you have scrolled.

If you are looking for a value relative to the viewport (window), rather than the document on a position:fixed element, you can subtract the document's scrollTop() value from the fixed element's offset().top value. Example: $("#el").offset().top - $(document).scrollTop()

If the position:fixed element's offset parent is the document, you want to read parseInt($.css('top')) instead.

What is apache's maximum url length?

  • Internet Explorer: 2,083 characters, with no more than 2,048 characters in the path portion of the URL
  • Firefox: 65,536 characters show up, but longer URLs do still work even up past 100,000
  • Safari: > 80,000 characters
  • Opera: > 190,000 characters
  • IIS: 16,384 characters, but is configurable
  • Apache: 4,000 characters

From: http://www.danrigsby.com/blog/index.php/2008/06/17/rest-and-max-url-size/

A hex viewer / editor plugin for Notepad++?

According to some comments on Super User it still works :) It just should be copied back to the plugins folder (if it's in the disabled folder) or downloaded from Plugins Central. I have downloaded it a few minutes ago and succeeded in using it.

Of course, be warned: this plugin COULD be unstable in some situations - that's why it was disabled.

MS-DOS Batch file pause with enter key

Depending on which OS you're using, if you are flexible, then CHOICE can be used to wait on almost any key EXCEPT enter

If you are really referring to what Microsoft insists on calling "Command Prompt" which is simply an MS-DOS emulator, then perhaps TIMEOUT may suit your purpose (timeout /t -1 waits on any key, not just ENTER) and of course CHOICE is available again in recent WIN editions.

And a warning on SET /P - whereas set /p DUMMY=Hit ENTER to continue... will work,

set "dummy="
set /p DUMMY=Hit ENTER to continue...
if defined dummy (echo not just ENTER was pressed) else (echo just ENTER was pressed)

will detect whether just ENTER or something else, ending in ENTER was keyed in.

Drop a temporary table if it exists

From SQL Server 2016 you can just use

 DROP TABLE IF EXISTS ##CLIENTS_KEYWORD

On previous versions you can use

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
/*Then it exists*/
DROP TABLE ##CLIENTS_KEYWORD
CREATE TABLE ##CLIENTS_KEYWORD
(
   client_id INT
)

You could also consider truncating the table instead rather than dropping and recreating.

IF OBJECT_ID('tempdb..##CLIENTS_KEYWORD', 'U') IS NOT NULL
  TRUNCATE TABLE ##CLIENTS_KEYWORD
ELSE
  CREATE TABLE ##CLIENTS_KEYWORD
  (
     client_id INT
  ) 

Proper way to return JSON using node or Express

The res.json() function should be sufficient for most cases.

app.get('/', (req, res) => res.json({ answer: 42 }));

The res.json() function converts the parameter you pass to JSON using JSON.stringify() and sets the Content-Type header to application/json; charset=utf-8 so HTTP clients know to automatically parse the response.

C# try catch continue execution

just do this

    try
    {
        //some code
     try
     {
          int idNumber = function2();

     }
     finally
     {
       do stuff here....
     }
    }
    catch(Exception e)
    {//... perhaps something here}

For all intents and purposes the finally block will always execute. Now there are a couple of exceptions where it won't actually execute: task killing the program, and there is a fast fail security exception which kills the application instantly. Other than that, an exception will be thrown in function 2, the finally block will execute the needed code and then catch the exception in the outer catch block.

Scroll RecyclerView to show selected item on top

You just need to call recyclerview.scrollToPosition(position). That's fine!

If you want to call it in adapter, just let your adapter has the instance of recyclerview or the activity or fragment which contains recyclerview,than implements the method getRecyclerview() in them.

I hope it can help you.

Why do abstract classes in Java have constructors?

I guess root of this question is that people believe that a call to a constructor creates the object. That is not the case. Java nowhere claims that a constructor call creates an object. It just does what we want constructor to do, like initialising some fields..that's all. So an abstract class's constructor being called doesn't mean that its object is created.

Manually install Gradle and use it in Android Studio

Like @ said

https://services.gradle.org/distributions/

Download The Latest Gradle Distribution File and Extract It, Then Copy all Files and Paste it Under:

C:\Users\{USERNAME}\.gradle\wrapper\dists\

but you have to first make Android Studio try downloading the zip file and cancel it.

That way you can get the hash and copy the file and put it under the hash

Easy way to pull latest of all git submodules

I don't know since which version of git this is working, but that's what you're searching for:

git submodule update --recursive

I use it with git pull to update the root repository, too:

git pull && git submodule update --recursive

Dynamically converting java object of Object class to a given class when class name is known

you don't, declare an interface that declares the methods you would like to call:

public interface MyInterface
{
  void doStuff();
}

public class MyClass implements MyInterface
{
  public void doStuff()
  {
    System.Console.Writeln("done!");
  }
}

then you use

MyInterface mobj = (myInterface)obj;
mobj.doStuff();

If MyClassis not under your control then you can't make it implement some interface, and the other option is to rely on reflection (see this tutorial).

Twitter - share button, but with image

I used this code to solve this problem.

<a href="https://twitter.com/intent/tweet?url=myUrl&text=myTitle" target="_blank"><img src="path_to_my_image"/></a>

You can check the tweet-button documentation here tweet-button

How can I use numpy.correlate to do autocorrelation?

I use talib.CORREL for autocorrelation like this, I suspect you could do the same with other packages:

def autocorrelate(x, period):

    # x is a deep indicator array 
    # period of sample and slices of comparison

    # oldest data (period of input array) may be nan; remove it
    x = x[-np.count_nonzero(~np.isnan(x)):]
    # subtract mean to normalize indicator
    x -= np.mean(x)
    # isolate the recent sample to be autocorrelated
    sample = x[-period:]
    # create slices of indicator data
    correls = []
    for n in range((len(x)-1), period, -1):
        alpha = period + n
        slices = (x[-alpha:])[:period]
        # compare each slice to the recent sample
        correls.append(ta.CORREL(slices, sample, period)[-1])
    # fill in zeros for sample overlap period of recent correlations    
    for n in range(period,0,-1):
        correls.append(0)
    # oldest data (autocorrelation period) will be nan; remove it
    correls = np.array(correls[-np.count_nonzero(~np.isnan(correls)):])      

    return correls

# CORRELATION OF BEST FIT
# the highest value correlation    
max_value = np.max(correls)
# index of the best correlation
max_index = np.argmax(correls)

PHP not displaying errors even though display_errors = On

When you update the configuration in the php.ini file, you might have to restart apache. Try running apachectl restart or apache2ctl restart, or something like that.

Also, in you ini file, make sure you have display_errors = on, but only in a development environment, never in a production machine.

Also, the strictest error reporting is exactly what you have cited, E_ALL | E_STRICT. You can find more information on error levels at the php docs.

Install a Windows service using a Windows command prompt?

the following code , install and uninstall the Service,

Open the command prompt and run the program as an administrator and fire the below command and press enter.

Syntax

To Install

C:\windows\microsoft.net\framework\v4.0.30319>InstallUtil.exe + Your copied path + \your service name + .exe

eg :Our Path InstallUtil.exe C:\MyFirstService\bin\Debug\MyFirstService.exe

To uninstall

 C:\windows\microsoft.net\framework\v4.0.30319>InstallUtil.exe -u + Your copied path + \your service name + .exe

eg : Our path InstallUtil.exe -u C:\MyFirstService\bin\Debug\MyFirstService.exe

for more help you can see the following link: sample program

How to insert table values from one database to another database?

INSERT
INTO    remotedblink.remotedatabase.remoteschema.remotetable
SELECT  *
FROM    mytable

There is no such thing as "the end of the table" in relational databases.

How do I consume the JSON POST data in an Express application

_x000D_
_x000D_
const express = require('express');_x000D_
let app = express();_x000D_
app.use(express.json());
_x000D_
_x000D_
_x000D_

This app.use(express.json) will now let you read the incoming post JSON object

Parsing string as JSON with single quotes?

Using single quotes for keys are not allowed in JSON. You need to use double quotes.

For your use-case perhaps this would be the easiest solution:

str = '{"a":1}';

Source:

If a property requires quotes, double quotes must be used. All property names must be surrounded by double quotes.

How to get the current time as datetime

I know there are a lot of answers but I think that mine may be more convenient to many

extension String {
    init(epoch: Double) {
        let date = Date(timeIntervalSince1970: epoch)

        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "dd/MM/yyyy HH:mm:ssZZZ"

        self = dateFormatter.string(from: date)
    }
}

Double decimal formatting in Java

Works 100%.

import java.text.DecimalFormat;

public class Formatting {

    public static void main(String[] args) {
        double value = 22.2323242434342;
        // or  value = Math.round(value*100) / 100.0;

        System.out.println("this is before formatting: "+value);
        DecimalFormat df = new DecimalFormat("####0.00");

        System.out.println("Value: " + df.format(value));
    }

}

Gradle error: could not execute build using gradle distribution

For me the following two steps fixed the issue:

  1. Make sure the Gradle build was successful
  2. Android Studio - File - Invalidate Caches / Restart...

How to overplot a line on a scatter plot in python?

I'm partial to scikits.statsmodels. Here an example:

import statsmodels.api as sm
import numpy as np
import matplotlib.pyplot as plt

X = np.random.rand(100)
Y = X + np.random.rand(100)*0.1

results = sm.OLS(Y,sm.add_constant(X)).fit()

print results.summary()

plt.scatter(X,Y)

X_plot = np.linspace(0,1,100)
plt.plot(X_plot, X_plot*results.params[0] + results.params[1])

plt.show()

The only tricky part is sm.add_constant(X) which adds a columns of ones to X in order to get an intercept term.

     Summary of Regression Results
=======================================
| Dependent Variable:            ['y']|
| Model:                           OLS|
| Method:                Least Squares|
| Date:               Sat, 28 Sep 2013|
| Time:                       09:22:59|
| # obs:                         100.0|
| Df residuals:                   98.0|
| Df model:                        1.0|
==============================================================================
|                   coefficient     std. error    t-statistic          prob. |
------------------------------------------------------------------------------
| x1                      1.007       0.008466       118.9032         0.0000 |
| const                 0.05165       0.005138        10.0515         0.0000 |
==============================================================================
|                          Models stats                      Residual stats  |
------------------------------------------------------------------------------
| R-squared:                     0.9931   Durbin-Watson:              1.484  |
| Adjusted R-squared:            0.9930   Omnibus:                    12.16  |
| F-statistic:                1.414e+04   Prob(Omnibus):           0.002294  |
| Prob (F-statistic):        9.137e-108   JB:                        0.6818  |
| Log likelihood:                 223.8   Prob(JB):                  0.7111  |
| AIC criterion:                 -443.7   Skew:                     -0.2064  |
| BIC criterion:                 -438.5   Kurtosis:                   2.048  |
------------------------------------------------------------------------------

example plot

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I respect all the solutions given here.

But what I came to know after reading all these, we haven't observed that on which folder the struts.xml file or any configuration file which is necessary for the web application.

My SOULUTION IS:

  1. copy the struts.xml file to the src folder of our project.
  2. click "file-->save all" in eclipse and go click "project-->clean".
  3. restart the server.

Hope the problem solved.

What's the difference between commit() and apply() in SharedPreferences

From javadoc:

Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a > apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself

Draw on HTML5 Canvas using a mouse

Here is a working sample.

_x000D_
_x000D_
 <html>_x000D_
    <script type="text/javascript">_x000D_
    var canvas, ctx, flag = false,_x000D_
        prevX = 0,_x000D_
        currX = 0,_x000D_
        prevY = 0,_x000D_
        currY = 0,_x000D_
        dot_flag = false;_x000D_
_x000D_
    var x = "black",_x000D_
        y = 2;_x000D_
    _x000D_
    function init() {_x000D_
        canvas = document.getElementById('can');_x000D_
        ctx = canvas.getContext("2d");_x000D_
        w = canvas.width;_x000D_
        h = canvas.height;_x000D_
    _x000D_
        canvas.addEventListener("mousemove", function (e) {_x000D_
            findxy('move', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mousedown", function (e) {_x000D_
            findxy('down', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mouseup", function (e) {_x000D_
            findxy('up', e)_x000D_
        }, false);_x000D_
        canvas.addEventListener("mouseout", function (e) {_x000D_
            findxy('out', e)_x000D_
        }, false);_x000D_
    }_x000D_
    _x000D_
    function color(obj) {_x000D_
        switch (obj.id) {_x000D_
            case "green":_x000D_
                x = "green";_x000D_
                break;_x000D_
            case "blue":_x000D_
                x = "blue";_x000D_
                break;_x000D_
            case "red":_x000D_
                x = "red";_x000D_
                break;_x000D_
            case "yellow":_x000D_
                x = "yellow";_x000D_
                break;_x000D_
            case "orange":_x000D_
                x = "orange";_x000D_
                break;_x000D_
            case "black":_x000D_
                x = "black";_x000D_
                break;_x000D_
            case "white":_x000D_
                x = "white";_x000D_
                break;_x000D_
        }_x000D_
        if (x == "white") y = 14;_x000D_
        else y = 2;_x000D_
    _x000D_
    }_x000D_
    _x000D_
    function draw() {_x000D_
        ctx.beginPath();_x000D_
        ctx.moveTo(prevX, prevY);_x000D_
        ctx.lineTo(currX, currY);_x000D_
        ctx.strokeStyle = x;_x000D_
        ctx.lineWidth = y;_x000D_
        ctx.stroke();_x000D_
        ctx.closePath();_x000D_
    }_x000D_
    _x000D_
    function erase() {_x000D_
        var m = confirm("Want to clear");_x000D_
        if (m) {_x000D_
            ctx.clearRect(0, 0, w, h);_x000D_
            document.getElementById("canvasimg").style.display = "none";_x000D_
        }_x000D_
    }_x000D_
    _x000D_
    function save() {_x000D_
        document.getElementById("canvasimg").style.border = "2px solid";_x000D_
        var dataURL = canvas.toDataURL();_x000D_
        document.getElementById("canvasimg").src = dataURL;_x000D_
        document.getElementById("canvasimg").style.display = "inline";_x000D_
    }_x000D_
    _x000D_
    function findxy(res, e) {_x000D_
        if (res == 'down') {_x000D_
            prevX = currX;_x000D_
            prevY = currY;_x000D_
            currX = e.clientX - canvas.offsetLeft;_x000D_
            currY = e.clientY - canvas.offsetTop;_x000D_
    _x000D_
            flag = true;_x000D_
            dot_flag = true;_x000D_
            if (dot_flag) {_x000D_
                ctx.beginPath();_x000D_
                ctx.fillStyle = x;_x000D_
                ctx.fillRect(currX, currY, 2, 2);_x000D_
                ctx.closePath();_x000D_
                dot_flag = false;_x000D_
            }_x000D_
        }_x000D_
        if (res == 'up' || res == "out") {_x000D_
            flag = false;_x000D_
        }_x000D_
        if (res == 'move') {_x000D_
            if (flag) {_x000D_
                prevX = currX;_x000D_
                prevY = currY;_x000D_
                currX = e.clientX - canvas.offsetLeft;_x000D_
                currY = e.clientY - canvas.offsetTop;_x000D_
                draw();_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
    </script>_x000D_
    <body onload="init()">_x000D_
        <canvas id="can" width="400" height="400" style="position:absolute;top:10%;left:10%;border:2px solid;"></canvas>_x000D_
        <div style="position:absolute;top:12%;left:43%;">Choose Color</div>_x000D_
        <div style="position:absolute;top:15%;left:45%;width:10px;height:10px;background:green;" id="green" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:15%;left:46%;width:10px;height:10px;background:blue;" id="blue" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:15%;left:47%;width:10px;height:10px;background:red;" id="red" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:45%;width:10px;height:10px;background:yellow;" id="yellow" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:46%;width:10px;height:10px;background:orange;" id="orange" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:17%;left:47%;width:10px;height:10px;background:black;" id="black" onclick="color(this)"></div>_x000D_
        <div style="position:absolute;top:20%;left:43%;">Eraser</div>_x000D_
        <div style="position:absolute;top:22%;left:45%;width:15px;height:15px;background:white;border:2px solid;" id="white" onclick="color(this)"></div>_x000D_
        <img id="canvasimg" style="position:absolute;top:10%;left:52%;" style="display:none;">_x000D_
        <input type="button" value="save" id="btn" size="30" onclick="save()" style="position:absolute;top:55%;left:10%;">_x000D_
        <input type="button" value="clear" id="clr" size="23" onclick="erase()" style="position:absolute;top:55%;left:15%;">_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

C# version of java's synchronized keyword?

static object Lock = new object();

lock (Lock) 
{
// do stuff
}

Spark RDD to DataFrame python

Try if that works

sc = spark.sparkContext

# Infer the schema, and register the DataFrame as a table.
schemaPeople = spark.createDataFrame(RddName)
schemaPeople.createOrReplaceTempView("RddName")

Converting a String array into an int Array in java

To get rid of additional whitespace, you could change the code like this:

intarray[i]=Integer.parseInt(str.trim()); // No more Exception in this line

In angular $http service, How can I catch the "status" of error?

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. Have a look at the docs https://docs.angularjs.org/api/ng/service/$http

Now the right way to use is:

// Simple GET request example:
$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
});

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

A response status code between 200 and 299 is considered a success status and will result in the success callback being called.

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

How to remove spaces from a string using JavaScript?

SHORTEST and FASTEST: str.replace(/ /g, '');


Benchmark:

Here my results - (2018.07.13) MacOs High Sierra 10.13.3 on Chrome 67.0.3396 (64-bit), Safari 11.0.3 (13604.5.6), Firefox 59.0.2 (64-bit) ):

SHORT strings

Short string similar to examples from OP question

enter image description here

The fastest solution on all browsers is / /g (regexp1a) - Chrome 17.7M (operation/sec), Safari 10.1M, Firefox 8.8M. The slowest for all browsers was split-join solution. Change to \s or add + or i to regexp slows down processing.

LONG strings

For string about ~3 milion character results are:

  • regexp1a: Safari 50.14 ops/sec, Firefox 18.57, Chrome 8.95
  • regexp2b: Safari 38.39, Firefox 19.45, Chrome 9.26
  • split-join: Firefox 26.41, Safari 23.10, Chrome 7.98,

You can run it on your machine: https://jsperf.com/remove-string-spaces/1

What does random.sample() method in python do?

According to documentation:

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Basically, it picks k unique random elements, a sample, from a sequence:

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample works also directly from a range:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

In addition to sequences, random.sample works with sets too:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

However, random.sample doesn't work with arbitrary iterators:

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set.  For dicts, use list(d).

How can I pass data from Flask to JavaScript in a template?

Just another alternative solution for those who want to pass variables to a script which is sourced using flask, I only managed to get this working by defining the variables outside and then calling the script as follows:

    <script>
    var myfileuri = "/static/my_csv.csv"
    var mytableid = 'mytable';
    </script>
    <script type="text/javascript" src="/static/test123.js"></script>

If I input jinja variables in test123.js it doesn't work and you will get an error.

java.lang.NoClassDefFoundError: org/json/JSONObject

The Exception it self says it all java.lang.ClassNotFoundException: org.json.JSONObject

You have not added the necessary jar file which will be having org.json.JSONObject class to your classpath.

You can Download it From Here

jQuery event for images loaded

imagesLoaded Plugin is way to go ,if you need a crossbrowser solution

 $("<img>", {src: 'image.jpg'}).imagesLoaded( function( $images, $proper, $broken ){
 if($broken.length > 0){
 //Error CallBack
 console.log('Error');
 }
 else{
 // Load CallBack
 console.log('Load');
 }
 });

If You Just Need a IE WorkAround,This Will Do

 var img = $("<img>", {
    error: function() {console.log('error'); },
    load: function() {console.log('load');}
    });
  img.attr('src','image.jpg');

Oracle sqlldr TRAILING NULLCOLS required, but why?

The problem here is that you have defined ID as a field in your data file when what you want is to just use an expression without any data from the data file. You can fix this by defining ID as an expression (or a sequence in this case)

ID EXPRESSION "ID_SEQ.nextval"

or

ID SEQUENCE(count)

See: http://docs.oracle.com/cd/B28359_01/server.111/b28319/ldr_field_list.htm#i1008234 for all options

docker unauthorized: authentication required - upon push with successful login

Make sure your docker repositry name matches your local docker repo name. e.g lets say if you local repo name "kavashgar/nodjsapp"

then your should also have a repo names "kavashgar" in docker hub

What does the "+" (plus sign) CSS selector mean?

+ selector is called Adjacent Sibling Selector.

For example, the selector p + p, selects the p elements immediately following the p elements

It can be thought of as a looking outside selector which checks for the immediately following element.

Here is a sample snippet to make things more clear:

_x000D_
_x000D_
body {_x000D_
  font-family: Tahoma;_x000D_
  font-size: 12px;_x000D_
}_x000D_
p + p {_x000D_
  margin-left: 10px;_x000D_
}
_x000D_
<div>_x000D_
  <p>Header paragraph</p>_x000D_
  <p>This is a paragraph</p>_x000D_
  <p>This is another paragraph</p>_x000D_
  <p>This is yet another paragraph</p>_x000D_
  <hr>_x000D_
  <p>Footer paragraph</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Since we are one the same topic, it is worth mentioning another selector, ~ selector, which is General Sibling Selector

For example, p ~ p selects all the p which follows the p doesn't matter where it is, but both p should be having the same parent.

Here is how it looks like with the same markup:

_x000D_
_x000D_
body {_x000D_
  font-family: Tahoma;_x000D_
  font-size: 12px;_x000D_
}_x000D_
p ~ p {_x000D_
  margin-left: 10px;_x000D_
}
_x000D_
<div>_x000D_
  <p>Header paragraph</p>_x000D_
  <p>This is a paragraph</p>_x000D_
  <p>This is another paragraph</p>_x000D_
  <p>This is yet another paragraph</p>_x000D_
  <hr>_x000D_
  <p>Footer paragraph</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Notice that the last p is also matched in this sample.

Eclipse - java.lang.ClassNotFoundException

Changing the order of classpath artifacts in the Java Build Path resolved it for me.

  1. Right Click on the project and go to Project Build path.
  2. Go to, Order and Export tab and move the JRE system library to after the sources.

This should fix it.

How to create string with multiple spaces in JavaScript

With template literals, you can use multiple spaces or multi-line strings and string interpolation. Template Literals are a new ES2015 / ES6 feature that allows you to work with strings. The syntax is very simple, just use backticks instead of single or double quotes:

let a = `something                 something`;

and to make multiline strings just press enter to create a new line, with no special characters:

let a = `something 

    
                         something`;

The results are exactly the same as you write in the string.

TensorFlow, "'module' object has no attribute 'placeholder'"

It may be the typo if you incorrectly wrote the placeholder word. In my case I misspelled it as placehoder and got the error like this: AttributeError: 'module' object has no attribute 'placehoder'

How to pass form input value to php function

You need to look into Ajax; Start here this is the best way to stay on the current page and be able to send inputs to php.

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
var xmlhttp;
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

This gets the users input on the textbox and opens the webpage gethint.php?q=ja from here the php script can do anything with $_GET['q'] and echo back to the page James, Jason....etc

How to hide a <option> in a <select> menu with CSS?

// Simplest way

var originalContent = $('select').html();

$('select').change(function() {
    $('select').html(originalContent); //Restore Original Content
    $('select option[myfilter=1]').remove(); // Filter my options
});

Change the "No file chosen":

<div class="field">
    <label class="field-label" for="photo">Your photo</label>
    <input class="field-input" type="file" name="photo"  id="photo" value="photo" />
</div>

and the css

input[type="file"]
{ 
   color: transparent; 
   background-color: #F89406; 
   border: 2px solid #34495e; 
   width: 100%; 
   height: 36px; 
   border-radius: 3px; 
}

Laravel csrf token mismatch for ajax POST Request

The best way to solve this problem "X-CSRF-TOKEN" is to add the following code to your main layout, and continue making your ajax calls normally:

In header

<meta name="csrf-token" content="{{ csrf_token() }}" />

In script

<script type="text/javascript">
$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});
</script>

Limiting floats to two decimal points

Use

print"{:.2f}".format(a)

instead of

print"{0:.2f}".format(a)

Because the latter may lead to output errors when trying to output multiple variables (see comments).

close fancy box from function from within open 'fancybox'

i had the same issues a longtime then i got the solution by the below code. please use

parent.jQuery.fancybox.close()

IndexOf function in T-SQL

CHARINDEX is what you are looking for

select CHARINDEX('@', '[email protected]')
-----------
8

(1 row(s) affected)

-or-

select CHARINDEX('c', 'abcde')
-----------
3

(1 row(s) affected)

SSRS Query execution failed for dataset

I had the similar issue showing the error

For more information about this error navigate to the report server on the local server machine, or enable remote errors Query execution failed for dataset 'PrintInvoice'.

Solution: 1) The error may be with the dataset in some cases, you can always check if the dataset is populating the exact data you are expecting by going to the dataset properties and choosing 'Query Designer' and try 'Run', If you can successfully able to pull the fields you are expecting, then you can be sure that there isn't any problem with the dataset, which takes us to next solution.

2) Even though the error message says "Query Failed Execution for the dataset", another probable chances are with the datasource connection, make sure you have connected to the correct datasource that has the tables you need and you have permissions to access that datasource.

Git error on git pull (unable to update local ref)

rm .git/refs/remotes/origin/master

It works to me!

XPath - Selecting elements that equal a value

Try

//*[text()='qwerty'] because . is your current element

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

You can easily write the method to do that :

  public static String toCamelCase(final String init) {
    if (init == null)
        return null;

    final StringBuilder ret = new StringBuilder(init.length());

    for (final String word : init.split(" ")) {
        if (!word.isEmpty()) {
            ret.append(Character.toUpperCase(word.charAt(0)));
            ret.append(word.substring(1).toLowerCase());
        }
        if (!(ret.length() == init.length()))
            ret.append(" ");
    }

    return ret.toString();
}

Listing only directories in UNIX

Since there are dozens of ways to do it, here is another one:

tree -d -L 1 -i --noreport
  • -d: directories
  • -L: depth of the tree (hence 1, our working directory)
  • -i: no indentation, print names only
  • --noreport: do not report information at the end of the tree listing

mysql: SOURCE error 2?

I've had the same error on Windows. I solved it with (after on cmd: mysql -u root):

mysql> SOURCE C:/users/xxx/xxxx/metropolises.sql;

Be sure you type the right file path

Why don't Java's +=, -=, *=, /= compound assignment operators require casting?

Very good question. The Java Language specification confirms your suggestion.

For example, the following code is correct:

short x = 3;
x += 4.6;

and results in x having the value 7 because it is equivalent to:

short x = 3;
x = (short)(x + 4.6);

What is a race condition?

A race condition is an undesirable situation that occurs when two or more process can access and change the shared data at the same time.It occurred because there were conflicting accesses to a resource . Critical section problem may cause race condition. To solve critical condition among the process we have take out only one process at a time which execute the critical section.

How to convert a PIL Image into a numpy array?

If your image is stored in a Blob format (i.e. in a database) you can use the same technique explained by Billal Begueradj to convert your image from Blobs to a byte array.

In my case, I needed my images where stored in a blob column in a db table:

def select_all_X_values(conn):
    cur = conn.cursor()
    cur.execute("SELECT ImageData from PiecesTable")    
    rows = cur.fetchall()    
    return rows

I then created a helper function to change my dataset into np.array:

X_dataset = select_all_X_values(conn)
imagesList = convertToByteIO(np.array(X_dataset))

def convertToByteIO(imagesArray):
    """
    # Converts an array of images into an array of Bytes
    """
    imagesList = []

    for i in range(len(imagesArray)):  
        img = Image.open(BytesIO(imagesArray[i])).convert("RGB")
        imagesList.insert(i, np.array(img))

    return imagesList

After this, I was able to use the byteArrays in my Neural Network.

plt.imshow(imagesList[0])

What is uintptr_t data type

It's an unsigned integer type exactly the size of a pointer. Whenever you need to do something unusual with a pointer - like for example invert all bits (don't ask why) you cast it to uintptr_t and manipulate it as a usual integer number, then cast back.

How to convert .crt to .pem

You can do this conversion with the OpenSSL library

http://www.openssl.org/

Windows binaries can be found here:

http://www.slproweb.com/products/Win32OpenSSL.html

Once you have the library installed, the command you need to issue is:

openssl x509 -in mycert.crt -out mycert.pem -outform PEM

How to install a specific JDK on Mac OS X?

If you installed brew, cmd below will be helpful:

brew cask install java

How to resolve 'unrecognized selector sent to instance'?

For me, what caused this error was that I accidentally had the same message being sent twice to the same class member. When I right clicked on the button in the gui, I could see the method name twice, and I just deleted one. Newbie mistake in my case for sure, but wanted to get it out there for other newbies to consider.

How to use Javascript to read local text file and read line by line?

Without jQuery:

document.getElementById('file').onchange = function(){

  var file = this.files[0];

  var reader = new FileReader();
  reader.onload = function(progressEvent){
    // Entire file
    console.log(this.result);

    // By lines
    var lines = this.result.split('\n');
    for(var line = 0; line < lines.length; line++){
      console.log(lines[line]);
    }
  };
  reader.readAsText(file);
};

HTML:

<input type="file" name="file" id="file">

Remember to put your javascript code after the file field is rendered.

How to install Laravel's Artisan?

Explanation: When you install a new laravel project on your folder(for example myfolder) using the composer, it installs the complete laravel project inside your folder(myfolder/laravel) than artisan is inside laravel.that's, why you see an error,

Could not open input file: artisan

Solution: You have to go inside by command prompt to that location or move laravel files inside your folder.

How to create a circular ImageView in Android?

I too needed a rounded ImageView, I used the below code, you can modify it accordingly:

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RoundedImageView extends ImageView {

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

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

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

    @Override
    protected void onDraw(Canvas canvas) {

        Drawable drawable = getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }
        Bitmap b = ((BitmapDrawable) drawable).getBitmap();
        Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

        int w = getWidth();
        @SuppressWarnings("unused")
        int h = getHeight();

        Bitmap roundBitmap = getCroppedBitmap(bitmap, w);
        canvas.drawBitmap(roundBitmap, 0, 0, null);

    }

    public static Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
        Bitmap sbmp;

        if (bmp.getWidth() != radius || bmp.getHeight() != radius) {
            float smallest = Math.min(bmp.getWidth(), bmp.getHeight());
            float factor = smallest / radius;
            sbmp = Bitmap.createScaledBitmap(bmp,
                    (int) (bmp.getWidth() / factor),
                    (int) (bmp.getHeight() / factor), false);
        } else {
            sbmp = bmp;
        }

        Bitmap output = Bitmap.createBitmap(radius, radius, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final String color = "#BAB399";
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, radius, radius);

        paint.setAntiAlias(true);
        paint.setFilterBitmap(true);
        paint.setDither(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(Color.parseColor(color));
        canvas.drawCircle(radius / 2 + 0.7f, radius / 2 + 0.7f,
                radius / 2 + 0.1f, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(sbmp, rect, rect, paint);

        return output;
    }

}

Algorithm to find Largest prime factor of a number

The simplest solution is a pair of mutually recursive functions.

The first function generates all the prime numbers:

  1. Start with a list of all natural numbers greater than 1.
  2. Remove all numbers that are not prime. That is, numbers that have no prime factors (other than themselves). See below.

The second function returns the prime factors of a given number n in increasing order.

  1. Take a list of all the primes (see above).
  2. Remove all the numbers that are not factors of n.

The largest prime factor of n is the last number given by the second function.

This algorithm requires a lazy list or a language (or data structure) with call-by-need semantics.

For clarification, here is one (inefficient) implementation of the above in Haskell:

import Control.Monad

-- All the primes
primes = 2 : filter (ap (<=) (head . primeFactors)) [3,5..]

-- Gives the prime factors of its argument
primeFactors = factor primes
  where factor [] n = []
        factor xs@(p:ps) n =
          if p*p > n then [n]
          else let (d,r) = divMod n p in
            if r == 0 then p : factor xs d
            else factor ps n

-- Gives the largest prime factor of its argument
largestFactor = last . primeFactors

Making this faster is just a matter of being more clever about detecting which numbers are prime and/or factors of n, but the algorithm stays the same.

How to set commands output as a variable in a batch file

These answers were all so close to the answer that I needed. This is an attempt to expand on them.

In a Batch file

If you're running from within a .bat file and you want a single line that allows you to export a complicated command like jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json to a variable named AWS_ACCESS_KEY then you want this:

FOR /F "tokens=* USEBACKQ" %%g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET "AWS_ACCESS_KEY=%%g")

On the Command Line

If you're at the C:\ prompt you want a single line that allows you to run a complicated command like jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json to a variable named AWS_ACCESS_KEY then you want this:

FOR /F "tokens=* USEBACKQ" %g IN (`jq -r ".Credentials.AccessKeyId" c:\temp\mfa-getCreds.json`) do (SET "AWS_ACCESS_KEY=%g")

Explanation

The only difference between the two answers above is that on the command line, you use a single % in your variable. In a batch file, you have to double up on the percentage signs (%%).

Since the command includes colons, quotes, and parentheses, you need to include the USEBACKQ line in the options so that you can use backquotes to specify the command to run and then all kinds of funny characters inside of it.

How to change fontFamily of TextView in Android

The easiest way to add the font programatically to a TextView is to, first, add the font file in your Assets folder in the project. For example your font path is looking like this: assets/fonts/my_font.otf

And add it to a TextView as:

Kotlin

val font_path = "fonts/my_font.otf"  

myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)

textView.typeface = myTypeface

Java

String font_path = "fonts/my_font.otf";
Typeface myTypeface = Typeface.createFromAsset(MyApplication.getInstance().assets, font_path)
textView.setTypeface(myTypeface);

How to launch a Google Chrome Tab with specific URL using C#

If the user doesn't have Chrome, it will throw an exception like this:

    //chrome.exe http://xxx.xxx.xxx --incognito
    //chrome.exe http://xxx.xxx.xxx -incognito
    //chrome.exe --incognito http://xxx.xxx.xxx
    //chrome.exe -incognito http://xxx.xxx.xxx
    private static void Chrome(string link)
    {
        string url = "";

        if (!string.IsNullOrEmpty(link)) //if empty just run the browser
        {
            if (link.Contains('.')) //check if it's an url or a google search
            {
                url = link;
            }
            else
            {
                url = "https://www.google.com/search?q=" + link.Replace(" ", "+");
            }
        }

        try
        {
            Process.Start("chrome.exe", url + " --incognito");
        }
        catch (System.ComponentModel.Win32Exception e)
        {
            MessageBox.Show("Unable to find Google Chrome...",
                "chrome.exe not found!", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

JavaScript getElementByID() not working

At the point you are calling your function, the rest of the page has not rendered and so the element is not in existence at that point. Try calling your function on window.onload maybe. Something like this:

<html>
<head>
    <title></title>
    <script type="text/javascript">
        window.onload = function(){
           var refButton = document.getElementById("btnButton");

            refButton.onclick = function() {
                alert('I am clicked!');
            }
        };
    </script>
</head>
<body>
    <form id="form1">
    <div>
        <input id="btnButton" type="button" value="Click me"/>
    </div>
    </form>
</body>
</html>

How to paste yanked text into the Vim command line

"I'd like to paste yanked text into Vim command line."

While the top voted answer is very complete, I prefer editing the command history.

In normal mode, type: q:. This will give you a list of recent commands, editable and searchable with normal vim commands. You'll start on a blank command line at the bottom.

For the exact thing that the article asks, pasting a yanked line (or yanked anything) into a command line, yank your text and then: q:p (get into command history edit mode, and then (p)ut your yanked text into a new command line. Edit at will, enter to execute.

To get out of command history mode, it's the opposite. In normal mode in command history, type: :q + enter

How to select an element with 2 classes

You can chain class selectors without a space between them:

.a.b {
     color: #666;
}

Note that, if it matters to you, IE6 treats .a.b as .b, so in that browser both div.a.b and div.b will have gray text. See this answer for a comparison between proper browsers and IE6.

SQL Server CASE .. WHEN .. IN statement

CASE AlarmEventTransactions.DeviceID should just be CASE.

You are mixing the 2 forms of the CASE expression.

Displaying Windows command prompt output and redirecting it to a file

I was able to find a solution/workaround of redirecting output to a file and then to the console:

dir > a.txt | type a.txt

where dir is the command which output needs to be redirected, a.txt a file where to store output.

nuget 'packages' element is not declared warning

Actually the correct answer to this is to just add the schema to your document, like so

<packages xmlns="http://schemas.microsoft.com/packaging/2010/07/nuspec.xsd">

...and you're done :)

If the XSD is not already cached and unavailable, you can add it as follows from the NuGet console

Install-Package NuGet.Manifest.Schema -Version 2.0.0

Once this is done, as noted in a comment below, you may want to move it from your current folder to the official schema folder that is found in

%VisualStudioPath%\Xml\Schemas

How do I put variable values into a text string in MATLAB?

You can use fprintf/sprintf with familiar C syntax. Maybe something like:

fprintf('x = %d, y = %d \n x+y=%d \n x*y=%d \n x/y=%f\n', x,y,d,e,f)

reading your comment, this is how you use your functions from the main program:

x = 2;
y = 2;
[d e f] = answer(x,y);
fprintf('%d + %d = %d\n', x,y,d)
fprintf('%d * %d = %d\n', x,y,e)
fprintf('%d / %d = %f\n', x,y,f)

Also for the answer() function, you can assign the output values to a vector instead of three distinct variables:

function result=answer(x,y)
result(1)=addxy(x,y);
result(2)=mxy(x,y);
result(3)=dxy(x,y);

and call it simply as:

out = answer(x,y);

How can I get the executing assembly version?

This should do:

Assembly assem = Assembly.GetExecutingAssembly();
AssemblyName aName = assem.GetName();
return aName.Version.ToString();

Checking whether a variable is an integer or not

if type(input('enter = '))==int:
     print 'Entered number is an Integer'
else:
     print 'Entered number isn't an Integer'

This'll work to check out whether number is an integer or not

What does servletcontext.getRealPath("/") mean and when should I use it

There is also a change between Java 7 and Java 8. Admittedly it involves the a deprecated call, but I had to add a "/" to get our program working! Here is the link discussing it Why does servletContext.getRealPath returns null on tomcat 8?

Batch file to perform start, run, %TEMP% and delete all

If you want to remove all the files in the %TEMP% folder you could just do this:

del %TEMP%\*.* /f /s /q

That will remove everything, any file with any extension (*.*) and do the same for all sub-folders (/s), without prompting you for anything (/q), it will just do it, including read only files (/f).

Hope this helps.

ViewBag, ViewData and TempData

void Keep()

Calling this method with in the current action ensures that all the items in TempData are not removed at the end of the current request.

    @model MyProject.Models.EmpModel;
    @{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "About";
    var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
    TempData.Keep(); // retains all strings values
    } 

void Keep(string key)

Calling this method with in the current action ensures that specific item in TempData is not removed at the end of the current request.

    @model MyProject.Models.EmpModel;
    @{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "About";
    var tempDataEmployeet = TempData["emp"] as Employee; //need typcasting
    TempData.Keep("emp"); // retains only "emp" string values
    } 

HTTP GET request in JavaScript?

In your widget's Info.plist file, don't forget to set your AllowNetworkAccess key to true.

IntelliJ: Never use wildcard imports

Shortcut doing this on Mac: Press command+Shift+A (Action) and type "class count to use import with *" Press Enter. Enter a higher number there like 999

How do I alter the position of a column in a PostgreSQL database table?

"Alter column position" in the PostgreSQL Wiki says:

PostgreSQL currently defines column order based on the attnum column of the pg_attribute table. The only way to change column order is either by recreating the table, or by adding columns and rotating data until you reach the desired layout.

That's pretty weak, but in their defense, in standard SQL, there is no solution for repositioning a column either. Database brands that support changing the ordinal position of a column are defining an extension to SQL syntax.

One other idea occurs to me: you can define a VIEW that specifies the order of columns how you like it, without changing the physical position of the column in the base table.

How to return a html page from a restful controller in spring boot?

You get only the name because you return only the name return "login";. It's @RestController and this controller returns data rather than a view; because of this, you get only content that you return from method.

If you want to show view with this name you need to use Spring MVC, see this example.

What does it mean by select 1 from table?

The result is 1 for every record in the table. __

Is there any kind of hash code function in JavaScript?

If you want to have unique values in a lookup object you can do something like this:

Creating a lookup object

var lookup = {};

Setting up the hashcode function

function getHashCode(obj) {
    var hashCode = '';
    if (typeof obj !== 'object')
        return hashCode + obj;
    for (var prop in obj) // No hasOwnProperty needed
        hashCode += prop + getHashCode(obj[prop]); // Add key + value to the result string
    return hashCode;
}

Object

var key = getHashCode({ 1: 3, 3: 7 });
// key = '1337'
lookup[key] = true;

Array

var key = getHashCode([1, 3, 3, 7]);
// key = '01132337'
lookup[key] = true;

Other types

var key = getHashCode('StackOverflow');
// key = 'StackOverflow'
lookup[key] = true;

Final result

{ 1337: true, 01132337: true, StackOverflow: true }

Do note that getHashCode doesn't return any value when the object or array is empty

getHashCode([{},{},{}]);
// '012'
getHashCode([[],[],[]]);
// '012'

This is similar to @ijmacd solution only getHashCode doesn't has the JSON dependency.

How do you make websites with Java?

Read the tutorial on Java Web applications.

Basically Web applications are a part of the Java EE standard. A lot of people only use the Web (servlets) part with additional frameworks thrown in, most notably Spring but also Struts, Seam and others.

All you need is an IDE like IntelliJ, Eclipse or Netbeans, the JDK, the Java EE download and a servlet container like Tomcat (or a full-blown application server like Glassfish or JBoss).

Here is a Tomcat tutorial.

Auto number column in SharePoint list

I had this issue with a custom list and while it's not possible to use the auto-generated ID column to create a calculated column, it is possible to use a workflow to do the heavy lifting.

I created a new workflow variable of type Number and set it to be the value of the ID column in the current item. Then it's simply a matter of calculating the custom column value and setting it - in my case I just needed the numbering to begin at 100,000.

enter image description here

How to use Sublime over SSH

Use FileZilla

This applies to Mac and Windows users (I use on Mac) . I've used several of the listed answers over the years and have found that FileZilla suits my needs well when editing files on a remote host that I have SSH access to. It's also quick to setup.

  • I config a new server connection
  • connect to the server
  • right click on the file I'd like to edit and select View/Edit.

This brings up my default editor (Sublime) but it will work with any editor you have installed.

  • Once I save the file, Filezilla automatically prompts me asking if I'd like to "Upload this file back to the server", I click "Yes" and then it's updated.

Comparing two NumPy arrays for equality, element-wise

Usually two arrays will have some small numeric errors,

You can use numpy.allclose(A,B), instead of (A==B).all(). This returns a bool True/False

Getting list of tables, and fields in each, in a database

Is this what you are looking for:

Using OBJECT CATALOG VIEWS

 SELECT T.name AS Table_Name ,
       C.name AS Column_Name ,
       P.name AS Data_Type ,
       P.max_length AS Size ,
       CAST(P.precision AS VARCHAR) + '/' + CAST(P.scale AS VARCHAR) AS Precision_Scale
FROM   sys.objects AS T
       JOIN sys.columns AS C ON T.object_id = C.object_id
       JOIN sys.types AS P ON C.system_type_id = P.system_type_id
WHERE  T.type_desc = 'USER_TABLE';

Using INFORMATION SCHEMA VIEWS

  SELECT TABLE_SCHEMA ,
       TABLE_NAME ,
       COLUMN_NAME ,
       ORDINAL_POSITION ,
       COLUMN_DEFAULT ,
       DATA_TYPE ,
       CHARACTER_MAXIMUM_LENGTH ,
       NUMERIC_PRECISION ,
       NUMERIC_PRECISION_RADIX ,
       NUMERIC_SCALE ,
       DATETIME_PRECISION
FROM   INFORMATION_SCHEMA.COLUMNS;

Reference : My Blog - http://dbalink.wordpress.com/2008/10/24/querying-the-object-catalog-and-information-schema-views/

How to iterate through a DataTable

You can also use linq extensions for DataSets:

var imagePaths = dt.AsEnumerble().Select(r => r.Field<string>("ImagePath");
foreach(string imgPath in imagePaths)
{
    TextBox1.Text = imgPath;
}

React: why child component doesn't update when prop changes

You should use setState function. If not, state won't save your change, no matter how you use forceUpdate.

Container {
    handleEvent= () => { // use arrow function
        //this.props.foo.bar = 123
        //You should use setState to set value like this:
        this.setState({foo: {bar: 123}});
    };

    render() {
        return <Child bar={this.state.foo.bar} />
    }
    Child {
        render() {
            return <div>{this.props.bar}</div>
        }
    }
}

Your code seems not valid. I can not test this code.

How do I change the data type for a column in MySQL?

Alter TABLE `tableName` MODIFY COLUMN `ColumnName` datatype(length);

Ex :

Alter TABLE `tbl_users` MODIFY COLUMN `dup` VARCHAR(120);

How to sort a dataframe by multiple column(s)

Just like the mechanical card sorters of long ago, first sort by the least significant key, then the next most significant, etc. No library required, works with any number of keys and any combination of ascending and descending keys.

 dd <- dd[order(dd$b, decreasing = FALSE),]

Now we're ready to do the most significant key. The sort is stable, and any ties in the most significant key have already been resolved.

dd <- dd[order(dd$z, decreasing = TRUE),]

This may not be the fastest, but it is certainly simple and reliable

Git is not working after macOS Update (xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools)

For me what worked is the following:

sudo xcode-select --reset

Then like in @High6's answer:

sudo xcodebuild -license

This will reveal a license which I assume is some Xcode license. Scroll to the bottom using space (or the mouse) then tap agree.

This is what worked for me on MacOS Mojave v 10.14.

JWT refresh token flow

Based in this implementation with Node.js of JWT with refresh token:

1) In this case they use a uid and it's not a JWT. When they refresh the token they send the refresh token and the user. If you implement it as a JWT, you don't need to send the user, because it would inside the JWT.

2) They implement this in a separated document (table). It has sense to me because a user can be logged in in different client applications and it could have a refresh token by app. If the user lose a device with one app installed, the refresh token of that device could be invalidated without affecting the other logged in devices.

3) In this implementation it response to the log in method with both, access token and refresh token. It seams correct to me.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

I got an error when I used

<git config --global http.proxy http://user:password@proxy_addr:port>

The error is that the config file cannot be identified as there is no such file. I changed the command to

<git config --system http.proxy http://user:password@proxy_addr:port>

I am running git on the Windows 7 command prompt.
The above command references the config file in GIT_HOME/etc/gitconfig.
The --global option does not.

PostgreSQL: How to make "case-insensitive" query

The most common approach is to either lowercase or uppercase the search string and the data. But there are two problems with that.

  1. It works in English, but not in all languages. (Maybe not even in most languages.) Not every lowercase letter has a corresponding uppercase letter; not every uppercase letter has a corresponding lowercase letter.
  2. Using functions like lower() and upper() will give you a sequential scan. It can't use indexes. On my test system, using lower() takes about 2000 times longer than a query that can use an index. (Test data has a little over 100k rows.)

There are at least three less frequently used solutions that might be more effective.

  1. Use the citext module, which mostly mimics the behavior of a case-insensitive data type. Having loaded that module, you can create a case-insensitive index by CREATE INDEX ON groups (name::citext);. (But see below.)
  2. Use a case-insensitive collation. This is set when you initialize a database. Using a case-insensitive collation means you can accept just about any format from client code, and you'll still return useful results. (It also means you can't do case-sensitive queries. Duh.)
  3. Create a functional index. Create a lowercase index by using CREATE INDEX ON groups (LOWER(name));. Having done that, you can take advantage of the index with queries like SELECT id FROM groups WHERE LOWER(name) = LOWER('ADMINISTRATOR');, or SELECT id FROM groups WHERE LOWER(name) = 'administrator'; You have to remember to use LOWER(), though.

The citext module doesn't provide a true case-insensitive data type. Instead, it behaves as if each string were lowercased. That is, it behaves as if you had called lower() on each string, as in number 3 above. The advantage is that programmers don't have to remember to lowercase strings. But you need to read the sections "String Comparison Behavior" and "Limitations" in the docs before you decide to use citext.

cannot import name patterns

Yes:

from django.conf.urls.defaults import ... # is for django 1.3
from django.conf.urls  import ...         # is for django 1.4

I met this problem too.

linux find regex

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

Reimport a module in python while interactive

This should work:

reload(my.module)

From the Python docs

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.

If running Python 3.4 and up, do import importlib, then do importlib.reload(nameOfModule).

Don't forget the caveats of using this method:

  • When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.

  • If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

  • If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

Delete all data in SQL Server database

/* Drop all non-system stored procs */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 ORDER BY [name])

WHILE @name is not null
BEGIN
    SELECT @SQL = 'DROP PROCEDURE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Procedure: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'P' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all views */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP VIEW [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped View: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'V' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all functions */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP FUNCTION [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Function: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] IN (N'FN', N'IF', N'TF', N'FS', N'FT') AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

/* Drop all Foreign Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)

WHILE @name is not null
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint IS NOT NULL
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint) +']'
        EXEC (@SQL)
        PRINT 'Dropped FK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'FOREIGN KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all Primary Key constraints */
DECLARE @name VARCHAR(128)
DECLARE @constraint VARCHAR(254)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)

WHILE @name IS NOT NULL
BEGIN
    SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    WHILE @constraint is not null
    BEGIN
        SELECT @SQL = 'ALTER TABLE [dbo].[' + RTRIM(@name) +'] DROP CONSTRAINT [' + RTRIM(@constraint)+']'
        EXEC (@SQL)
        PRINT 'Dropped PK Constraint: ' + @constraint + ' on ' + @name
        SELECT @constraint = (SELECT TOP 1 CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' AND CONSTRAINT_NAME <> @constraint AND TABLE_NAME = @name ORDER BY CONSTRAINT_NAME)
    END
SELECT @name = (SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS WHERE constraint_catalog=DB_NAME() AND CONSTRAINT_TYPE = 'PRIMARY KEY' ORDER BY TABLE_NAME)
END
GO

/* Drop all tables */
DECLARE @name VARCHAR(128)
DECLARE @SQL VARCHAR(254)

SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 ORDER BY [name])

WHILE @name IS NOT NULL
BEGIN
    SELECT @SQL = 'DROP TABLE [dbo].[' + RTRIM(@name) +']'
    EXEC (@SQL)
    PRINT 'Dropped Table: ' + @name
    SELECT @name = (SELECT TOP 1 [name] FROM sysobjects WHERE [type] = 'U' AND category = 0 AND [name] > @name ORDER BY [name])
END
GO

What is the strict aliasing rule?

Strict aliasing is not allowing different pointer types to the same data.

This article should help you understand the issue in full detail.

HTML5 Video Autoplay not working correctly

_x000D_
_x000D_
html {_x000D_
  padding: 20px 0;_x000D_
  background-color: #efefef;_x000D_
}_x000D_
_x000D_
body {_x000D_
  width: 400px;_x000D_
  padding: 40px;_x000D_
  margin: 0 auto;_x000D_
  background: #fff;_x000D_
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);_x000D_
}_x000D_
_x000D_
video {_x000D_
  width: 400px;_x000D_
  display: block;_x000D_
}
_x000D_
<video onloadeddata="this.play();this.muted=false;" poster="https://durian.blender.org/wp-content/themes/durian/images/void.png" playsinline loop muted controls>_x000D_
    <source src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4" />_x000D_
    Your browser does not support the video tag or the file format of this video._x000D_
</video>
_x000D_
_x000D_
_x000D_

Where is the .NET Framework 4.5 directory?

The official way to find out if you have 4.5 installed (and not 4.0) is in the registry keys :

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full

Relesae DWORD needs to be bigger than 378675 Here is the Microsoft doc for it

all the other answers of checking the minor version after 4.0.30319.xxxxx seem correct though (msbuild.exe -version , or properties of clr.dll), i just needed something documented (not a blog)

How do I remove the last comma from a string using PHP?

Try the below code:

$my_string = "'name', 'name2', 'name3',";
echo substr(trim($my_string), 0, -1);

Use this code to remove the last character of the string.

Random number c++ in some range

int random(int min, int max) //range : [min, max]
{
   static bool first = true;
   if (first) 
   {  
      srand( time(NULL) ); //seeding for the first time only!
      first = false;
   }
   return min + rand() % (( max + 1 ) - min);
}

mysql query order by multiple items

SELECT some_cols
FROM prefix_users
WHERE (some conditions)
ORDER BY pic_set DESC, last_activity;

What is the most elegant way to check if all values in a boolean array are true?

It depends how many times you're going to want to find this information, if more than once:

Set<Boolean> flags = new HashSet<Boolean>(myArray);
flags.contains(false);

Otherwise a short circuited loop:

for (i = 0; i < myArray.length; i++) {
  if (!myArray[i]) return false;
}
return true;

Google Maps API v3 marker with label

I can't guarantee it's the simplest, but I like MarkerWithLabel. As shown in the basic example, CSS styles define the label's appearance and options in the JavaScript define the content and placement.

 .labels {
   color: red;
   background-color: white;
   font-family: "Lucida Grande", "Arial", sans-serif;
   font-size: 10px;
   font-weight: bold;
   text-align: center;
   width: 60px;     
   border: 2px solid black;
   white-space: nowrap;
 }

JavaScript:

 var marker = new MarkerWithLabel({
   position: homeLatLng,
   draggable: true,
   map: map,
   labelContent: "$425K",
   labelAnchor: new google.maps.Point(22, 0),
   labelClass: "labels", // the CSS class for the label
   labelStyle: {opacity: 0.75}
 });

The only part that may be confusing is the labelAnchor. By default, the label's top left corner will line up to the marker pushpin's endpoint. Setting the labelAnchor's x-value to half the width defined in the CSS width property will center the label. You can make the label float above the marker pushpin with an anchor point like new google.maps.Point(22, 50).

In case access to the links above are blocked, I copied and pasted the packed source of MarkerWithLabel into this JSFiddle demo. I hope JSFiddle is allowed in China :|

How do you get the contextPath from JavaScript, the right way?

I think you can achieve what you are looking for by combining number 1 with calling a function like in number 3.

You don't want to execute scripts on page load and prefer to call a function later on? Fine, just create a function that returns the value you would have set in a variable:

function getContextPath() {
   return "<%=request.getContextPath()%>";
}

It's a function so it wont be executed until you actually call it, but it returns the value directly, without a need to do DOM traversals or tinkering with URLs.

At this point I agree with @BalusC to use EL:

function getContextPath() {
   return "${pageContext.request.contextPath}";
}

or depending on the version of JSP fallback to JSTL:

function getContextPath() {
   return "<c:out value="${pageContext.request.contextPath}" />";
}

This action could not be completed. Try Again (-22421)

When above problem exists and you have Two Factor Authentication enabled, just do the following:

  1. go to http://appleid.apple.com and then create your App-Specific Password

enter image description here

  1. Inside Application Loader login with your apple id and App Specific Password you just created.

  2. Upload your ipa to itunesconnect.

How to delete the last row of data of a pandas dataframe

Since index positioning in Python is 0-based, there won't actually be an element in index at the location corresponding to len(DF). You need that to be last_row = len(DF) - 1:

In [49]: dfrm
Out[49]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723
9  0.834706  0.002989  0.333436

[10 rows x 3 columns]

In [50]: dfrm.drop(dfrm.index[len(dfrm)-1])
Out[50]: 
          A         B         C
0  0.120064  0.785538  0.465853
1  0.431655  0.436866  0.640136
2  0.445904  0.311565  0.934073
3  0.981609  0.695210  0.911697
4  0.008632  0.629269  0.226454
5  0.577577  0.467475  0.510031
6  0.580909  0.232846  0.271254
7  0.696596  0.362825  0.556433
8  0.738912  0.932779  0.029723

[9 rows x 3 columns]

However, it's much simpler to just write DF[:-1].

Ignoring new fields on JSON objects using Jackson

In addition to 2 mechanisms already mentioned, there is also global feature that can be used to suppress all failures caused by unknown (unmapped) properties:

// jackson 1.9 and before
objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// or jackson 2.0
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

This is the default used in absence of annotations, and can be convenient fallback.

Scrollview vertical and horizontal in android

Option #1: You can come up with a new UI design that does not require simultaneous horizontal and vertical scrolling.

Option #2: You can obtain the source code to ScrollView and HorizontalScrollView, learn how the core Android team implemented those, and create your own BiDirectionalScrollView implementation.

Option #3: You can get rid of the dependencies that are requiring you to use the widget system and draw straight to the Canvas.

Option #4: If you stumble upon an open source application that seems to implement what you seek, look to see how they did it.

Use CSS to remove the space between images

Make them display: block in your CSS.

How can I fill a column with random numbers in SQL? I get the same value in every row

While I do love using CHECKSUM, I feel that a better way to go is using NEWID(), just because you don't have to go through a complicated math to generate simple numbers .

ROUND( 1000 *RAND(convert(varbinary, newid())), 0)

You can replace the 1000 with whichever number you want to set as the limit, and you can always use a plus sign to create a range, let's say you want a random number between 100 and 200, you can do something like :

100 + ROUND( 100 *RAND(convert(varbinary, newid())), 0)

Putting it together in your query :

UPDATE CattleProds 
SET SheepTherapy= ROUND( 1000 *RAND(convert(varbinary, newid())), 0)
WHERE SheepTherapy IS NULL

How to add item to the beginning of List<T>?

Use List<T>.Insert

While not relevant to your specific example, if performance is important also consider using LinkedList<T> because inserting an item to the start of a List<T> requires all items to be moved over. See When should I use a List vs a LinkedList.

How do I access nested HashMaps in Java?

I prefer creating a custom map that extends HashMap. Then just override get() to add extra logic so that if the map doesnt contain your key. It will a create a new instance of the nested map, add it, then return it.

public class KMap<K, V> extends HashMap<K, V> {

    public KMap() {
        super();
    }

    @Override
    public V get(Object key) {
        if (this.containsKey(key)) {
            return super.get(key);
        } else {
            Map<K, V> value = new KMap<K, V>();
            super.put((K)key, (V)value);
            return (V)value;
        }
    }
}

Now you can use it like so:

Map<Integer, Map<Integer, Map<String, Object>>> nestedMap = new KMap<Integer, Map<Integer, Map<String, Object>>>();

Map<String, Object> map = (Map<String, Object>) nestedMap.get(1).get(2);
Object obj= new Object();
map.put(someKey, obj);

NoClassDefFoundError - Eclipse and Android

please make sure your jar file is in the libs directory of your project in you are using newer ADT version with your eclipse.

Fastest JSON reader/writer for C++

rapidjson is a C++ JSON parser/generator designed to be fast and small memory footprint.

There is a performance comparison with YAJL and JsonCPP.


Update:

I created an open source project Native JSON benchmark, which evaluates 29 (and increasing) C/C++ JSON libraries, in terms of conformance and performance. This should be an useful reference.

ffmpeg - Converting MOV files to MP4

The command to just stream it to a new container (mp4) needed by some applications like Adobe Premiere Pro without encoding (fast) is:

ffmpeg -i input.mov -qscale 0 output.mp4

Alternative as mentioned in the comments, which re-encodes with best quaility (-qscale 0):

ffmpeg -i input.mov -q:v 0 output.mp4

How to declare a type as nullable in TypeScript?

All fields in JavaScript (and in TypeScript) can have the value null or undefined.

You can make the field optional which is different from nullable.

interface Employee1 {
    name: string;
    salary: number;
}

var a: Employee1 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee1 = { name: 'Bob' }; // Not OK, you must have 'salary'
var c: Employee1 = { name: 'Bob', salary: undefined }; // OK
var d: Employee1 = { name: null, salary: undefined }; // OK

// OK
class SomeEmployeeA implements Employee1 {
    public name = 'Bob';
    public salary = 40000;
}

// Not OK: Must have 'salary'
class SomeEmployeeB implements Employee1 {
    public name: string;
}

Compare with:

interface Employee2 {
    name: string;
    salary?: number;
}

var a: Employee2 = { name: 'Bob', salary: 40000 }; // OK
var b: Employee2 = { name: 'Bob' }; // OK
var c: Employee2 = { name: 'Bob', salary: undefined }; // OK
var d: Employee2 = { name: null, salary: 'bob' }; // Not OK, salary must be a number

// OK, but doesn't make too much sense
class SomeEmployeeA implements Employee2 {
    public name = 'Bob';
}

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

VBA general way for pulling data out of SAP

This all depends on what sort of access you have to your SAP system. An ABAP program that exports the data and/or an RFC that your macro can call to directly get the data or have SAP create the file is probably best.

However as a general rule people looking for this sort of answer are looking for an immediate solution that does not require their IT department to spend months customizing their SAP system.

In that case you probably want to use SAP GUI Scripting. SAP GUI scripting allows you to automate the Windows SAP GUI in much the same way as you automate Excel. In fact you can call the SAP GUI directly from an Excel macro. Read up more on it here. The SAP GUI has a macro recording tool much like Excel does. It records macros in VBScript which is nearly identical to Excel VBA and can usually be copied and pasted into an Excel macro directly.

Example Code

Here is a simple example based on a SAP system I have access to.

Public Sub SimpleSAPExport()
  Set SapGuiAuto  = GetObject("SAPGUI") 'Get the SAP GUI Scripting object
  Set SAPApp = SapGuiAuto.GetScriptingEngine 'Get the currently running SAP GUI 
  Set SAPCon = SAPApp.Children(0) 'Get the first system that is currently connected
  Set session = SAPCon.Children(0) 'Get the first session (window) on that connection

  'Start the transaction to view a table
  session.StartTransaction "SE16"

  'Select table T001
  session.findById("wnd[0]/usr/ctxtDATABROWSE-TABLENAME").Text = "T001"
  session.findById("wnd[0]/tbar[1]/btn[7]").Press

  'Set our selection criteria
  session.findById("wnd[0]/usr/txtMAX_SEL").text = "2"
  session.findById("wnd[0]/tbar[1]/btn[8]").press

  'Click the export to file button
  session.findById("wnd[0]/tbar[1]/btn[45]").press

  'Choose the export format
  session.findById("wnd[1]/usr/subSUBSCREEN_STEPLOOP:SAPLSPO5:0150/sub:SAPLSPO5:0150/radSPOPLI-SELFLAG[1,0]").select
  session.findById("wnd[1]/tbar[0]/btn[0]").press

  'Choose the export filename
  session.findById("wnd[1]/usr/ctxtDY_FILENAME").text = "test.txt"
  session.findById("wnd[1]/usr/ctxtDY_PATH").text = "C:\Temp\"

  'Export the file
  session.findById("wnd[1]/tbar[0]/btn[0]").press
End Sub

Script Recording

To help find the names of elements such aswnd[1]/tbar[0]/btn[0] you can use script recording. Click the customize local layout button, it probably looks a bit like this: Customize Local Layout
Then find the Script Recording and Playback menu item.
Script Recording and Playback
Within that the More button allows you to see/change the file that the VB Script is recorded to. The output format is a bit messy, it records things like selecting text, clicking inside a text field, etc.

Edit: Early and Late binding

The provided script should work if copied directly into a VBA macro. It uses late binding, the line Set SapGuiAuto = GetObject("SAPGUI") defines the SapGuiAuto object.

If however you want to use early binding so that your VBA editor might show the properties and methods of the objects you are using, you need to add a reference to sapfewse.ocx in the SAP GUI installation folder.

importing external ".txt" file in python

As you can't import a .txt file, I would suggest to read words this way.

list_ = open("world.txt").read().split()

Initializing ArrayList with some predefined values

import com.google.common.collect.Lists;

...


ArrayList<String> getSymbolsPresent = Lists.newArrayList("item 1", "item 2");

...

Unit testing click event in Angular

to check button call event first we need to spy on method which will be called after button click so our first line will be spyOn spy methode take two arguments 1) component name 2) method to be spy i.e: 'onSubmit' remember not use '()' only name required then we need to make object of button to be clicked now we have to trigger the event handler on which we will add click event then we expect our code to call the submit method once

it('should call onSubmit method',() => {
    spyOn(component, 'onSubmit');
    let submitButton: DebugElement = 
    fixture.debugElement.query(By.css('button[type=submit]'));
    fixture.detectChanges();
    submitButton.triggerEventHandler('click',null);
    fixture.detectChanges();
    expect(component.onSubmit).toHaveBeenCalledTimes(1);
});

Twitter Bootstrap - full width navbar

Just replace <div class="container"> with <div class="container-fluid">, which is the container with no margins on both sides.

I think this is the best solution because it avoids some useless overriding and makes use of built-in classes, it's clean.

Select all DIV text with single mouse click

UPDATE 2017:

To select the node's contents call:

window.getSelection().selectAllChildren(
    document.getElementById(id)
);

This works on all modern browsers including IE9+ (in standards mode).

Runnable Example:

_x000D_
_x000D_
function select(id) {_x000D_
  window.getSelection()_x000D_
    .selectAllChildren(_x000D_
      document.getElementById("target-div") _x000D_
    );_x000D_
}
_x000D_
#outer-div  { padding: 1rem; background-color: #fff0f0; }_x000D_
#target-div { padding: 1rem; background-color: #f0fff0; }_x000D_
button      { margin: 1rem; }
_x000D_
<div id="outer-div">_x000D_
  <div id="target-div">_x000D_
    Some content for the _x000D_
    <br>Target DIV_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<button onclick="select(id);">Click to SELECT Contents of #target-div</button>
_x000D_
_x000D_
_x000D_


The original answer below is obsolete since window.getSelection().addRange(range); has been deprecated

Original Answer:

All of the examples above use:

    var range = document.createRange();
    range.selectNode( ... );

but the problem with that is that it selects the Node itself including the DIV tag etc.

To select the Node's text as per the OP question you need to call instead:

    range.selectNodeContents( ... )

So the full snippet would be:

    function selectText( containerid ) {

        var node = document.getElementById( containerid );

        if ( document.selection ) {
            var range = document.body.createTextRange();
            range.moveToElementText( node  );
            range.select();
        } else if ( window.getSelection ) {
            var range = document.createRange();
            range.selectNodeContents( node );
            window.getSelection().removeAllRanges();
            window.getSelection().addRange( range );
        }
    }

Why can't I reference my class library?

Another possible fix that just worked for me:

If you have Assembly A, which references Assembly B, both of which reference a non-project (external) assembly X, and Assembly B's code will not recognize that you have referenced X, then try the following steps in order:

  • Drop reference to X from BOTH A and B
  • Recreate reference to X in B
  • Recreate reference to X in A

Apparently, VS will not recognize a reference to an external assembly in a project that is a dependency of another project that already references the external. By setting up the references again from the ground up, you overcome this. It's just very odd.

jquery click event not firing?

You need to prevent the default event (following the link), otherwise your link will load a new page:

    $(document).ready(function(){
        $('.play_navigation a').click(function(e){
            e.preventDefault();
            console.log("this is the click");
        });
    });

As pointed out in comments, if your link has no href, then it's not a link, use something else.

Not working? Your code is A MESS! and ready() events everywhere... clean it, put all your scripts in ONE ready event and then try again, it will very likely sort things out.

How to reset all checkboxes using jQuery or pure JS?

The above answer did not work for me -

The following worked

$('input[type=checkbox]').each(function() 
{ 
        this.checked = false; 
}); 

This makes sure all the checkboxes are unchecked.

Which comment style should I use in batch files?

After I realized that I could use label :: to make comments and comment out code REM just looked plain ugly to me. As has been mentioned the double-colon can cause problems when used inside () blocked code, but I've discovered a work-around by alternating between the labels :: and :space

:: This, of course, does
:: not cause errors.

(
  :: But
   : neither
  :: does
   : this.
)

It's not ugly like REM, and actually adds a little style to your code.

So outside of code blocks I use :: and inside them I alternate between :: and :.

By the way, for large hunks of comments, like in the header of your batch file, you can avoid special commands and characters completely by simply gotoing over your comments. This let's you use any method or style of markup you want, despite that fact that if CMD ever actually tried to processes those lines it'd throw a hissy.

@echo off
goto :TopOfCode

=======================================================================
COOLCODE.BAT

Useage:
  COOLCODE [/?] | [ [/a][/c:[##][a][b][c]] INPUTFILE OUTPUTFILE ]

Switches:
       /?    - This menu
       /a    - Some option
       /c:## - Where ## is which line number to begin the processing at.
         :a  - Some optional method of processing
         :b  - A third option for processing
         :c  - A forth option
  INPUTFILE  - The file to process.
  OUTPUTFILE - Store results here.

 Notes:
   Bla bla bla.

:TopOfCode
CODE
.
.
.

Use what ever notation you wish *'s, @'s etc.

C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H

Just used the Nathan's solution and it works fine. I needed to convert ISO-8859-1 to Unicode:

string isocontent = Encoding.GetEncoding("ISO-8859-1").GetString(fileContent, 0, fileContent.Length);
byte[] isobytes = Encoding.GetEncoding("ISO-8859-1").GetBytes(isocontent);
byte[] ubytes = Encoding.Convert(Encoding.GetEncoding("ISO-8859-1"), Encoding.Unicode, isobytes);
return Encoding.Unicode.GetString(ubytes, 0, ubytes.Length);

How to move an element into another element?

You may want to use the appendTo function (which adds to the end of the element):

$("#source").appendTo("#destination");

Alternatively you could use the prependTo function (which adds to the beginning of the element):

$("#source").prependTo("#destination");

Example:

_x000D_
_x000D_
$("#appendTo").click(function() {_x000D_
  $("#moveMeIntoMain").appendTo($("#main"));_x000D_
});_x000D_
$("#prependTo").click(function() {_x000D_
  $("#moveMeIntoMain").prependTo($("#main"));_x000D_
});
_x000D_
#main {_x000D_
  border: 2px solid blue;_x000D_
  min-height: 100px;_x000D_
}_x000D_
_x000D_
.moveMeIntoMain {_x000D_
  border: 1px solid red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="main">main</div>_x000D_
<div id="moveMeIntoMain" class="moveMeIntoMain">move me to main</div>_x000D_
_x000D_
<button id="appendTo">appendTo main</button>_x000D_
<button id="prependTo">prependTo main</button>
_x000D_
_x000D_
_x000D_

How do I change data-type of pandas data frame to string with a defined format?

I'm unable to reproduce your problem but have you tried converting it to an integer first?

image_name_data['id'] = image_name_data['id'].astype(int).astype('str')

Then, regarding your more general question you could use map (as in this answer). In your case:

image_name_data['id'] = image_name_data['id'].map('{:.0f}'.format)

Using an image caption in Markdown Jekyll

Andrew's @andrew-wei answer works great. You can also chain a few together, depending on what you are trying to do. This, for example, gets you an image with alt, title and caption with a line break and bold and italics in different parts of the caption:

img + br + strong {margin-top: 5px; margin-bottom: 7px; font-style:italic; font-size: 12px; }
img + br + strong + em {margin-top: 5px; margin-bottom: 7px; font-size: 12px; font-style:italic;}

With the following <img> markdown:

![description](https://img.jpg "description")
***Image:*** *description*

Can't open config file: /usr/local/ssl/openssl.cnf on Windows

SOLUTION!

just set -config parameter location correctly, i.e :

openssl ....................  -config C:\bin\apache\apache2.4.9\conf\openssl.cnf

How can I define a composite primary key in SQL?

In Oracle database we can achieve like this.

CREATE TABLE Student(
  StudentID Number(38, 0) not null,
  DepartmentID Number(38, 0) not null,
  PRIMARY KEY (StudentID, DepartmentID)
);

Changing tab bar item image and text color iOS

Swift 5:

let homeTab = UITabBarItem(title: "Home", image: UIImage(named: "YOUR_IMAGE_NAME_FROM_ASSETS")?.withRenderingMode(UIImage.RenderingMode.alwaysOriginal), tag: 1)

How to visualize an XML schema?

Visual Studio 2013 has a pretty cool visualizer built in.

File -> Open -> File pick your .xsd and then drag elements from XML Schema Explorer onto the designer surface.