Programs & Examples On #Simplexmlrpcserver

What is the current choice for doing RPC in Python?

There are some attempts at making SOAP work with python, but I haven't tested it much so I can't say if it is good or not.

SOAPy is one example.

How to use ng-repeat without an html element

for a solution that really works

html

<remove  ng-repeat-start="itemGroup in Groups" ></remove>
   html stuff in here including inner repeating loops if you want
<remove  ng-repeat-end></remove>

add an angular.js directive

//remove directive
(function(){
    var remove = function(){

        return {    
            restrict: "E",
            replace: true,
            link: function(scope, element, attrs, controller){
                element.replaceWith('<!--removed element-->');
            }
        };

    };
    var module = angular.module("app" );
    module.directive('remove', [remove]);
}());

for a brief explanation,

ng-repeat binds itself to the <remove> element and loops as it should, and because we have used ng-repeat-start / ng-repeat-end it loops a block of html not just an element.

then the custom remove directive places the <remove> start and finish elements with <!--removed element-->

Getting index value on razor foreach

In case you want to count the references from your model( ie: Client has Address as reference so you wanna count how many address would exists for a client) in a foreach loop at your view such as:

 @foreach (var item in Model)
                        {
                            <tr>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DtCadastro)
                                </td>

                                <td style="width:50%">
                                    @Html.DisplayFor(modelItem => item.DsLembrete)
                                </td>
                                <td>
                                    @Html.DisplayFor(modelItem => item.DtLembrete)
                                </td>
                                <td>
                                    @{ 
                                        var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();
                                    }
                                    <button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>
                                    <button class="btn-link associar" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Create/@item.IdLembrete"><i class="fas fa-plus"></i></button>
                                </td>
                                <td class="text-right">
                                    <button class="btn-link delete" data-id="@item.IdLembrete" data-path="/Lembretes/Delete/@item.IdLembrete">Excluir</button>
                                </td>
                            </tr>
                        }

do as coded:

@{ var contador = item.LembreteEnvolvido.Where(w => w.IdLembrete == item.IdLembrete).Count();}

and use it like this:

<button class="btn-link associado" data-id="@item.IdLembrete" data-path="/LembreteEnvolvido/Index/@item.IdLembrete"><i class="fas fa-search"></i> @contador</button>

ps: don't forget to add INCLUDE to that reference at you DbContext inside, for example, your Index action controller, in case this is an IEnumerable model.

How to make a edittext box in a dialog

Use Activtiy Context

Replace this

  final EditText input = new EditText(this);

By

  final EditText input = new EditText(MainActivity.this);  
  LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        LinearLayout.LayoutParams.MATCH_PARENT,
                        LinearLayout.LayoutParams.MATCH_PARENT);
  input.setLayoutParams(lp);
  alertDialog.setView(input); // uncomment this line

Iterate through every file in one directory

I like this one, that hasn't been mentioned above.

require 'pathname'

Pathname.new('/my/dir').children.each do |path|
    puts path
end

The benefit is that you get a Pathname object instead of a string, that you can do useful stuff with and traverse further.

Spring MVC: Error 400 The request sent by the client was syntactically incorrect

Please keep your

<form method="POST" action="XYZ">

@RequestMapping(value="/XYZ", method=RequestMethod.POST)
    public void handleSave(@RequestParam String action){

Your form action attribute value must match to value of @RequestMapping, So that Spring MVC can resolve it.

Also, as you told it is giving 404 after changing, for this, can you please check whether control is entering inside handleSave() method.

I think, as you are not returning any thing from handleSave() method, you have to look at it.

if it still not work, can you please post your spring logs.

Also, make sure that your request should come like

/PORTAL/save

if there is anything between like PORTAL/jsp/save the mention in @RequestMapping(value="/jsp/save")

What does Visual Studio mean by normalize inconsistent line endings?

It means that, for example, some of your lines of text with a <Carriage Return><Linefeed> (the Windows standard), and some end with just a <Linefeed> (the Unix standard).

If you click 'yes' these the end-of-lines in your source file will be converted to have all the same format.

This won't make any difference to the compiler (because end-of-lines count as mere whitespace), but it might make some difference to other tools (e.g. the 'diff' on your version control system).

Removing space from dataframe columns in pandas

  • To remove white spaces:

1) To remove white space everywhere:

df.columns = df.columns.str.replace(' ', '')

2) To remove white space at the beginning of string:

df.columns = df.columns.str.lstrip()

3) To remove white space at the end of string:

df.columns = df.columns.str.rstrip()

4) To remove white space at both ends:

df.columns = df.columns.str.strip()
  • To replace white spaces with other characters (underscore for instance):

5) To replace white space everywhere

df.columns = df.columns.str.replace(' ', '_')

6) To replace white space at the beginning:

df.columns = df.columns.str.replace('^ +', '_')

7) To replace white space at the end:

df.columns = df.columns.str.replace(' +$', '_')

8) To replace white space at both ends:

df.columns = df.columns.str.replace('^ +| +$', '_')

All above applies to a specific column as well, assume you have a column named col, then just do:

df[col] = df[col].str.strip()  # or .replace as above

Can I dynamically add HTML within a div tag from C# on load event?

Use asp:Panel for that. It translates into a div.

json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190)

This error can also show up if there are parts in your string that json.loads() does not recognize. An in this example string, an error will be raised at character 27 (char 27).

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

My solution to this would be to use the string.replace() to convert these items to a string:

import json

string = """[{"Item1": "One", "Item2": False}, {"Item3": "Three"}]"""

string = string.replace("False", '"False"')

dict_list = json.loads(string)

Get random sample from list while maintaining ordering of items?

Simple-to-code O(N + K*log(K)) way

Take a random sample without replacement of the indices, sort the indices, and take them from the original.

indices = random.sample(range(len(myList)), K)
[myList[i] for i in sorted(indices)]

Or more concisely:

[x[1] for x in sorted(random.sample(enumerate(myList),K))]

Optimized O(N)-time, O(1)-auxiliary-space way

You can alternatively use a math trick and iteratively go through myList from left to right, picking numbers with dynamically-changing probability (N-numbersPicked)/(total-numbersVisited). The advantage of this approach is that it's an O(N) algorithm since it doesn't involve sorting!

from __future__ import division

def orderedSampleWithoutReplacement(seq, k):
    if not 0<=k<=len(seq):
        raise ValueError('Required that 0 <= sample_size <= population_size')

    numbersPicked = 0
    for i,number in enumerate(seq):
        prob = (k-numbersPicked)/(len(seq)-i)
        if random.random() < prob:
            yield number
            numbersPicked += 1

Proof of concept and test that probabilities are correct:

Simulated with 1 trillion pseudorandom samples over the course of 5 hours:

>>> Counter(
        tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
        for _ in range(10**9)
    )
Counter({
    (0, 3): 166680161, 
    (1, 2): 166672608, 
    (0, 2): 166669915, 
    (2, 3): 166667390, 
    (1, 3): 166660630, 
    (0, 1): 166649296
})

Probabilities diverge from true probabilities by less a factor of 1.0001. Running this test again resulted in a different order meaning it isn't biased towards one ordering. Running the test with fewer samples for [0,1,2,3,4], k=3 and [0,1,2,3,4,5], k=4 had similar results.

edit: Not sure why people are voting up wrong comments or afraid to upvote... NO, there is nothing wrong with this method. =)

(Also a useful note from user tegan in the comments: If this is python2, you will want to use xrange, as usual, if you really care about extra space.)

edit: Proof: Considering the uniform distribution (without replacement) of picking a subset of k out of a population seq of size len(seq), we can consider a partition at an arbitrary point i into 'left' (0,1,...,i-1) and 'right' (i,i+1,...,len(seq)). Given that we picked numbersPicked from the left known subset, the remaining must come from the same uniform distribution on the right unknown subset, though the parameters are now different. In particular, the probability that seq[i] contains a chosen element is #remainingToChoose/#remainingToChooseFrom, or (k-numbersPicked)/(len(seq)-i), so we simulate that and recurse on the result. (This must terminate since if #remainingToChoose == #remainingToChooseFrom, then all remaining probabilities are 1.) This is similar to a probability tree that happens to be dynamically generated. Basically you can simulate a uniform probability distribution by conditioning on prior choices (as you grow the probability tree, you pick the probability of the current branch such that it is aposteriori the same as prior leaves, i.e. conditioned on prior choices; this will work because this probability is uniformly exactly N/k).

edit: Timothy Shields mentions Reservoir Sampling, which is the generalization of this method when len(seq) is unknown (such as with a generator expression). Specifically the one noted as "algorithm R" is O(N) and O(1) space if done in-place; it involves taking the first N element and slowly replacing them (a hint at an inductive proof is also given). There are also useful distributed variants and miscellaneous variants of reservoir sampling to be found on the wikipedia page.

edit: Here's another way to code it below in a more semantically obvious manner.

from __future__ import division
import random

def orderedSampleWithoutReplacement(seq, sampleSize):
    totalElems = len(seq)
    if not 0<=sampleSize<=totalElems:
        raise ValueError('Required that 0 <= sample_size <= population_size')

    picksRemaining = sampleSize
    for elemsSeen,element in enumerate(seq):
        elemsRemaining = totalElems - elemsSeen
        prob = picksRemaining/elemsRemaining
        if random.random() < prob:
            yield element
            picksRemaining -= 1

from collections import Counter         
Counter(
    tuple(orderedSampleWithoutReplacement([0,1,2,3], 2))
    for _ in range(10**5)

)

Communication between multiple docker-compose projects

version: '2'
services:
  bot:
    build: .
    volumes:
      - '.:/home/node'
      - /home/node/node_modules
    networks:
      - my-rede
    mem_limit: 100m
    memswap_limit: 100m
    cpu_quota: 25000
    container_name: 236948199393329152_585042339404185600_bot
    command: node index.js
    environment:
      NODE_ENV: production
networks:
  my-rede:
    external:
      name: name_rede_externa

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

Make sure that both the chromedriver and google-chrome executable have execute permissions

sudo chmod -x "/usr/bin/chromedriver"

sudo chmod -x "/usr/bin/google-chrome"

How to get File Created Date and Modified Date

File.GetLastWriteTime Method

Returns the date and time the specified file or directory was last written to.

string path = @"c:\Temp\MyTest.txt";
DateTime dt = File.GetLastWriteTime(path);

For create time File.GetCreationTime Method

DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
Console.WriteLine("file created: " + fileCreatedDate);

Removing all line breaks and adding them after certain text

I have achieved this with following
Edit > Blank Operations > Remove Unnecessary Blank and EOL

How can I calculate divide and modulo for integers in C#?

Before asking questions of this kind, please check MSDN documentation.

When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2. To determine the remainder of 7 / 3, use the remainder operator (%).

int a = 5;
int b = 3;

int div = a / b; //quotient is 1
int mod = a % b; //remainder is 2

PKIX path building failed: unable to find valid certification path to requested target

For me, I had encountered this error when invoking a webservice call, make sure that the site has a valid ssl, i.e the logo on the side of the url is checked, otherwise need to add the certificate to trusted key store in your machine

How do you create a Marker with a custom icon for google maps API v3?

marker = new google.maps.Marker({
    map:map,
    // draggable:true,
    // animation: google.maps.Animation.DROP,
    position: new google.maps.LatLng(59.32522, 18.07002),
    icon: 'http://cdn.com/my-custom-icon.png' // null = default icon
  });

JAVA_HOME does not point to the JDK

It looks like you are currently pointing JAVA_HOME to /usr/lib/jvm/java-6-openjdk/jre which appears to be a JRE not a JDK. Try setting JAVA_HOME to /usr/lib/jvm/java-6-openjdk.

The JRE does not contain the Java compiler, only the JDK (Java Developer Kit) contains it.

DateTime and CultureInfo

InvariantCulture is similar to en-US, so i would use the correct CultureInfo instead:

var dutchCulture = CultureInfo.CreateSpecificCulture("nl-NL");
var date1 = DateTime.ParseExact(date, "dd.MM.yyyy HH:mm:ss", dutchCulture);

Demo

And what about when the culture is en-us? Will I have to code for every single language there is out there?

If you want to know how to display the date in another culture like "en-us", you can use date1.ToString(CultureInfo.CreateSpecificCulture("en-US")).

Expected response code 220 but got code "", with message "" in Laravel

In my case I had to set the

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=465           <<<<<<<------------------------- (FOCUS THIS)
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>

MAIL_ENCRYPTION= ssl    <<<<<<<------------------------- (FOCUS THIS)

to work it.. Might be useful. Rest of the code was same as @Sid said.

And I think that editing both environment file and app/config/mail.php is unnecessary. Just use one method.

Edit as per the comment by @Zan

If you need to enable tls protection use following settings.

MAIL_PORT=587
MAIL_ENCRYPTION= tls  

See here for some other gmail settings

SELECT *, COUNT(*) in SQLite

count(*) is an aggregate function. Aggregate functions need to be grouped for a meaningful results. You can read: count columns group by

How to convert datatype:object to float64 in python?

Or you can use regular expression to handle multiple items as the general case of this issue,

df['2nd'] = pd.to_numeric(df['2nd'].str.replace(r'[,.%]','')) 
df['CTR'] = pd.to_numeric(df['CTR'].str.replace(r'[^\d%]',''))

Add space between cells (td) using css

table { 
  border-spacing: 10px; 
} 

This worked for me once I removed

border-collapse: separate;

from my table tag.

Recursive Lock (Mutex) vs Non-Recursive Lock (Mutex)

The difference between a recursive and non-recursive mutex has to do with ownership. In the case of a recursive mutex, the kernel has to keep track of the thread who actually obtained the mutex the first time around so that it can detect the difference between recursion vs. a different thread that should block instead. As another answer pointed out, there is a question of the additional overhead of this both in terms of memory to store this context and also the cycles required for maintaining it.

However, there are other considerations at play here too.

Because the recursive mutex has a sense of ownership, the thread that grabs the mutex must be the same thread that releases the mutex. In the case of non-recursive mutexes, there is no sense of ownership and any thread can usually release the mutex no matter which thread originally took the mutex. In many cases, this type of "mutex" is really more of a semaphore action, where you are not necessarily using the mutex as an exclusion device but use it as synchronization or signaling device between two or more threads.

Another property that comes with a sense of ownership in a mutex is the ability to support priority inheritance. Because the kernel can track the thread owning the mutex and also the identity of all the blocker(s), in a priority threaded system it becomes possible to escalate the priority of the thread that currently owns the mutex to the priority of the highest priority thread that is currently blocking on the mutex. This inheritance prevents the problem of priority inversion that can occur in such cases. (Note that not all systems support priority inheritance on such mutexes, but it is another feature that becomes possible via the notion of ownership).

If you refer to classic VxWorks RTOS kernel, they define three mechanisms:

  • mutex - supports recursion, and optionally priority inheritance. This mechanism is commonly used to protect critical sections of data in a coherent manner.
  • binary semaphore - no recursion, no inheritance, simple exclusion, taker and giver does not have to be same thread, broadcast release available. This mechanism can be used to protect critical sections, but is also particularly useful for coherent signalling or synchronization between threads.
  • counting semaphore - no recursion or inheritance, acts as a coherent resource counter from any desired initial count, threads only block where net count against the resource is zero.

Again, this varies somewhat by platform - especially what they call these things, but this should be representative of the concepts and various mechanisms at play.

Java: Local variable mi defined in an enclosing scope must be final or effectively final

The error means you cannot use the local variable mi inside an inner class.


To use a variable inside an inner class you must declare it final. As long as mi is the counter of the loop and final variables cannot be assigned, you must create a workaround to get mi value in a final variable that can be accessed inside inner class:

final Integer innerMi = new Integer(mi);

So your code will be like this:

for (int mi=0; mi<colors.length; mi++){

    String pos = Character.toUpperCase(colors[mi].charAt(0)) + colors[mi].substring(1);
    JMenuItem Jmi =new JMenuItem(pos);
    Jmi.setIcon(new IconA(colors[mi]));

    // workaround:
    final Integer innerMi = new Integer(mi);

    Jmi.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JMenuItem item = (JMenuItem) e.getSource();
                IconA icon = (IconA) item.getIcon();
                // HERE YOU USE THE FINAL innerMi variable and no errors!!!
                Color kolorIkony = getColour(colors[innerMi]); 
                textArea.setForeground(kolorIkony);
            }
        });

        mnForeground.add(Jmi);
    }
}

How to change a text with jQuery

$('#toptitle').html('New world');

or

$('#toptitle').text('New world');

Allowing Untrusted SSL Certificates with HttpClient

If you are using System.Net.Http.HttpClient I believe correct pattern is

var handler = new HttpClientHandler() 
{ 
    ServerCertificateCustomValidationCallback = HttpClientHandler.DangerousAcceptAnyServerCertificateValidator
};

var http = new HttpClient(handler);
var res = http.GetAsync(url);

returning a Void object

There is no generic type which will tell the compiler that a method returns nothing.

I believe the convention is to use Object when inheriting as a type parameter

OR

Propagate the type parameter up and then let users of your class instantiate using Object and assigning the object to a variable typed using a type-wildcard ?:

interface B<E>{ E method(); }

class A<T> implements B<T>{

    public T method(){
        // do something
        return null;
    }
}

A<?> a = new A<Object>();

how to compare two string dates in javascript?

Directly parsing a date string that is not in yyyy-mm-dd format, like in the accepted answer does not work. The answer by vitran does work but has some JQuery mixed in so I reworked it a bit.

// Takes two strings as input, format is dd/mm/yyyy
// returns true if d1 is smaller than or equal to d2

function compareDates(d1, d2){
var parts =d1.split('/');
var d1 = Number(parts[2] + parts[1] + parts[0]);
parts = d2.split('/');
var d2 = Number(parts[2] + parts[1] + parts[0]);
return d1 <= d2;
}

P.S. would have commented directly to vitran's post but I don't have the rep to do that.

Inserting HTML into a div

Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:

$('#yourDivName').html('yourtHTML');

You may also consider using:

$('#yourDivName').append('yourtHTML');

This will add your gallery as the last item in the selected div. Or:

$('#yourDivName').prepend('yourtHTML');

This will add it as the first item in the selected div.

See the JQuery docs for these functions:

How to automatically generate N "distinct" colors?

Like Uri Cohen's answer, but is a generator instead. Will start by using colors far apart. Deterministic.

Sample, left colors first: sample

#!/usr/bin/env python3.5
from typing import Iterable, Tuple
import colorsys
import itertools
from fractions import Fraction
from pprint import pprint

def zenos_dichotomy() -> Iterable[Fraction]:
    """
    http://en.wikipedia.org/wiki/1/2_%2B_1/4_%2B_1/8_%2B_1/16_%2B_%C2%B7_%C2%B7_%C2%B7
    """
    for k in itertools.count():
        yield Fraction(1,2**k)

def fracs() -> Iterable[Fraction]:
    """
    [Fraction(0, 1), Fraction(1, 2), Fraction(1, 4), Fraction(3, 4), Fraction(1, 8), Fraction(3, 8), Fraction(5, 8), Fraction(7, 8), Fraction(1, 16), Fraction(3, 16), ...]
    [0.0, 0.5, 0.25, 0.75, 0.125, 0.375, 0.625, 0.875, 0.0625, 0.1875, ...]
    """
    yield Fraction(0)
    for k in zenos_dichotomy():
        i = k.denominator # [1,2,4,8,16,...]
        for j in range(1,i,2):
            yield Fraction(j,i)

# can be used for the v in hsv to map linear values 0..1 to something that looks equidistant
# bias = lambda x: (math.sqrt(x/3)/Fraction(2,3)+Fraction(1,3))/Fraction(6,5)

HSVTuple = Tuple[Fraction, Fraction, Fraction]
RGBTuple = Tuple[float, float, float]

def hue_to_tones(h: Fraction) -> Iterable[HSVTuple]:
    for s in [Fraction(6,10)]: # optionally use range
        for v in [Fraction(8,10),Fraction(5,10)]: # could use range too
            yield (h, s, v) # use bias for v here if you use range

def hsv_to_rgb(x: HSVTuple) -> RGBTuple:
    return colorsys.hsv_to_rgb(*map(float, x))

flatten = itertools.chain.from_iterable

def hsvs() -> Iterable[HSVTuple]:
    return flatten(map(hue_to_tones, fracs()))

def rgbs() -> Iterable[RGBTuple]:
    return map(hsv_to_rgb, hsvs())

def rgb_to_css(x: RGBTuple) -> str:
    uint8tuple = map(lambda y: int(y*255), x)
    return "rgb({},{},{})".format(*uint8tuple)

def css_colors() -> Iterable[str]:
    return map(rgb_to_css, rgbs())

if __name__ == "__main__":
    # sample 100 colors in css format
    sample_colors = list(itertools.islice(css_colors(), 100))
    pprint(sample_colors)

Convert varchar to uniqueidentifier in SQL Server

SELECT CONVERT(uniqueidentifier,STUFF(STUFF(STUFF(STUFF('B33D42A3AC5A4D4C81DD72F3D5C49025',9,0,'-'),14,0,'-'),19,0,'-'),24,0,'-'))

Java String declaration

String str = new String("SOME")

always create a new object on the heap

String str="SOME" 

uses the String pool

Try this small example:

        String s1 = new String("hello");
        String s2 = "hello";
        String s3 = "hello";

        System.err.println(s1 == s2);
        System.err.println(s2 == s3);

To avoid creating unnecesary objects on the heap use the second form.

Prevent overwriting a file using cmd if exist

As in the answer of Escobar Ceaser, I suggest to use quotes arround the whole path. It's the common way to wrap the whole path in "", not only separate directory names within the path.

I had a similar issue that it didn't work for me. But it was no option to use "" within the path for separate directory names because the path contained environment variables, which theirself cover more than one directory hierarchies. The conclusion was that I missed the space between the closing " and the (

The correct version, with the space before the bracket, would be

If NOT exist "C:\Documents and Settings\John\Start Menu\Programs\Software Folder" (
 start "\\filer\repo\lab\software\myapp\setup.exe"
 pause
) 

Storing image in database directly or as base64 data?

Just want to give one example why we decided to store image in DB not files or CDN, it is storing images of signatures.

We have tried to do so via CDN, cloud storage, files, and finally decided to store in DB and happy about the decision as it was proven us right in our subsequent events when we moved, upgraded our scripts and migrated the sites serveral times.

For my case, we wanted the signatures to be with the records that belong to the author of documents.

Storing in files format risks missing them or deleted by accident.

We store it as a blob binary format in MySQL, and later as based64 encoded image in a text field. The decision to change to based64 was due to smaller size as result for some reason, and faster loading. Blob was slowing down the page load for some reason.

In our case, this solution to store signature images in DB, (whether as blob or based64), was driven by:

  1. Most signature images are very small.
  2. We don't need to index the signature images stored in DB.
  3. Index is done on the primary key.
  4. We may have to move or switch servers, moving physical images files to different servers, may cause the images not found due to links change.
  5. it is embarrassed to ask the author to re-sign their signatures.
  6. it is more secured saving in the DB as compared to exposing it as files which can be downloaded if security is compromised. Storing in DB allows us better control over its access.
  7. any future migrations, change of web design, hosting, servers, we have zero worries about reconcilating the signature file names against the physical files, it is all in the DB!

AC

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

PHP Include for HTML?

You can use php code in files with extension .php and only there (iff other is not defined in your server settings).

Just rename your file *.html to *.php


If you want to allow php code processing in files of different format, you have two options to do that:

1) Modifying httpd.conf to allow this for all projects on your server, by adding:

AddHandler application/x-httpd-php .htm .html

2) Creating .htaccess file in your separate project top directory with:

<Files />
    AddType application/x-httpd-php .html
</Files>

For second option you need to allow use of .htaccess files in your httpd.conf, by adding the following settings:

AllowOverride All
AccessFileName .htaccess

*that is correct for Apache HTTP Server

Oracle PL/SQL - How to create a simple array variable?

You can use VARRAY for a fixed-size array:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t('Matt', 'Joanne', 'Robert');
begin
   for i in 1..array.count loop
       dbms_output.put_line(array(i));
   end loop;
end;

Or TABLE for an unbounded array:

...
   type array_t is table of varchar2(10);
...

The word "table" here has nothing to do with database tables, confusingly. Both methods create in-memory arrays.

With either of these you need to both initialise and extend the collection before adding elements:

declare
   type array_t is varray(3) of varchar2(10);
   array array_t := array_t(); -- Initialise it
begin
   for i in 1..3 loop
      array.extend(); -- Extend it
      array(i) := 'x';
   end loop;
end;

The first index is 1 not 0.

Getting Current time to display in Label. VB.net

There are several problems here:

  • Your assignment is the wrong way round; you're trying to assign a value to DateTime.Now instead of Start
  • DateTime.Now is a value of type DateTime, not Integer, so the assignment wouldn't work anyway
  • There's no need to have the Start variable anyway; it's doing no good
  • total.Text is a property of type String - not DateTime or Integer

(Some of these would only show up at execution time unless you have Option Strict on, which you really should.)

You should use:

total.Text = DateTime.Now.ToString()

... possibly specifying a culture and/or format specifier if you want the result in a particular format.

How can I parse a time string containing milliseconds in it with python?

To give the code that nstehr's answer refers to (from its source):

def timeparse(t, format):
    """Parse a time string that might contain fractions of a second.

    Fractional seconds are supported using a fragile, miserable hack.
    Given a time string like '02:03:04.234234' and a format string of
    '%H:%M:%S', time.strptime() will raise a ValueError with this
    message: 'unconverted data remains: .234234'.  If %S is in the
    format string and the ValueError matches as above, a datetime
    object will be created from the part that matches and the
    microseconds in the time string.
    """
    try:
        return datetime.datetime(*time.strptime(t, format)[0:6]).time()
    except ValueError, msg:
        if "%S" in format:
            msg = str(msg)
            mat = re.match(r"unconverted data remains:"
                           " \.([0-9]{1,6})$", msg)
            if mat is not None:
                # fractional seconds are present - this is the style
                # used by datetime's isoformat() method
                frac = "." + mat.group(1)
                t = t[:-len(frac)]
                t = datetime.datetime(*time.strptime(t, format)[0:6])
                microsecond = int(float(frac)*1e6)
                return t.replace(microsecond=microsecond)
            else:
                mat = re.match(r"unconverted data remains:"
                               " \,([0-9]{3,3})$", msg)
                if mat is not None:
                    # fractional seconds are present - this is the style
                    # used by the logging module
                    frac = "." + mat.group(1)
                    t = t[:-len(frac)]
                    t = datetime.datetime(*time.strptime(t, format)[0:6])
                    microsecond = int(float(frac)*1e6)
                    return t.replace(microsecond=microsecond)

        raise

How to download all files (but not HTML) from a website using wget?

To filter for specific file extensions:

wget -A pdf,jpg -m -p -E -k -K -np http://site/path/

Or, if you prefer long option names:

wget --accept pdf,jpg --mirror --page-requisites --adjust-extension --convert-links --backup-converted --no-parent http://site/path/

This will mirror the site, but the files without jpg or pdf extension will be automatically removed.

Undefined class constant 'MYSQL_ATTR_INIT_COMMAND' with pdo

You could try replacing it with 1002 or issuing your initialization query right after opening a connection.

Printing without newline (print 'a',) prints a space, how to remove?

Just as a side note:

Printing is O(1) but building a string and then printing is O(n), where n is the total number of characters in the string. So yes, while building the string is "cleaner", it's not the most efficient method of doing so.

The way I would do it is as follows:

from sys import stdout
printf = stdout.write

Now you have a "print function" that prints out any string you give it without returning the new line character each time.

printf("Hello,")
printf("World!")

The output will be: Hello, World!

However, if you want to print integers, floats, or other non-string values, you'll have to convert them to a string with the str() function.

printf(str(2) + " " + str(4))

The output will be: 2 4

Owl Carousel Won't Autoplay

Setting autoPlay: true didn't work for me. But on setting autoPlay: 5000 it worked.

CSS white space at bottom of page despite having both min-height and height tag

This will remove the margin and padding from your page elements, since there is a paragraph with a script inside that is causing an added margin. this way you should reset it and then you can style the other elements of your page, or you could give that paragraph an id and set margin to zero only for it.

<style>
* {
   margin: 0;
   padding: 0;
}
</style>

Try to put this as the first style.

Add space between <li> elements

#access a {
    border-bottom: 2px solid #fff;
    color: #eee;
    display: block;
    line-height: 3.333em;
    padding: 0 10px 0 20px;
    text-decoration: none;
}

I see that you had used line-height but you gave it to <a> tag instead of <ul> Try this:

#access ul {line-height:3.333em;}

You wouldn't need to play with margins then.

What is the most efficient way to create a dictionary of two pandas Dataframe columns?

I found a faster way to solve the problem, at least on realistically large datasets using: df.set_index(KEY).to_dict()[VALUE]

Proof on 50,000 rows:

df = pd.DataFrame(np.random.randint(32, 120, 100000).reshape(50000,2),columns=list('AB'))
df['A'] = df['A'].apply(chr)

%timeit dict(zip(df.A,df.B))
%timeit pd.Series(df.A.values,index=df.B).to_dict()
%timeit df.set_index('A').to_dict()['B']

Output:

100 loops, best of 3: 7.04 ms per loop  # WouterOvermeire
100 loops, best of 3: 9.83 ms per loop  # Jeff
100 loops, best of 3: 4.28 ms per loop  # Kikohs (me)

Simpler way to check if variable is not equal to multiple string values?

You can make use of in_array() in PHP.

$os = array("uk", "us"); // You can set multiple check conditions here
if (in_array("uk", $os)) //Founds a match !
{
    echo "Got you"; 
}

Named regular expression group "(?P<group_name>regexp)": what does "P" stand for?

Since we're all guessing, I might as well give mine: I've always thought it stood for Python. That may sound pretty stupid -- what, P for Python?! -- but in my defense, I vaguely remembered this thread [emphasis mine]:

Subject: Claiming (?P...) regex syntax extensions

From: Guido van Rossum ([email protected])

Date: Dec 10, 1997 3:36:19 pm

I have an unusual request for the Perl developers (those that develop the Perl language). I hope this (perl5-porters) is the right list. I am cc'ing the Python string-sig because it is the origin of most of the work I'm discussing here.

You are probably aware of Python. I am Python's creator; I am planning to release a next "major" version, Python 1.5, by the end of this year. I hope that Python and Perl can co-exist in years to come; cross-pollination can be good for both languages. (I believe Larry had a good look at Python when he added objects to Perl 5; O'Reilly publishes books about both languages.)

As you may know, Python 1.5 adds a new regular expression module that more closely matches Perl's syntax. We've tried to be as close to the Perl syntax as possible within Python's syntax. However, the regex syntax has some Python-specific extensions, which all begin with (?P . Currently there are two of them:

(?P<foo>...) Similar to regular grouping parentheses, but the text
matched by the group is accessible after the match has been performed, via the symbolic group name "foo".

(?P=foo) Matches the same string as that matched by the group named "foo". Equivalent to \1, \2, etc. except that the group is referred
to by name, not number.

I hope that this Python-specific extension won't conflict with any future Perl extensions to the Perl regex syntax. If you have plans to use (?P, please let us know as soon as possible so we can resolve the conflict. Otherwise, it would be nice if the (?P syntax could be permanently reserved for Python-specific syntax extensions. (Is there some kind of registry of extensions?)

to which Larry Wall replied:

[...] There's no registry as of now--yours is the first request from outside perl5-porters, so it's a pretty low-bandwidth activity. (Sorry it was even lower last week--I was off in New York at Internet World.)

Anyway, as far as I'm concerned, you may certainly have 'P' with my blessing. (Obviously Perl doesn't need the 'P' at this point. :-) [...]

So I don't know what the original choice of P was motivated by -- pattern? placeholder? penguins? -- but you can understand why I've always associated it with Python. Which considering that (1) I don't like regular expressions and avoid them wherever possible, and (2) this thread happened fifteen years ago, is kind of odd.

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

Dim NuevoLibro As Workbook
Dim NombreLibro As String
    NombreLibro = "LibroPrueba"
'---Creamos nuevo libro y lo guardamos
    Set NuevoLibro = Workbooks.Add
        With NuevoLibro
            .SaveAs Filename:=NuevaRuta & NombreLibro, FileFormat:=52
        End With
                                                    '*****************************
                                                        'valores para FileFormat
                                                        '.xlsx = 51 '(52 for Mac)
                                                        '.xlsm = 52 '(53 for Mac)
                                                        '.xlsb = 50 '(51 for Mac)
                                                        '.xls = 56 '(57 for Mac)
                                                    '*****************************

How to clear jQuery validation error messages?

In my case helped with approach:

$(".field-validation-error span").hide();

Difference between Pragma and Cache-Control headers?

Stop using (HTTP 1.0) Replaced with (HTTP 1.1 since 1999)
Expires: [date] Cache-Control: max-age=[seconds]
Pragma: no-cache Cache-Control: no-cache

If it's after 1999, and you're still using Expires or Pragma, you're doing it wrong.

I'm looking at you Stackoverflow:

200 OK
Pragma: no-cache
Content-Type: application/json
X-Frame-Options: SAMEORIGIN
X-Request-Guid: a3433194-4a03-4206-91ea-6a40f9bfd824
Strict-Transport-Security: max-age=15552000
Content-Length: 54
Accept-Ranges: bytes
Date: Tue, 03 Apr 2018 19:03:12 GMT
Via: 1.1 varnish
Connection: keep-alive
X-Served-By: cache-yyz8333-YYZ
X-Cache: MISS
X-Cache-Hits: 0
X-Timer: S1522782193.766958,VS0,VE30
Vary: Fastly-SSL
X-DNS-Prefetch-Control: off
Cache-Control: private

tl;dr: Pragma is a legacy of HTTP/1.0 and hasn't been needed since Internet Explorer 5, or Netscape 4.7. Unless you expect some of your users to be using IE5: it's safe to stop using it.


  • Expires: [date] (deprecated - HTTP 1.0)
  • Pragma: no-cache (deprecated - HTTP 1.0)
  • Cache-Control: max-age=[seconds]
  • Cache-Control: no-cache (must re-validate the cached copy every time)

And the conditional requests:

  • Etag (entity tag) based conditional requests
    • Server: Etag: W/“1d2e7–1648e509289”
    • Client: If-None-Match: W/“1d2e7–1648e509289”
    • Server: 304 Not Modified
  • Modified date based conditional requests
    • Server: last-modified: Thu, 09 May 2019 19:15:47 GMT
    • Client: If-Modified-Since: Fri, 13 Jul 2018 10:49:23 GMT
    • Server: 304 Not Modified

last-modified: Thu, 09 May 2019 19:15:47 GMT

Does "display:none" prevent an image from loading?

The background-image of a div element will load if the div is set do 'display:none'.

Anyway, if that same div has a parent and that parent is set to 'display:none', the background-image of the child element will not load. :)

Example using bootstrap:

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">_x000D_
_x000D_
_x000D_
<div class="col-xs-12 visible-lg">_x000D_
 <div style="background-image: url('http://via.placeholder.com/300x300'); background-repeat:no-repeat; height: 300px;">lg</div>_x000D_
</div>_x000D_
<div class="col-xs-12 visible-md">_x000D_
 <div style="background-image: url('http://via.placeholder.com/200x200'); background-repeat:no-repeat; height: 200px;">md</div>_x000D_
</div>_x000D_
<div class="col-xs-12 visible-sm">_x000D_
 <div style="background-image: url('http://via.placeholder.com/100x100'); background-repeat:no-repeat; height: 100px">sm</div>_x000D_
</div>_x000D_
<div class="col-xs-12 visible-xs">_x000D_
 <div style="background-image: url('http://via.placeholder.com/50x50'); background-repeat:no-repeat; height: 50px">xs</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to run a cron job inside a docker container?

When you deploy your container on another host, just note that it won't start any processes automatically. You need to make sure that 'cron' service is running inside your container. In our case, I am using Supervisord with other services to start cron service.

[program:misc]
command=/etc/init.d/cron restart
user=root
autostart=true
autorestart=true
stderr_logfile=/var/log/misc-cron.err.log
stdout_logfile=/var/log/misc-cron.out.log
priority=998

Console app arguments, how arguments are passed to Main method

Read MSDN.

it also contains a link to the args.

short answer: no, the main does not get override. when visual studio (actually the compiler) builds your exe it must declare a starting point for the assmebly, that point is the main function.

if you meant how to literary pass args then you can either run you're app from the command line with them (e.g. appname.exe param1 param2) or in the project setup, enter them (in the command line arguments in the Debug tab)

in the main you will need to read those args for example:

for (int i = 0; i < args.Length; i++)
{
    string flag = args.GetValue(i).ToString();
    if (flag == "bla") 
    {
        Bla();
    }
}

Install apps silently, with granted INSTALL_PACKAGES permission

An 3rd party application cannot install an Android App sliently. However, a 3rd party application can ask the Android OS to install a application.

So you should define this:

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file:///sdcard/app.apk", "application/vnd.android.package-archive");
startActivity(intent);

You can also try to install it as a system app to grant the permission and ignore this define. (Root Required)

You can run the following command on your 3rd party app to install an app on the rooted device.

The code is:

private void installApk(String filename) {
File file = new File(filename); 
if(file.exists()){
    try {   
        final String command = "pm install -r " + file.getAbsolutePath();
        Process proc = Runtime.getRuntime().exec(new String[] { "su", "-c", command });
        proc.waitFor();
    } catch (Exception e) {
        e.printStackTrace();
    }
 }
}

I hope that this answer is helpful for you.

Check if an element is present in an array

In lodash you can use _.includes (which also aliases to _.contains)

You can search the whole array:

_.includes([1, 2, 3], 1); // true

You can search the array from a starting index:

_.includes([1, 2, 3], 1, 1);  // false (begins search at index 1)

Search a string:

_.includes('pebbles', 'eb');  // true (string contains eb)

Also works for checking simple arrays of objects:

_.includes({ 'user': 'fred', 'age': 40 }, 'fred');    // true
_.includes({ 'user': 'fred', 'age': false }, false);  // true

One thing to note about the last case is it works for primitives like strings, numbers and booleans but cannot search through arrays or objects

_.includes({ 'user': 'fred', 'age': {} }, {});   // false
_.includes({ 'user': [1,2,3], 'age': {} }, 3);   // false

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Right click on your website go to property pages and check both the check-boxes under Accessibility validation click on ok. run the website.

Android List View Drag and Drop sort

Now it's pretty easy to implement for RecyclerView with ItemTouchHelper. Just override onMove method from ItemTouchHelper.Callback:

 @Override
public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
    mMovieAdapter.swap(viewHolder.getAdapterPosition(), target.getAdapterPosition());
    return true;
}

Pretty good tutorial on this can be found at medium.com : Drag and Swipe with RecyclerView

How to recursively find and list the latest modified files in a directory with subdirectories and times

You may give the printf command of find a try

%Ak File's last access time in the format specified by k, which is either @' or a directive for the C strftime' function. The possible values for k are listed below; some of them might not be available on all systems, due to differences in `strftime' between systems.

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

First of all, a caveat. Why do you want to use telnet? telnet is an old protocol, unsafe and impractical for remote access. It's been (almost)totally replaced by ssh.

To answer your questions, it depends. It depends on the telnet client you use. If you use microsoft telnet, you can't. Microsoft telnet does not have any mean to send commands from a batch file or a command line.

Shell Scripting: Using a variable to define a path

To add to the above correct answer :- For my case in shell, this code worked (working on sqoop)

ROOT_PATH="path/to/the/folder"
--options-file  $ROOT_PATH/query.txt

JUnit 5: How to assert an exception is thrown?

In Java 8 and JUnit 5 (Jupiter) we can assert for exceptions as follows. Using org.junit.jupiter.api.Assertions.assertThrows

public static < T extends Throwable > T assertThrows(Class< T > expectedType, Executable executable)

Asserts that execution of the supplied executable throws an exception of the expectedType and returns the exception.

If no exception is thrown, or if an exception of a different type is thrown, this method will fail.

If you do not want to perform additional checks on the exception instance, simply ignore the return value.

@Test
public void itShouldThrowNullPointerExceptionWhenBlahBlah() {
    assertThrows(NullPointerException.class,
            ()->{
            //do whatever you want to do here
            //ex : objectName.thisMethodShoulThrowNullPointerExceptionForNullParameter(null);
            });
}

That approach will use the Functional Interface Executable in org.junit.jupiter.api.

Refer :

How to replace NaN value with zero in a huge data frame?

The following should do what you want:

x <- data.frame(X1=sample(c(1:3,NaN), 200, replace=TRUE), X2=sample(c(4:6,NaN), 200, replace=TRUE))
head(x)
x <- replace(x, is.na(x), 0)
head(x)

how to add a jpg image in Latex

if you add a jpg,png,pdf picture, you should use pdflatex to compile it.

Unable to run Java GUI programs with Ubuntu

Check your X Window environment variables using the "env" command.

How do I check if the Java JDK is installed on Mac?

If you are on Mac OS Big Sur, then you probably have a messed up java installation. I found info on how to fix the issue with this article: https://knasmueller.net/how-to-install-java-openjdk-15-on-macos-big-sur

  1. Download the .tar.gz file of the JDK on https://jdk.java.net/15/
  2. Navigate to the download folder, and run these commands (move the .tar.gz file, extract it and remove it after extraction):
sudo mv openjdk-15.0.2_osx-x64_bin.tar.gz /Library/Java/JavaVirtualMachines/
cd /Library/Java/JavaVirtualMachines/
sudo tar -xzf openjdk-15.0.2_osx-x64_bin.tar.gz
sudo rm openjdk-15.0.2_osx-x64_bin.tar.gz

Note: it might be 15.0.3 or higher, depending on the date of your download.

  1. run /usr/libexec/java_home -v15 and copy the output
  2. add this line to your .bash_profile or .zshrc file, depending on which shell you are using. You will probably have only one of these files existing in your home directory (~/.bash_profile or ~/.zshrc).
JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.0.2.jdk/Contents/Home
  1. save the changes and make them effective right away by running: source ~/.bash_profile or source ~/.zshrc
  2. check that java is working - run java -v

View JSON file in Browser

In Chrome, use JSONView to view formatted JSON.

To view "local" *.json files: - after install You must open the Extensions option from Window menu. - Check box next to "Allow Access to File URLs" - note that save is automatic (i.e. no explicit save necessary)

Re-open the *.json file and it should be formatted.

Prevent scroll-bar from adding-up to the Width of page on Chrome

For containers with a fixed width a pure CSS cross browser solution can be accomplished by wrapping the container into another div and applying the same width to both divs.

#outer {
  overflow-y: auto;
  overflow-x: hidden;
  /*
   * width must be an absolute value otherwise the inner divs width must be set via
   * javascript to the computed width of the parent container
   */
  width: 200px;
}

#inner {
  width: inherit;
}

Click here to see an example on Codepen

Check if table exists without using "select from"

You can query the INFORMATION_SCHEMA tables system view:

SELECT table_name
FROM information_schema.tables
WHERE table_schema = 'databasename'
AND table_name = 'testtable';

If no rows returned, then the table doesn't exist.

How to get setuptools and easy_install?

Give this link a try --> https://pypi.python.org/pypi/setuptools

I'm assuming you're on Windows (could be wrong) but if you click the green Downloads button, it should take you to a table where you can choose to download a .exe version of setuptools appropriate for your version of Python. All that eggsetup stuff should be taken care of in the executable file.

Let me know if you need more help.

Is there any good dynamic SQL builder library in Java?

You can use the following library:

https://github.com/pnowy/NativeCriteria

The library is built on the top of the Hibernate "create sql query" so it supports all databases supported by Hibernate (the Hibernate session and JPA providers are supported). The builder patter is available and so on (object mappers, result mappers).

You can find the examples on github page, the library is available at Maven central of course.

NativeCriteria c = new NativeCriteria(new HibernateQueryProvider(hibernateSession), "table_name", "alias");
c.addJoin(NativeExps.innerJoin("table_name_to_join", "alias2", "alias.left_column", "alias2.right_column"));
c.setProjection(NativeExps.projection().addProjection(Lists.newArrayList("alias.table_column","alias2.table_column")));

How do you set your pythonpath in an already-created virtualenv?

It's already answered here -> Is my virtual environment (python) causing my PYTHONPATH to break?

UNIX/LINUX

Add "export PYTHONPATH=/usr/local/lib/python2.0" this to ~/.bashrc file and source it by typing "source ~/.bashrc" OR ". ~/.bashrc".

WINDOWS XP

1) Go to the Control panel 2) Double click System 3) Go to the Advanced tab 4) Click on Environment Variables

In the System Variables window, check if you have a variable named PYTHONPATH. If you have one already, check that it points to the right directories. If you don't have one already, click the New button and create it.

PYTHON CODE

Alternatively, you can also do below your code:-

import sys
sys.path.append("/home/me/mypy") 

How to convert local time string to UTC?

How about -

time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime(seconds))

if seconds is None then it converts the local time to UTC time else converts the passed in time to UTC.

How to delete multiple values from a vector?

instead of

x <- x[! x %in% c(2,3,5)]

using the packages purrr and magrittr, you can do:

your_vector %<>% discard(~ .x %in% c(2,3,5))

this allows for subsetting using the vector name only once. And you can use it in pipes :)

Using AJAX to pass variable to PHP and retrieve those using AJAX again

you have to pass values with the single quotes

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: '145'}), //variables should be pass like this
            success: function(data){
                console.log(data);
                           }
        });  
        $.ajax({
    url:'ajax.php',
    data:"",
    dataType:'json',
    success:function(data1){
            var y1=data1;
            console.log(data1);
            }
        });

    });
});

try it it may work.......

Vertical alignment of text and icon in button

Just wrap the button label in an extra span and add class="align-middle" to both (the icon and the label). This will center your icon with text vertical.

<button id="edit-listing-form-house_Continue" 
    class="btn btn-large btn-primary"
    style=""
    value=""
    name="Continue"
    type="submit">
<span class="align-middle">Continue</span>
<i class="icon-ok align-middle" style="font-size:40px;"></i>

addEventListener vs onclick

Using inline handlers is incompatible with Content Security Policy so the addEventListener approach is more secure from that point of view. Of course you can enable the inline handlers with unsafe-inline but, as the name suggests, it's not safe as it brings back the whole hordes of JavaScript exploits that CSP prevents.

Most common C# bitwise operations on enums

C++ operations are: & | ^ ~ (for and, or, xor and not bitwise operations). Also of interest are >> and <<, which are bitshift operations.

So, to test for a bit being set in a flag, you would use: if (flags & 8) //tests bit 4 has been set

Can't find file executable in your configured search path for gnc gcc compiler

I had also found this error but I have solved this problem by easy steps. If you want to solve this problem follow these steps:

Step 1: First start code block

Step 2: Go to menu bar and click on the Setting menu

Step 3: After that click on the Compiler option

Step 4: Now, a pop up window will be opened. In this window, select "GNU GCC COMPILER"

Step 5: Now go to the toolchain executables tab and select the compiler installation directory like (C:\Program Files (x86)\CodeBlocks\MinGW\bin)

Step 6: Click on the Ok.

enter image description here

Now you can remove this error by follow these steps. Sometimes you don't need to select bin folder. You need to select only (C:\Program Files (x86)\CodeBlocks\MinGW) this path but some system doesn't work this path. That's why you have to select path from C:/ to bin folder.

Thank you.

How to install sklearn?

pip install numpy scipy scikit-learn

if you don't have pip, install it using

python get-pip.py

Download get-pip.py from the following link. or use curl to download it.

curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

Add 'x' number of hours to date

You may use something like the strtotime() function to add something to the current timestamp. $new_time = date("Y-m-d H:i:s", strtotime('+5 hours')).

If you need variables in the function, you must use double quotes then like strtotime("+{$hours} hours"), however better you use strtotime(sprintf("+%d hours", $hours)) then.

How to replace plain URLs with links?

Replacing URLs with links (Answer to the General Problem)

The regular expression in the question misses a lot of edge cases. When detecting URLs, it's always better to use a specialized library that handles international domain names, new TLDs like .museum, parentheses and other punctuation within and at the end of the URL, and many other edge cases. See the Jeff Atwood's blog post The Problem With URLs for an explanation of some of the other issues.

The best summary of URL matching libraries is in Dan Dascalescu's Answer +100
(as of Feb 2014)


"Make a regular expression replace more than one match" (Answer to the specific problem)

Add a "g" to the end of the regular expression to enable global matching:

/ig;

But that only fixes the problem in the question where the regular expression was only replacing the first match. Do not use that code.

How to insert a row between two rows in an existing excel with HSSF (Apache POI)

I came across the same issue recently. I had to insert new rows in a document with hidden rows and faced the same issues with you. After some search and some emails in apache poi list, it seems like a bug in shiftrows() when a document has hidden rows.

How to use range-based for() loop with std::map?

Each element of the container is a map<K, V>::value_type, which is a typedef for std::pair<const K, V>. Consequently, in C++17 or higher, you can write

for (auto& [key, value]: myMap) {
    std::cout << key << " has value " << value << std::endl;
}

or as

for (const auto& [key, value]: myMap) {
    std::cout << key << " has value " << value << std::endl;
}

if you don't plan on modifying the values.

In C++11 and C++14, you can use enhanced for loops to extract out each pair on its own, then manually extract the keys and values:

for (const auto& kv : myMap) {
    std::cout << kv.first << " has value " << kv.second << std::endl;
}

You could also consider marking the kv variable const if you want a read-only view of the values.

Can I add background color only for padding?

Another option with pure CSS would be something like this:

nav {
    margin: 0px auto;
    width: 100%;
    height: 50px;
    background-color: white;
    float: left;
    padding: 10px;
    border: 2px solid red;
    position: relative;
    z-index: 10;
}

nav:after {
    background-color: grey;
    content: '';
    display: block;
    position: absolute;
    top: 10px;
    left: 10px;
    right: 10px;
    bottom: 10px;
    z-index: -1;
}

Demo here

Regex to match string containing two names in any order

Explanation of command that i am going to write:-

. means any character, digit can come in place of .

* means zero or more occurrences of thing written just previous to it.

| means 'or'.

So,

james.*jack

would search james , then any number of character until jack comes.

Since you want either jack.*james or james.*jack

Hence Command:

jack.*james|james.*jack

Gradle - Could not find or load main class

I resolved it by adding below code to my application.

// enter code here this is error I was getting when I run build.gradle. main class name has not been configured and it could not be resolved

public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
}

CSS3 transition events

Update

All modern browsers now support the unprefixed event:

element.addEventListener('transitionend', callback, false);

https://caniuse.com/#feat=css-transitions


I was using the approach given by Pete, however I have now started using the following

$(".myClass").one('transitionend webkitTransitionEnd oTransitionEnd otransitionend MSTransitionEnd', 
function() {
 //do something
});

Alternatively if you use bootstrap then you can simply do

$(".myClass").one($.support.transition.end,
function() {
 //do something
});

This is becuase they include the following in bootstrap.js

+function ($) {
  'use strict';

  // CSS TRANSITION SUPPORT (Shoutout: http://www.modernizr.com/)
  // ============================================================

  function transitionEnd() {
    var el = document.createElement('bootstrap')

    var transEndEventNames = {
      'WebkitTransition' : 'webkitTransitionEnd',
      'MozTransition'    : 'transitionend',
      'OTransition'      : 'oTransitionEnd otransitionend',
      'transition'       : 'transitionend'
    }

    for (var name in transEndEventNames) {
      if (el.style[name] !== undefined) {
        return { end: transEndEventNames[name] }
      }
    }

    return false // explicit for ie8 (  ._.)
  }


  $(function () {
    $.support.transition = transitionEnd()
  })

}(jQuery);

Note they also include an emulateTransitionEnd function which may be needed to ensure a callback always occurs.

  // http://blog.alexmaccaw.com/css-transitions
  $.fn.emulateTransitionEnd = function (duration) {
    var called = false, $el = this
    $(this).one($.support.transition.end, function () { called = true })
    var callback = function () { if (!called) $($el).trigger($.support.transition.end) }
    setTimeout(callback, duration)
    return this
  }

Be aware that sometimes this event doesn’t fire, usually in the case when properties don’t change or a paint isn’t triggered. To ensure we always get a callback, let’s set a timeout that’ll trigger the event manually.

http://blog.alexmaccaw.com/css-transitions

Jaxb, Class has two properties of the same name

ModeleREP#getTimeSeries() have to be with @Transient annotation. That would help.

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

TypeScript function overloading

Function overloading in typescript:

According to Wikipedia, (and many programming books) the definition of method/function overloading is the following:

In some programming languages, function overloading or method overloading is the ability to create multiple functions of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

In typescript we cannot have different implementations of the same function that are called according to the number and type of arguments. This is because when TS is compiled to JS, the functions in JS have the following characteristics:

  • JavaScript function definitions do not specify data types for their parameters
  • JavaScript functions do not check the number of arguments when called

Therefore, in a strict sense, one could argue that TS function overloading doesn't exists. However, there are things you can do within your TS code that can perfectly mimick function overloading.

Here is an example:

function add(a: number, b: number, c: number): number;
function add(a: number, b: number): any;
function add(a: string, b: string): any;

function add(a: any, b: any, c?: any): any {
  if (c) {
    return a + c;
  }
  if (typeof a === 'string') {
    return `a is ${a}, b is ${b}`;
  } else {
    return a + b;
  }
}

The TS docs call this method overloading, and what we basically did is supplying multiple method signatures (descriptions of possible parameters and types) to the TS compiler. Now TS can figure out if we called our function correctly during compile time and give us an error if we called the function incorrectly.

Variable number of arguments in C++?

The only way is through the use of C style variable arguments, as described here. Note that this is not a recommended practice, as it's not typesafe and error-prone.

What is the convention for word separator in Java package names?

Here's what the official naming conventions document prescribes:

Packages

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.

Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.

Examples

  • com.sun.eng
  • com.apple.quicktime.v2
  • edu.cmu.cs.bovik.cheese

References


Note that in particular, anything following the top-level domain prefix isn't specified by the above document. The JLS also agrees with this by giving the following examples:

  • com.sun.sunsoft.DOE
  • gov.whitehouse.socks.mousefinder
  • com.JavaSoft.jag.Oak
  • org.npr.pledge.driver
  • uk.ac.city.rugby.game

The following excerpt is also relevant:

In some cases, the internet domain name may not be a valid package name. Here are some suggested conventions for dealing with these situations:

  • If the domain name contains a hyphen, or any other special character not allowed in an identifier, convert it into an underscore.
  • If any of the resulting package name components are keywords then append underscore to them.
  • If any of the resulting package name components start with a digit, or any other character that is not allowed as an initial character of an identifier, have an underscore prefixed to the component.

References

How to compile makefile using MinGW?

Excerpt from http://www.mingw.org/wiki/FAQ:

What's the difference between make and mingw32-make?

The "native" (i.e.: MSVCRT dependent) port of make is lacking in some functionality and has modified functionality due to the lack of POSIX on Win32. There also exists a version of make in the MSYS distribution that is dependent on the MSYS runtime. This port operates more as make was intended to operate and gives less headaches during execution. Based on this, the MinGW developers/maintainers/packagers decided it would be best to rename the native version so that both the "native" version and the MSYS version could be present at the same time without file name collision.

So,look into C:\MinGW\bin directory and first make sure what make executable, have you installed.(make.exe or mingw32-make.exe)

Before using MinGW, you should add C:\MinGW\bin; to the PATH environment variable using the instructions mentioned at http://www.mingw.org/wiki/Getting_Started/

Then cd to your directory, where you have the makefile and Try using mingw32-make.exe makefile.in or simply make.exe makefile.in(depending on executables in C:\MinGW\bin).

If you want a GUI based solution, install DevCPP IDE and then re-make.

Git command to display HEAD commit id?

You can specify git log options to show only the last commit, -1, and a format that includes only the commit ID, like this:

git log -1 --format=%H

If you prefer the shortened commit ID:

git log -1 --format=%h

Web colors in an Android color xml resource file

Here is the improved answer from submitted by Lars: this works with the new android "L" (preview)

<?xml version="1.0" encoding="utf-8"?>
<resources>
 <item name="White" type="color">#FFFFFFFF</item>
 <item name="Ivory" type="color">#FFFFFFF0</item>
 <item name="LightYellow" type="color">#FFFFFFE0</item>
 <item name="Yellow" type="color">#FFFFFF00</item>
 <item name="Snow" type="color">#FFFFFAFA</item>
 <item name="FloralWhite" type="color">#FFFFFAF0</item>
 <item name="LemonChiffon" type="color">#FFFFFACD</item>
 <item name="Cornsilk" type="color">#FFFFF8DC</item>
 <item name="Seashell" type="color">#FFFFF5EE</item>
 <item name="LavenderBlush" type="color">#FFFFF0F5</item>
 <item name="PapayaWhip" type="color">#FFFFEFD5</item>
 <item name="BlanchedAlmond" type="color">#FFFFEBCD</item>
 <item name="MistyRose" type="color">#FFFFE4E1</item>
 <item name="Bisque" type="color">#FFFFE4C4</item>
 <item name="Moccasin" type="color">#FFFFE4B5</item>
 <item name="NavajoWhite" type="color">#FFFFDEAD</item>
 <item name="PeachPuff" type="color">#FFFFDAB9</item>
 <item name="Gold" type="color">#FFFFD700</item>
 <item name="Pink" type="color">#FFFFC0CB</item>
 <item name="LightPink" type="color">#FFFFB6C1</item>
 <item name="Orange" type="color">#FFFFA500</item>
 <item name="LightSalmon" type="color">#FFFFA07A</item>
 <item name="DarkOrange" type="color">#FFFF8C00</item>
 <item name="Coral" type="color">#FFFF7F50</item>
 <item name="HotPink" type="color">#FFFF69B4</item>
 <item name="Tomato" type="color">#FFFF6347</item>
 <item name="OrangeRed" type="color">#FFFF4500</item>
 <item name="DeepPink" type="color">#FFFF1493</item>
 <item name="Fuchsia" type="color">#FFFF00FF</item>
 <item name="Magenta" type="color">#FFFF00FF</item>
 <item name="Red" type="color">#FFFF0000</item>
 <item name="OldLace" type="color">#FFFDF5E6</item>
 <item name="LightGoldenrodYellow" type="color">#FFFAFAD2</item>
 <item name="Linen" type="color">#FFFAF0E6</item>
 <item name="AntiqueWhite" type="color">#FFFAEBD7</item>
 <item name="Salmon" type="color">#FFFA8072</item>
 <item name="GhostWhite" type="color">#FFF8F8FF</item>
 <item name="MintCream" type="color">#FFF5FFFA</item>
 <item name="WhiteSmoke" type="color">#FFF5F5F5</item>
 <item name="Beige" type="color">#FFF5F5DC</item>
 <item name="Wheat" type="color">#FFF5DEB3</item>
 <item name="SandyBrown" type="color">#FFF4A460</item>
 <item name="Azure" type="color">#FFF0FFFF</item>
 <item name="Honeydew" type="color">#FFF0FFF0</item>
 <item name="AliceBlue" type="color">#FFF0F8FF</item>
 <item name="Khaki" type="color">#FFF0E68C</item>
 <item name="LightCoral" type="color">#FFF08080</item>
 <item name="PaleGoldenrod" type="color">#FFEEE8AA</item>
 <item name="Violet" type="color">#FFEE82EE</item>
 <item name="DarkSalmon" type="color">#FFE9967A</item>
 <item name="Lavender" type="color">#FFE6E6FA</item>
 <item name="LightCyan" type="color">#FFE0FFFF</item>
 <item name="BurlyWood" type="color">#FFDEB887</item>
 <item name="Plum" type="color">#FFDDA0DD</item>
 <item name="Gainsboro" type="color">#FFDCDCDC</item>
 <item name="Crimson" type="color">#FFDC143C</item>
 <item name="PaleVioletRed" type="color">#FFDB7093</item>
 <item name="Goldenrod" type="color">#FFDAA520</item>
 <item name="Orchid" type="color">#FFDA70D6</item>
 <item name="Thistle" type="color">#FFD8BFD8</item>
 <item name="LightGrey" type="color">#FFD3D3D3</item>
 <item name="Tan" type="color">#FFD2B48C</item>
 <item name="Chocolate" type="color">#FFD2691E</item>
 <item name="Peru" type="color">#FFCD853F</item>
 <item name="IndianRed" type="color">#FFCD5C5C</item>
 <item name="MediumVioletRed" type="color">#FFC71585</item>
 <item name="Silver" type="color">#FFC0C0C0</item>
 <item name="DarkKhaki" type="color">#FFBDB76B</item>
 <item name="RosyBrown" type="color">#FFBC8F8F</item>
 <item name="MediumOrchid" type="color">#FFBA55D3</item>
 <item name="DarkGoldenrod" type="color">#FFB8860B</item>
 <item name="FireBrick" type="color">#FFB22222</item>
 <item name="PowderBlue" type="color">#FFB0E0E6</item>
 <item name="LightSteelBlue" type="color">#FFB0C4DE</item>
 <item name="PaleTurquoise" type="color">#FFAFEEEE</item>
 <item name="GreenYellow" type="color">#FFADFF2F</item>
 <item name="LightBlue" type="color">#FFADD8E6</item>
 <item name="DarkGray" type="color">#FFA9A9A9</item>
 <item name="Brown" type="color">#FFA52A2A</item>
 <item name="Sienna" type="color">#FFA0522D</item>
 <item name="YellowGreen" type="color">#FF9ACD32</item>
 <item name="DarkOrchid" type="color">#FF9932CC</item>
 <item name="PaleGreen" type="color">#FF98FB98</item>
 <item name="DarkViolet" type="color">#FF9400D3</item>
 <item name="MediumPurple" type="color">#FF9370DB</item>
 <item name="LightGreen" type="color">#FF90EE90</item>
 <item name="DarkSeaGreen" type="color">#FF8FBC8F</item>
 <item name="SaddleBrown" type="color">#FF8B4513</item>
 <item name="DarkMagenta" type="color">#FF8B008B</item>
 <item name="DarkRed" type="color">#FF8B0000</item>
 <item name="BlueViolet" type="color">#FF8A2BE2</item>
 <item name="LightSkyBlue" type="color">#FF87CEFA</item>
 <item name="SkyBlue" type="color">#FF87CEEB</item>
 <item name="Gray" type="color">#FF808080</item>
 <item name="Olive" type="color">#FF808000</item>
 <item name="Purple" type="color">#FF800080</item>
 <item name="Maroon" type="color">#FF800000</item>
 <item name="Aquamarine" type="color">#FF7FFFD4</item>
 <item name="Chartreuse" type="color">#FF7FFF00</item>
 <item name="LawnGreen" type="color">#FF7CFC00</item>
 <item name="MediumSlateBlue" type="color">#FF7B68EE</item>
 <item name="LightSlateGray" type="color">#FF778899</item>
 <item name="SlateGray" type="color">#FF708090</item>
 <item name="OliveDrab" type="color">#FF6B8E23</item>
 <item name="SlateBlue" type="color">#FF6A5ACD</item>
 <item name="DimGray" type="color">#FF696969</item>
 <item name="MediumAquamarine" type="color">#FF66CDAA</item>
 <item name="CornflowerBlue" type="color">#FF6495ED</item>
 <item name="CadetBlue" type="color">#FF5F9EA0</item>
 <item name="DarkOliveGreen" type="color">#FF556B2F</item>
 <item name="Indigo" type="color">#FF4B0082</item>
 <item name="MediumTurquoise" type="color">#FF48D1CC</item>
 <item name="DarkSlateBlue" type="color">#FF483D8B</item>
 <item name="SteelBlue" type="color">#FF4682B4</item>
 <item name="RoyalBlue" type="color">#FF4169E1</item>
 <item name="Turquoise" type="color">#FF40E0D0</item>
 <item name="MediumSeaGreen" type="color">#FF3CB371</item>
 <item name="LimeGreen" type="color">#FF32CD32</item>
 <item name="DarkSlateGray" type="color">#FF2F4F4F</item>
 <item name="SeaGreen" type="color">#FF2E8B57</item>
 <item name="ForestGreen" type="color">#FF228B22</item>
 <item name="LightSeaGreen" type="color">#FF20B2AA</item>
 <item name="DodgerBlue" type="color">#FF1E90FF</item>
 <item name="MidnightBlue" type="color">#FF191970</item>
 <item name="Aqua" type="color">#FF00FFFF</item>
 <item name="Cyan" type="color">#FF00FFFF</item>
 <item name="SpringGreen" type="color">#FF00FF7F</item>
 <item name="Lime" type="color">#FF00FF00</item>
 <item name="MediumSpringGreen" type="color">#FF00FA9A</item>
 <item name="DarkTurquoise" type="color">#FF00CED1</item>
 <item name="DeepSkyBlue" type="color">#FF00BFFF</item>
 <item name="DarkCyan" type="color">#FF008B8B</item>
 <item name="Teal" type="color">#FF008080</item>
 <item name="Green" type="color">#FF008000</item>
 <item name="DarkGreen" type="color">#FF006400</item>
 <item name="Blue" type="color">#FF0000FF</item>
 <item name="MediumBlue" type="color">#FF0000CD</item>
 <item name="DarkBlue" type="color">#FF00008B</item>
 <item name="Navy" type="color">#FF000080</item>
 <item name="Black" type="color">#FF000000</item>

 <integer-array name="androidcolors">

         <item>@color/White</item>
         <item>@color/Ivory</item>
         <item>@color/LightYellow</item>
         <item>@color/Yellow</item>
         <item>@color/Snow</item>
         <item>@color/FloralWhite</item>
         <item>@color/LemonChiffon</item>
         <item>@color/Cornsilk</item>
         <item>@color/Seashell</item>
         <item>@color/LavenderBlush</item>
         <item>@color/PapayaWhip</item>
         <item>@color/BlanchedAlmond</item>
         <item>@color/MistyRose</item>
         <item>@color/Bisque</item>
         <item>@color/Moccasin</item>
         <item>@color/NavajoWhite</item>
         <item>@color/PeachPuff</item>
         <item>@color/Gold</item>
         <item>@color/Pink</item>
         <item>@color/LightPink</item>
         <item>@color/Orange</item>
         <item>@color/LightSalmon</item>
         <item>@color/DarkOrange</item>
         <item>@color/Coral</item>
         <item>@color/HotPink</item>
         <item>@color/Tomato</item>
         <item>@color/OrangeRed</item>
         <item>@color/DeepPink</item>
         <item>@color/Fuchsia</item>
         <item>@color/Magenta</item>
         <item>@color/Red</item>
         <item>@color/OldLace</item>
         <item>@color/LightGoldenrodYellow</item>
         <item>@color/Linen</item>
         <item>@color/AntiqueWhite</item>
         <item>@color/Salmon</item>
         <item>@color/GhostWhite</item>
         <item>@color/MintCream</item>
         <item>@color/WhiteSmoke</item>
         <item>@color/Beige</item>
         <item>@color/Wheat</item>
         <item>@color/SandyBrown</item>
         <item>@color/Azure</item>
         <item>@color/Honeydew</item>
         <item>@color/AliceBlue</item>
         <item>@color/Khaki</item>
         <item>@color/LightCoral</item>
         <item>@color/PaleGoldenrod</item>
         <item>@color/Violet</item>
         <item>@color/DarkSalmon</item>
         <item>@color/Lavender</item>
         <item>@color/LightCyan</item>
         <item>@color/BurlyWood</item>
         <item>@color/Plum</item>
         <item>@color/Gainsboro</item>
         <item>@color/Crimson</item>
         <item>@color/PaleVioletRed</item>
         <item>@color/Goldenrod</item>
         <item>@color/Orchid</item>
         <item>@color/Thistle</item>
         <item>@color/LightGrey</item>
         <item>@color/Tan</item>
         <item>@color/Chocolate</item>
         <item>@color/Peru</item>
         <item>@color/IndianRed</item>
         <item>@color/MediumVioletRed</item>
         <item>@color/Silver</item>
         <item>@color/DarkKhaki</item>
         <item>@color/RosyBrown</item>
         <item>@color/MediumOrchid</item>
         <item>@color/DarkGoldenrod</item>
         <item>@color/FireBrick</item>
         <item>@color/PowderBlue</item>
         <item>@color/LightSteelBlue</item>
         <item>@color/PaleTurquoise</item>
         <item>@color/GreenYellow</item>
         <item>@color/LightBlue</item>
         <item>@color/DarkGray</item>
         <item>@color/Brown</item>
         <item>@color/Sienna</item>
         <item>@color/YellowGreen</item>
         <item>@color/DarkOrchid</item>
         <item>@color/PaleGreen</item>
         <item>@color/DarkViolet</item>
         <item>@color/MediumPurple</item>
         <item>@color/LightGreen</item>
         <item>@color/DarkSeaGreen</item>
         <item>@color/SaddleBrown</item>
         <item>@color/DarkMagenta</item>
         <item>@color/DarkRed</item>
         <item>@color/BlueViolet</item>
         <item>@color/LightSkyBlue</item>
         <item>@color/SkyBlue</item>
         <item>@color/Gray</item>
         <item>@color/Olive</item>
         <item>@color/Purple</item>
         <item>@color/Maroon</item>
         <item>@color/Aquamarine</item>
         <item>@color/Chartreuse</item>
         <item>@color/LawnGreen</item>
         <item>@color/MediumSlateBlue</item>
         <item>@color/LightSlateGray</item>
         <item>@color/SlateGray</item>
         <item>@color/OliveDrab</item>
         <item>@color/SlateBlue</item>
         <item>@color/DimGray</item>
         <item>@color/MediumAquamarine</item>
         <item>@color/CornflowerBlue</item>
         <item>@color/CadetBlue</item>
         <item>@color/DarkOliveGreen</item>
         <item>@color/Indigo</item>
         <item>@color/MediumTurquoise</item>
         <item>@color/DarkSlateBlue</item>
         <item>@color/SteelBlue</item>
         <item>@color/RoyalBlue</item>
         <item>@color/Turquoise</item>
         <item>@color/MediumSeaGreen</item>
         <item>@color/LimeGreen</item>
         <item>@color/DarkSlateGray</item>
         <item>@color/SeaGreen</item>
         <item>@color/ForestGreen</item>
         <item>@color/LightSeaGreen</item>
         <item>@color/DodgerBlue</item>
         <item>@color/MidnightBlue</item>
         <item>@color/Aqua</item>
         <item>@color/Cyan</item>
         <item>@color/SpringGreen</item>
         <item>@color/Lime</item>
         <item>@color/MediumSpringGreen</item>
         <item>@color/DarkTurquoise</item>
         <item>@color/DeepSkyBlue</item>
         <item>@color/DarkCyan</item>
         <item>@color/Teal</item>
         <item>@color/Green</item>
         <item>@color/DarkGreen</item>
         <item>@color/Blue</item>
         <item>@color/MediumBlue</item>
         <item>@color/DarkBlue</item>
         <item>@color/Navy</item>
         <item>@color/Black</item>

     </integer-array>


</resources>

How do I get first element rather than using [0] in jQuery?

You can use the first selector.

var header = $('.header:first')

ssh: connect to host github.com port 22: Connection timed out

When I accidentally switched to a guest wifi network I got this error. Had to switch back to my default wifi network.

How do I get the value of a registry key and ONLY the value using powershell

Not sure at what version this capability arrived, but you can use something like this to return all the properties of multiple child registry entries in an array:

$InstalledSoftware = Get-ChildItem "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" | ForEach-Object {Get-ItemProperty "Registry::$_"}

Only adding this as Google brought me here for a relevant reason and I eventually came up with the above one-liner for dredging the registry.

Are "while(true)" loops so bad?

Back in 1967, Edgar Dijkstra wrote an article in a trade magazine about why goto should be eliminated from high level languages to improve code quality. A whole programming paradigm called "structured programming" came out of this, though certainly not everyone agrees that goto automatically means bad code.

The crux of structured programming is essentially that the structure of the code should determine its flow rather than having gotos or breaks or continues to determine flow, wherever possible. Similiarly, having multiple entry and exit points to a loop or function are also discouraged in that paradigm.

Obviously this is not the only programming paradigm, but often it can be easily applied to other paradigms like object oriented programming (ala Java).

Your teachers has probably been taught, and is trying to teach your class that we would best avoid "spaghetti code" by making sure our code is structured, and following the implied rules of structured programming.

While there is nothing inherently "wrong" with an implementation that uses break, some consider it significantly easier to read code where the condition for the loop is explicitly specified within the while() condition, and eliminates some possibilities of being overly tricky. There are definitely pitfalls to using a while(true) condition that seem to pop up frequently in code by novice programmers, such as the risk of accidentally creating an infinite loop, or making code that is hard to read or unnecessarily confusing.

Ironically, exception handling is an area where deviation from structured programming will certainly come up and be expected as you get further into programming in Java.

It is also possible your instructor may have expected you to demonstrate your ability to use a particular loop structure or syntax being taught in that chapter or lesson of your text, and while the code you wrote is functionally equivalent, you may not have been demonstrating the particular skill you were supposed to be learning in that lesson.

How to add a spinner icon to button when it's in the Loading state?

Here's my solution for Bootstrap 4:

<button id="search" class="btn btn-primary" 
data-loading-text="<i class='fa fa-spinner fa-spin fa-fw' aria-hidden='true'></i>Searching">
  Search
</button>

var setLoading = function () {
  var search = $('#search');
  if (!search.data('normal-text')) {
    search.data('normal-text', search.html());
  }
  search.html(search.data('loading-text'));
};

var clearLoading = function () {
  var search = $('#search');
  search.html(search.data('normal-text'));
};

setInterval(() => {
  setLoading();
  setTimeout(() => {
    clearLoading();
  }, 1000);
}, 2000);

Check it out on JSFiddle

Using the slash character in Git branch name

just had the same issue, but i could not find the conflicting branch anymore.

in my case the repo had and "foo" branch before, but not anymore and i tried to create and checkout "foo/bar" from remote. As i said "foo" did not exist anymore, but the issue persisted.

In the end, the branch "foo" was still in the .git/config file, after deleting it everything was alright :)

Node.js - SyntaxError: Unexpected token import

I've been trying to get this working. Here's what works:

  1. Use a recent node version. I'm using v14.15.5. Verify your version by running: node --version
  2. Name the files so that they all end with .mjs rather than .js

Example:

mod.mjs

export const STR = 'Hello World'

test.mjs

import {STR} from './mod.mjs'
console.log(STR)

Run: node test.mjs

You should see "Hello World".

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

Many JavaScript libraries (especially non-recent ones) do not handle IE9 well because it breaks with IE8 in the handling of a lot of things.

JS code that sniffs for IE will fail quite frequently in IE9, unless such code is rewritten to handle IE9 specifically.

Before the JS code is updated, you should use the "X-UA-Compatible" meta tag to force your web page into IE8 mode.

EDIT: Can't believe that, 3 years later and we're onto IE11, and there are still up-votes for this. :-) Many JS libraries should now at least support IE9 natively and most support IE10, so it is unlikely that you'll need the meta tag these days, unless you don't intend to upgrade your JS library. But beware that IE10 changes things regarding to cross-domain scripting and some CDN-based library code breaks. Check your library version. For example, Dojo 1.9 on the CDN will break on IE10, but 1.9.1 solves it.

EDIT 2: You REALLY need to get your acts together now. We are now in mid-2014!!! I am STILL getting up-votes for this! Revise your sites to get rid of old-IE hard-coded dependencies!

Sigh... If I had known that this would be by far my most popular answer, I'd probably have spent more time polishing it...

EDIT 3: It is now almost 2016. Upvotes still ticking up... I guess there are lots of legacy code out there... One day our programs will out-live us...

Extracting the top 5 maximum values in excel

There 3 functions you want to look at here:

I ran a sample in Excel with your OPS values in Column B and Players in Column C, see below:

Excel sample

  • In Cells A13 to A17, the values 1 to 5 were inserted to specify the nth highest value.
  • In Cell B13, the following formula was added: =LARGE($B$2:$B$11, A13)
  • In Cell C13, the following formula was added: =INDEX($C$2:$C$11,MATCH(B13,$B$2:$B$11,0))
  • These formulae get the highest ranking OPS and Player based on the value in A13.
  • Simply select and drag to copy these formulae down to the next 4 cells which will reference the corresponding ranking in Column A.

The equivalent of wrap_content and match_parent in flutter?

Use FractionallySizedBox widget.

FractionallySizedBox(
  widthFactor: 1.0, // width w.r.t to parent
  heightFactor: 1.0,  // height w.r.t to parent
  child: *Your Child Here*
}

This widget is also very useful when you want to size your child at a fractional of its parent's size.

Example:

If you want the child to occupy 50% width of its parent, provide widthFactor as 0.5

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

How to use Select2 with JSON via Ajax request?

My ajax never gets fired until I wrapped the whole thing in

setTimeout(function(){ .... }, 3000);

I was using it in mounted section of Vue. it needs more time.

Django 1.7 throws django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet

Another option is that you have a duplicate entry in INSTALLED_APPS. That threw this error for two different apps I tested. Apparently it's not something Django checks for, but then who's silly enough to put the same app in the list twice. Me, that's who.

ORA-00942: table or view does not exist (works when a separate sql, but does not work inside a oracle function)

Either u dont have permission to that schema/table OR table does exist. Mostly this issue occurred if you are using other schema tables in your stored procedures. Eg. If you are running Stored Procedure from user/schema ABC and in the same PL/SQL there are tables which is from user/schema XYZ. In this case ABC should have GRANT i.e. privileges of XYZ tables

Grant All On To ABC;

Select * From Dba_Tab_Privs Where Owner = 'XYZ'and Table_Name = <Table_Name>;

How to search if dictionary value contains certain string with Python

>>> myDict
{'lastName': ['Stone', 'Lee'], 'age': ['12'], 'firstName': ['Alan', 'Mary-Ann'],
 'address': ['34 Main Street, 212 First Avenue']}

>>> Set = set()

>>> not ['' for Key, Values in myDict.items() for Value in Values if 'Mary' in Value and Set.add(Key)] and list(Set)
['firstName']

Google.com and clients1.google.com/generate_204

Google is using this to detect whether the device is online or in captive portal.

Shill, the connection manager for Chromium OS, attempts to detect services that are within a captive portal whenever a service transitions to the ready state. This determination of being in a captive portal or being online is done by attempting to retrieve the webpage http://clients3.google.com/generate_204. This well known URL is known to return an empty page with an HTTP status 204. If for any reason the web page is not returned, or an HTTP response other than 204 is received, then shill marks the service as being in the portal state.

Here is the relevant explanation from the Google Chrome Privacy Whitepaper:

In the event that Chrome detects SSL connection timeouts, certificate errors, or other network issues that might be caused by a captive portal (a hotel's WiFi network, for instance), Chrome will make a cookieless request to http://www.gstatic.com/generate_204 and check the response code. If that request is redirected, Chrome will open the redirect target in a new tab on the assumption that it's a login page. Requests to the captive portal detection page are not logged.

More info: http://www.chromium.org/chromium-os/chromiumos-design-docs/network-portal-detection

Inline SVG in CSS

I've forked a CodePen demo that had the same problem with embedding inline SVG into CSS. A solution that works with SCSS is to build a simple url-encoding function.

A string replacement function can be created from the built-in str-slice, str-index functions (see css-tricks, thanks to Hugo Giraudel).

Then, just replace %,<,>,",', with the %xxcodes:

@function svg-inline($string){
  $result: str-replace($string, "<svg", "<svg xmlns='http://www.w3.org/2000/svg'");
  $result: str-replace($result, '%', '%25');
  $result: str-replace($result, '"', '%22');
  $result: str-replace($result, "'", '%27');
  $result: str-replace($result, ' ', '%20');
  $result: str-replace($result, '<', '%3C');
  $result: str-replace($result, '>', '%3E');
  @return "data:image/svg+xml;utf8," + $result;
}

$mySVG: svg-inline("<svg>...</svg>");

html {
  height: 100vh;
  background: url($mySVG) 50% no-repeat;
}

There is also a image-inline helper function available in Compass, but since it is not supported in CodePen, this solution might probably be useful.

Demo on CodePen: http://codepen.io/terabaud/details/PZdaJo/

Python subprocess.Popen "OSError: [Errno 12] Cannot allocate memory"

swap may not be the red herring previously suggested. How big is the python process in question just before the ENOMEM?

Under kernel 2.6, /proc/sys/vm/swappiness controls how aggressively the kernel will turn to swap, and overcommit* files how much and how precisely the kernel may apportion memory with a wink and a nod. Like your facebook relationship status, it's complicated.

...but swap is actually available on demand (according to the web host)...

but not according to the output of your free(1) command, which shows no swap space recognized by your server instance. Now, your web host may certainly know much more than I about this topic, but virtual RHEL/CentOS systems I've used have reported swap available to the guest OS.

Adapting Red Hat KB Article 15252:

A Red Hat Enterprise Linux 5 system will run just fine with no swap space at all as long as the sum of anonymous memory and system V shared memory is less than about 3/4 the amount of RAM. .... Systems with 4GB of ram or less [are recommended to have] a minimum of 2GB of swap space.

Compare your /proc/sys/vm settings to a plain CentOS 5.3 installation. Add a swap file. Ratchet down swappiness and see if you live any longer.

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

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

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

How to pass data to view in Laravel?

For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way

In the controller, you define the variables you want to pass as global and you attribute the values to these variables.

Example global $variable; $variable = 1;

And now in the view, at the top, simply do

<?php global $variable;?>

Then you can now call your variable from any where in the view for example

{{$variable}}

hope this helps someone.

How can I initialize an array without knowing it size?

You can't... an array's size is always fixed in Java. Typically instead of using an array, you'd use an implementation of List<T> here - usually ArrayList<T>, but with plenty of other alternatives available.

You can create an array from the list as a final step, of course - or just change the signature of the method to return a List<T> to start with.

android listview get selected item

final ListView lv = (ListView) findViewById(R.id.ListView01);

lv.setOnItemClickListener(new OnItemClickListener() {
      public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
        String selectedFromList =(String) (lv.getItemAtPosition(myItemInt));

      }                 
});

I hope this fixes your problem.

Bootstrap 3 breakpoints and media queries

for bootstrap 3 I have the following code in my navbar component

/**
 * Navbar styling.
 */
@mobile:          ~"screen and (max-width: @{screen-xs-max})";
@tablet:          ~"screen and (min-width: @{screen-sm-min})";
@normal:          ~"screen and (min-width: @{screen-md-min})";
@wide:            ~"screen and (min-width: @{screen-lg-min})";
@grid-breakpoint: ~"screen and (min-width: @{grid-float-breakpoint})";

then you can use something like

@media wide { selector: style }

This uses whatever value you have the variables set to.

Escaping allows you to use any arbitrary string as property or variable value. Anything inside ~"anything" or ~'anything' is used as is with no changes except interpolation.

http://lesscss.org

Empty ArrayList equals null

No, because it contains items there must be an instance of it. Its items being null is irrelevant, so the statment ((arrayList) != null) == true

bash assign default value

The default value parameter expansion is often useful in build scripts like the example one below. If the user just calls the script as-is, perl will not be built in. The user has to explicitly set WITH_PERL to a value other than "no" to have it built in.

$ cat defvar.sh
#!/bin/bash

WITH_PERL=${WITH_PERL:-no}

if [[ "$WITH_PERL" != no ]]; then
    echo "building with perl"
    # ./configure --enable=perl
else
    echo "not building with perl"
    # ./configure
fi

Build without Perl

$ ./defvar.sh
not building with perl

Build with Perl

$ WITH_PERL=yes ./defvar.sh
building with perl

`&mdash;` or `&#8212;` is there any difference in HTML output?

SGML parsers (or XML parsers in the case of XHTML) can handle &#8212; without having to process the DTD (which doesn't matter to browsers as they just slurp tag soup), while &mdash; is easier for humans to read and write in the source code.

Personally, I would stick to a literal em-dash and ensure that my character encoding settings were consistent.

Sending a notification from a service in Android

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void PushNotification()
{
    NotificationManager nm = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
    Notification.Builder builder = new Notification.Builder(context);
    Intent notificationIntent = new Intent(context, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(context,0,notificationIntent,0);

    //set
    builder.setContentIntent(contentIntent);
    builder.setSmallIcon(R.drawable.cal_icon);
    builder.setContentText("Contents");
    builder.setContentTitle("title");
    builder.setAutoCancel(true);
    builder.setDefaults(Notification.DEFAULT_ALL);

    Notification notification = builder.build();
    nm.notify((int)System.currentTimeMillis(),notification);
}

How to write lists inside a markdown table?

An alternative approach, which I've recently implemented, is to use the div-table plugin with panflute.

This creates a table from a set of fenced divs (standard in the pandoc implementation of markdown), in a similar layout to html:

---
panflute-filters: [div-table]
panflute-path: 'panflute/docs/source'
---

::::: {.divtable}
:::: {.tcaption}
a caption here (optional), only the first paragraph is used.
::::
:::: {.thead}
[Header 1]{width=0.4 align=center}
[Header 2]{width=0.6 align=default}
::::
:::: {.trow}
::: {.tcell}

1. any
2. normal markdown
3. can go in a cell

:::
::: {.tcell}
![](https://pixabay.com/get/e832b60e2cf7043ed1584d05fb0938c9bd22ffd41cb2144894f9c57aae/bird-1771435_1280.png?attachment){width=50%}

some text
:::
::::
:::: {.trow bypara=true}
If bypara=true

Then each paragraph will be treated as a separate column
::::
any text outside a div will be ignored
:::::

Looks like:

enter image description here

Create request with POST, which response codes 200 or 201 and content

I think atompub REST API is a great example of a restful service. See the snippet below from the atompub spec:

POST /edit/ HTTP/1.1
Host: example.org
User-Agent: Thingio/1.0
Authorization: Basic ZGFmZnk6c2VjZXJldA==
Content-Type: application/atom+xml;type=entry
Content-Length: nnn
Slug: First Post

<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>Atom-Powered Robots Run Amok</title>
  <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
  <updated>2003-12-13T18:30:02Z</updated>
  <author><name>John Doe</name></author>
  <content>Some text.</content>
</entry>

The server signals a successful creation with a status code of 201. The response includes a Location header indicating the Member Entry URI of the Atom Entry, and a representation of that Entry in the body of the response.

HTTP/1.1 201 Created
Date: Fri, 7 Oct 2005 17:17:11 GMT
Content-Length: nnn
Content-Type: application/atom+xml;type=entry;charset="utf-8"
Location: http://example.org/edit/first-post.atom
ETag: "c180de84f991g8"  

<?xml version="1.0"?>
<entry xmlns="http://www.w3.org/2005/Atom">
  <title>Atom-Powered Robots Run Amok</title>
  <id>urn:uuid:1225c695-cfb8-4ebb-aaaa-80da344efa6a</id>
  <updated>2003-12-13T18:30:02Z</updated>
  <author><name>John Doe</name></author>
  <content>Some text.</content>
  <link rel="edit"
      href="http://example.org/edit/first-post.atom"/>
</entry>

The Entry created and returned by the Collection might not match the Entry POSTed by the client. A server MAY change the values of various elements in the Entry, such as the atom:id, atom:updated, and atom:author values, and MAY choose to remove or add other elements and attributes, or change element content and attribute values.

Iterating on a file doesn't work the second time

As the file object reads the file, it uses a pointer to keep track of where it is. If you read part of the file, then go back to it later it will pick up where you left off. If you read the whole file, and go back to the same file object, it will be like reading an empty file because the pointer is at the end of the file and there is nothing left to read. You can use file.tell() to see where in the file the pointer is and file.seek to set the pointer. For example:

>>> file = open('myfile.txt')
>>> file.tell()
0
>>> file.readline()
'one\n'
>>> file.tell()
4L
>>> file.readline()
'2\n'
>>> file.tell()
6L
>>> file.seek(4)
>>> file.readline()
'2\n'

Also, you should know that file.readlines() reads the whole file and stores it as a list. That's useful to know because you can replace:

for line in file.readlines():
    #do stuff
file.seek(0)
for line in file.readlines():
    #do more stuff

with:

lines = file.readlines()
for each_line in lines:
    #do stuff
for each_line in lines:
    #do more stuff

You can also iterate over a file, one line at a time, without holding the whole file in memory (this can be very useful for very large files) by doing:

for line in file:
    #do stuff

Java Garbage Collection Log messages

Most of it is explained in the GC Tuning Guide (which you would do well to read anyway).

The command line option -verbose:gc causes information about the heap and garbage collection to be printed at each collection. For example, here is output from a large server application:

[GC 325407K->83000K(776768K), 0.2300771 secs]
[GC 325816K->83372K(776768K), 0.2454258 secs]
[Full GC 267628K->83769K(776768K), 1.8479984 secs]

Here we see two minor collections followed by one major collection. The numbers before and after the arrow (e.g., 325407K->83000K from the first line) indicate the combined size of live objects before and after garbage collection, respectively. After minor collections the size includes some objects that are garbage (no longer alive) but that cannot be reclaimed. These objects are either contained in the tenured generation, or referenced from the tenured or permanent generations.

The next number in parentheses (e.g., (776768K) again from the first line) is the committed size of the heap: the amount of space usable for java objects without requesting more memory from the operating system. Note that this number does not include one of the survivor spaces, since only one can be used at any given time, and also does not include the permanent generation, which holds metadata used by the virtual machine.

The last item on the line (e.g., 0.2300771 secs) indicates the time taken to perform the collection; in this case approximately a quarter of a second.

The format for the major collection in the third line is similar.

The format of the output produced by -verbose:gc is subject to change in future releases.

I'm not certain why there's a PSYoungGen in yours; did you change the garbage collector?

C++ template constructor

You could do this:

class C 
{
public:
    template <typename T> C(T*);
};
template <typename T> T* UseType() 
{
    static_cast<T*>(nullptr);
}

Then to create an object of type C using int as the template parameter to the constructor:

C obj(UseType<int>());

Since you can't pass template parameters to a constructor, this solution essentially converts the template parameter to a regular parameter. Using the UseType<T>() function when calling the constructor makes it clear to someone looking at the code that the purpose of that parameter is to tell the constructor what type to use.

One use case for this would be if the constructor creates a derived class object and assigns it to a member variable that is a base class pointer. (The constructor needs to know which derived class to use, but the class itself doesn't need to be templated since the same base class pointer type is always used.)

How do I create a nice-looking DMG for Mac OS X using command-line tools?

Bringing this question up to date by providing this answer.

appdmg is a simple, easy-to-use, open-source command line program that creates dmg-files from a simple json specification. Take a look at the readme at the official website:

https://github.com/LinusU/node-appdmg

Quick example:

  1. Install appdmg

    npm install -g appdmg
    
  2. Write a json file (spec.json)

    {
      "title": "Test Title",
      "background": "background.png",
      "icon-size": 80,
      "contents": [
        { "x": 192, "y": 344, "type": "file", "path": "TestApp.app" },
        { "x": 448, "y": 344, "type": "link", "path": "/Applications" }
      ]
    }
    
  3. Run program

    appdmg spec.json test.dmg
    

(disclaimer. I'm the creator of appdmg)

Spool Command: Do not output SQL statement to file

Unfortunately SQL Developer doesn't fully honour the set echo off command that would (appear to) solve this in SQL*Plus.

The only workaround I've found for this is to save what you're doing as a script, e.g. test.sql with:

set echo off
spool c:\test.csv 
select /*csv*/ username, user_id, created from all_users;
spool off;

And then from SQL Developer, only have a call to that script:

@test.sql

And run that as a script (F5).

Saving as a script file shouldn't be much of a hardship anyway for anything other than an ad hoc query; and running that with @ instead of opening the script and running it directly is only a bit of a pain.


A bit of searching found the same solution on the SQL Developer forum, and the development team suggest it's intentional behaviour to mimic what SQL*Plus does; you need to run a script with @ there too in order to hide the query text.

hibernate - get id after save object

Let's say your primary key is an Integer and the object you save is "ticket", then you can get it like this. When you save the object, a Serializable id is always returned

Integer id = (Integer)session.save(ticket);

Get content of a DIV using JavaScript

simply you can use jquery plugin to get/set the content of the div.

var divContent = $('#'DIV1).html(); $('#'DIV2).html(divContent );

for this you need to include jquery library.

What does "Changes not staged for commit" mean

Follow the steps below:

1- git stash
2- git add .
3- git commit -m "your commit message"

How do you determine what technology a website is built on?

You can use domaintools.com to lookup the server information for a website and narrow down to whether it's open source / Microsoft:

http://whois.domaintools.com/stackoverflow.com

And after that it's a matter of looking in the footer for tip-offs such as "Powered by WordPress" or "vBulletin" etc.

JSON to TypeScript class instance?

Why could you not just do something like this?

class Foo {
  constructor(myObj){
     Object.assign(this, myObj);
  }
  get name() { return this._name; }
  set name(v) { this._name = v; }
}

let foo = new Foo({ name: "bat" });
foo.toJSON() //=> your json ...

How permission can be checked at runtime without throwing SecurityException?

if ((ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) && (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)) {

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

        requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA},
                MY_PERMISSIONS_REQUEST_WRITE_EXTERNAL_STORAGE);
    }
} 

How do I get the MAX row with a GROUP BY in LINQ query?

The answers are OK if you only require those two fields, but for a more complex object, maybe this approach could be useful:

from x in db.Serials 
group x by x.Serial_Number into g 
orderby g.Key 
select g.OrderByDescending(z => z.uid)
.FirstOrDefault()

... this will avoid the "select new"

How do I search for an object by its ObjectId in the mongo console?

In MongoDB Stitch functions it can be done using BSON like below:

Use the ObjectId helper in the BSON utility package for this purpose like in the follwing example:

var id = "5bb9e9f84186b222c8901149";  
BSON.ObjectId(id);

How to use group by with union in t-sql

Identifying the column is easy:

SELECT  *
FROM    ( SELECT    id,
                    time
          FROM      dbo.a
          UNION
          SELECT    id,
                    time
          FROM      dbo.b
        )
GROUP BY id

But it doesn't solve the main problem of this query: what's to be done with the second column values upon grouping by the first? Since (peculiarly!) you're using UNION rather than UNION ALL, you won't have entirely duplicated rows between the two subtables in the union, but you may still very well have several values of time for one value of the id, and you give no hint of what you want to do - min, max, avg, sum, or what?! The SQL engine should give an error because of that (though some such as mysql just pick a random-ish value out of the several, I believe sql-server is better than that).

So, for example, change the first line to SELECT id, MAX(time) or the like!

Python CSV error: line contains NULL byte

For all those 'rU' filemode haters: I just tried opening a CSV file from a Windows machine on a Mac with the 'rb' filemode and I got this error from the csv module:

Error: new-line character seen in unquoted field - do you need to 
open the file in universal-newline mode?

Opening the file in 'rU' mode works fine. I love universal-newline mode -- it saves me so much hassle.

Swift Alamofire: How to get the HTTP response status code

For Swift 3.x / Swift 4.0 / Swift 5.0 users with Alamofire >= 5.0

Used request modifier to increase and decrease the timeout interval.

Alamofire's request creation methods offer the most common parameters for customization but sometimes those just aren't enough. The URLRequests created from the passed values can be modified by using a RequestModifier closure when creating requests. For example, to set the URLRequest's timeoutInterval to 120 seconds, modify the request in the closure.

var manager = Session.default
 manager.request(urlString, method: method, parameters: dict, headers: headers, requestModifier: { $0.timeoutInterval = 120 }).validate().responseJSON { response in

OR

RequestModifiers also work with trailing closure syntax.

var manager = Session.default
     manager.request("https://httpbin.org/get") { urlRequest in
    urlRequest.timeoutInterval = 60
    urlRequest.allowsConstrainedNetworkAccess = false
}
.response(...)

How to rename a file using svn?

The behaviour differs depending on whether the target file name already exists or not. It's usually a safety mechanism, and there are at least 3 different cases:

Target file does not exist:

In this case svn mv should work as follows:

$ svn mv old_file_name new_file_name
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding     new_file_name
Deleting   old_file_name
Committing transaction...

Target file already exists in repository:

In this case, the target file needs to be removed explicitly, before the source file can be renamed. This can be done in the same transaction as follows:

$ svn mv old_file_name new_file_name 
svn: E155010: Path 'new_file_name' is not a directory
$ svn rm new_file_name 
D         new_file_name
$ svn mv old_file_name new_file_name 
A         new_file_name
D         old_file_name
$ svn stat
R  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Replacing      new_file_name
Deleting       old_file_name
Committing transaction...

In the output of svn stat, the R indicates that the file has been replaced, and that the file has a history.

Target file already exists locally (unversioned):

In this case, the content of the local file would be lost. If that's okay, then the file can be removed locally before renaming the existing file.

$ svn mv old_file_name new_file_name 
svn: E155010: Path 'new_file_name' is not a directory
$ rm new_file_name 
$ svn mv old_file_name new_file_name 
A         new_file_name
D         old_file_name
$ svn stat
A  +    new_file_name
        > moved from old_file_name
D       old_file_name
        > moved to new_file_name
$ svn commit
Adding         new_file_name
Deleting       old_file_name
Committing transaction...

Accessing Imap in C#

I haven't tried it myself, but this is a free library you could try (I not so sure about the SSL part on this one):

http://www.codeproject.com/KB/IP/imaplibrary.aspx

Also, there is xemail, which has parameters for SSL:

http://xemail-net.sourceforge.net/

[EDIT] If you (or the client) have the money for a professional mail-client, this thread has some good recommendations:

Recommendations for a .NET component to access an email inbox

How do I combine 2 javascript variables into a string

Use the concatenation operator +, and the fact that numeric types will convert automatically into strings:

var a = 1;
var b = "bob";
var c = b + a;

How do I get a human-readable file size in bytes abbreviation using .NET?

I use the Long extension method below to convert to a human readable size string. This method is the C# implementation of the Java solution of this same question posted on Stack Overflow, here.

/// <summary>
/// Convert a byte count into a human readable size string.
/// </summary>
/// <param name="bytes">The byte count.</param>
/// <param name="si">Whether or not to use SI units.</param>
/// <returns>A human readable size string.</returns>
public static string ToHumanReadableByteCount(
    this long bytes
    , bool si
)
{
    var unit = si
        ? 1000
        : 1024;

    if (bytes < unit)
    {
        return $"{bytes} B";
    }

    var exp = (int) (Math.Log(bytes) / Math.Log(unit));

    return $"{bytes / Math.Pow(unit, exp):F2} " +
           $"{(si ? "kMGTPE" : "KMGTPE")[exp - 1] + (si ? string.Empty : "i")}B";
}

Get an element by index in jQuery

There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:

<script>
    // css selector that describes what you need:
    // ul li:nth-of-type(3)
    var selector = 'ul li:nth-of-type(' + index + ')';
    $(selector).css({'background-color':'#343434'});
</script>

There are other selectors that you may use with jQuery to match any element that you need.

What is makeinfo, and how do I get it?

On SuSE linux, you can use the following command to install 'texinfo':

sudo zypper install texinfo

On my system, it shows it is downloading about 1000 MiB, so make sure you have enough free space.

How to convert a file to utf-8 in Python?

Thanks for the replies, it works!

And since the source files are in mixed formats, I added a list of source formats to be tried in sequence (sourceFormats), and on UnicodeDecodeError I try the next format:

from __future__ import with_statement

import os
import sys
import codecs
from chardet.universaldetector import UniversalDetector

targetFormat = 'utf-8'
outputDir = 'converted'
detector = UniversalDetector()

def get_encoding_type(current_file):
    detector.reset()
    for line in file(current_file):
        detector.feed(line)
        if detector.done: break
    detector.close()
    return detector.result['encoding']

def convertFileBestGuess(filename):
   sourceFormats = ['ascii', 'iso-8859-1']
   for format in sourceFormats:
     try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
      except UnicodeDecodeError:
        pass

def convertFileWithDetection(fileName):
    print("Converting '" + fileName + "'...")
    format=get_encoding_type(fileName)
    try:
        with codecs.open(fileName, 'rU', format) as sourceFile:
            writeConversion(sourceFile)
            print('Done.')
            return
    except UnicodeDecodeError:
        pass

    print("Error: failed to convert '" + fileName + "'.")


def writeConversion(file):
    with codecs.open(outputDir + '/' + fileName, 'w', targetFormat) as targetFile:
        for line in file:
            targetFile.write(line)

# Off topic: get the file list and call convertFile on each file
# ...

(EDIT by Rudro Badhon: this incorporates the original try multiple formats until you don't get an exception as well as an alternate approach that uses chardet.universaldetector)

CodeIgniter: Create new helper?

Some code that allows you to use CI instance inside the helper:

function yourHelperFunction(){
    $ci=& get_instance();
    $ci->load->database(); 

    $sql = "select * from table"; 
    $query = $ci->db->query($sql);
    $row = $query->result();
}

How to use session in JSP pages to get information?

The reason why you are getting the compilation error is, you are trying to access the session in declaration block (<%! %>) where it is not available. All the implicit objects of jsp are available in service method only. Code of declarative blocks goes outside the service method.

I'd advice you to use EL. It is a simplified approach.

${sessionScope.username} would give you the desired output.

How to cast or convert an unsigned int to int in C?

It's as simple as this:

unsigned int foo;
int bar = 10;

foo = (unsigned int)bar;

Or vice versa...

Use PHP to convert PNG to JPG with compression?

Do this to convert safely a PNG to JPG with the transparency in white.

$image = imagecreatefrompng($filePath);
$bg = imagecreatetruecolor(imagesx($image), imagesy($image));
imagefill($bg, 0, 0, imagecolorallocate($bg, 255, 255, 255));
imagealphablending($bg, TRUE);
imagecopy($bg, $image, 0, 0, 0, 0, imagesx($image), imagesy($image));
imagedestroy($image);
$quality = 50; // 0 = worst / smaller file, 100 = better / bigger file 
imagejpeg($bg, $filePath . ".jpg", $quality);
imagedestroy($bg);

What is CMake equivalent of 'configure --prefix=DIR && make all install '?

Note that in both CMake and Autotools you don't always have to set the installation path at configure time. You can use DESTDIR at install time (see also here) instead as in:

make DESTDIR=<installhere> install

See also this question which explains the subtle difference between DESTDIR and PREFIX.

This is intended for staged installs and to allow for storing programs in a different location from where they are run e.g. /etc/alternatives via symbolic links.

However, if your package is relocatable and doesn't need any hard-coded (prefix) paths set via the configure stage you may be able to skip it. So instead of:

cmake -DCMAKE_INSTALL_PREFIX=/usr . && make all install

you would run:

cmake . && make DESTDIR=/usr all install

Note that, as user7498341 points out, this is not appropriate for cases where you really should be using PREFIX.

How to stop an unstoppable zombie job on Jenkins without restarting the server?

Without having to use the script console or additional plugins, you can simply abort a build by entering /stop, /term, or /kill after the build URL in your browser.

Quoting verbatim from the above link:

Pipeline jobs can by stopped by sending an HTTP POST request to URL endpoints of a build.

  • <BUILD ID URL>/stop - aborts a Pipeline.
  • <BUILD ID URL>/term - forcibly terminates a build (should only be used if stop does not work.
  • <BUILD ID URL>/kill - hard kill a pipeline. This is the most destructive way to stop a pipeline and should only be used as a last resort.

Simulate low network connectivity for Android

This may sound a little crazy, but a microwave oven serves as a microwave shield. Therefore, putting your device inside a microwave oven (DO NOT turn on the microwave oven while your device is inside!) will cause your signal strength to drop significantly. It definitely beats standing inside an elevator...

Getting a File's MD5 Checksum in Java

public static String MD5Hash(String toHash) throws RuntimeException {
   try{
       return String.format("%032x", // produces lower case 32 char wide hexa left-padded with 0
      new BigInteger(1, // handles large POSITIVE numbers 
           MessageDigest.getInstance("MD5").digest(toHash.getBytes())));
   }
   catch (NoSuchAlgorithmException e) {
      // do whatever seems relevant
   }
}

What is the difference between "word-break: break-all" versus "word-wrap: break-word" in CSS

With word-break, a very long word starts at the point it should start and it is being broken as long as required

[X] I am a text that 0123
4567890123456789012345678
90123456789 want to live 
inside this narrow paragr
aph.

However, with word-wrap, a very long word WILL NOT start at the point it should start. it wrap to next line and then being broken as long as required

[X] I am a text that 
012345678901234567890123
4567890123456789 want to
live inside this narrow 
paragraph.

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

Try:

SELECT convert(nvarchar(10), SA.[RequestStartDate], 103) as 'Service Start Date', 
       convert(nvarchar(10), SA.[RequestEndDate], 103) as 'Service End Date', 
FROM
(......)SA
WHERE......

Or:

SELECT format(SA.[RequestStartDate], 'dd/MM/yyyy') as 'Service Start Date', 
       format(SA.[RequestEndDate], 'dd/MM/yyyy') as 'Service End Date', 
FROM
(......)SA
WHERE......

setting textColor in TextView in layout/main.xml main layout file not referencing colors.xml file. (It wants a #RRGGBB instead of @color/text_color)

You have a typo in your xml; it should be:

android:textColor="@color/text_color"

that's "@color" without the 's'.

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);
}

Uncaught TypeError: undefined is not a function on loading jquery-min.js

Assuming this problem still has not be resolved, a lot of individual files don't end their code with a semicolon. Most jQuery scripts end with (jQuery) and you need to have (jQuery);.

As separate files the script will load just fine but as one individual file you need the semicolons.

How do I bind a WPF DataGrid to a variable number of columns?

I've continued my research and have not found any reasonable way to do this. The Columns property on the DataGrid isn't something I can bind against, in fact it's read only.

Bryan suggested something might be done with AutoGenerateColumns so I had a look. It uses simple .Net reflection to look at the properties of the objects in ItemsSource and generates a column for each one. Perhaps I could generate a type on the fly with a property for each column but this is getting way off track.

Since this problem is so easily sovled in code I will stick with a simple extension method I call whenever the data context is updated with new columns:

public static void GenerateColumns(this DataGrid dataGrid, IEnumerable<ColumnSchema> columns)
{
    dataGrid.Columns.Clear();

    int index = 0;
    foreach (var column in columns)
    {
        dataGrid.Columns.Add(new DataGridTextColumn
        {
            Header = column.Name,
            Binding = new Binding(string.Format("[{0}]", index++))
        });
    }
}

// E.g. myGrid.GenerateColumns(schema);

SELECT only rows that contain only alphanumeric characters in MySQL

There is also this:

select m from table where not regexp_like(m, '^[0-9]\d+$')

which selects the rows that contains characters from the column you want (which is m in the example but you can change).

Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.

How to get element's width/height within directives and component?

You can use ElementRef as shown below,

DEMO : https://plnkr.co/edit/XZwXEh9PZEEVJpe0BlYq?p=preview check browser's console.

import { Directive,Input,Outpu,ElementRef,Renderer} from '@angular/core';

@Directive({
  selector:"[move]",
  host:{
    '(click)':"show()"
  }
})

export class GetEleDirective{

  constructor(private el:ElementRef){

  }
  show(){
    console.log(this.el.nativeElement);

    console.log('height---' + this.el.nativeElement.offsetHeight);  //<<<===here
    console.log('width---' + this.el.nativeElement.offsetWidth);    //<<<===here
  }
}

Same way you can use it within component itself wherever you need it.

How to extract or unpack an .ab file (Android Backup file)

As per https://android.stackexchange.com/a/78183/239063 you can run a one line command in Linux to add in an appropriate tar header to extract it.

( printf "\x1f\x8b\x08\x00\x00\x00\x00\x00" ; tail -c +25 backup.ab ) | tar xfvz -

Replace backup.ab with the path to your file.

Add a thousands separator to a total with Javascript or jQuery?

Use toLocaleString()
In your case do:

return "Total Pounds Entered : " + tot.toLocaleString(); 

PHP - add 1 day to date format mm-dd-yyyy

Actually I wanted same alike thing, To get one year backward date, for a given date! :-)

With the hint of above answer from @mohammad mohsenipur I got to the following link, via his given link!

Luckily, there is a method same as date_add method, named date_sub method! :-) I do the following to get done what I wanted!

$date = date_create('2000-01-01');
date_sub($date, date_interval_create_from_date_string('1 years'));
echo date_format($date, 'Y-m-d');

Hopes this answer will help somebody too! :-)

Good luck guys!

How to generate Javadoc HTML files in Eclipse?

  1. Project > Generate Javadoc....

  2. In the Javadoc command: field, browse to find javadoc.exe (usually at [path_to_jdk_directory]\bin\javadoc.exe).

  3. Check the box next to the project/package/file for which you are creating the Javadoc.

  4. In the Destination: field, browse to find the desired destination (for example, the root directory of the current project).

  5. Click Finish.

You should now be able to find the newly generated Javadoc in the destination folder. Open index.html.

What is the difference between Subject and BehaviorSubject?

BehaviourSubject

BehaviourSubject will return the initial value or the current value on Subscription

var bSubject= new Rx.BehaviorSubject(0);  // 0 is the initial value

bSubject.subscribe({
  next: (v) => console.log('observerA: ' + v)  // output initial value, then new values on `next` triggers
});

bSubject.next(1);  // output new value 1 for 'observer A'
bSubject.next(2);  // output new value 2 for 'observer A', current value 2 for 'Observer B' on subscription

bSubject.subscribe({
  next: (v) => console.log('observerB: ' + v)  // output current value 2, then new values on `next` triggers
});

bSubject.next(3);

With output:

observerA: 0
observerA: 1
observerA: 2
observerB: 2
observerA: 3
observerB: 3

Subject

Subject does not return the current value on Subscription. It triggers only on .next(value) call and return/output the value

var subject = new Rx.Subject();

subject.next(1); //Subjects will not output this value

subject.subscribe({
  next: (v) => console.log('observerA: ' + v)
});
subject.subscribe({
  next: (v) => console.log('observerB: ' + v)
});

subject.next(2);
subject.next(3);

With the following output on the console:

observerA: 2
observerB: 2
observerA: 3
observerB: 3

No found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations:

I missed to add

@Controller("userBo") into UserBoImpl class.

The solution for this is adding this controller into Impl class.

How to read input from console in a batch file?

In addition to the existing answer it is possible to set a default option as follows:

echo off
ECHO A current build of Test Harness exists.
set delBuild=n
set /p delBuild=Delete preexisting build [y/n] (default - %delBuild%)?:

This allows users to simply hit "Enter" if they want to enter the default.

How to host google web fonts on my own server?

You can download source fonts from https://github.com/google/fonts

After that use font-ranger tool to split your large Unicode font into multiple subsets (e.g. latin, cyrillic). You should do the following with the tool:

  • Generate subsets for each language you support
  • Use unicode-range subsetting for saving bandwidth
  • Remove bloat from your fonts and optimize them for web
  • Convert your fonts to a compressed woff2 format
  • Provide .woff fallback for older browsers
  • Customize font loading and rendering
  • Generate CSS file with @font-face rules
  • Self-host web fonts or use them locally

Font-Ranger: https://www.npmjs.com/package/font-ranger

P.S. You can also automate this using Node.js API

How to resolve "Waiting for Debugger" message?

For Android Studio users I encountered this problem first time while trying to run a bare bone project just after updating my jdk location. So I stumbled across this post. In my case simple Build->Clean Project did the job.

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

I render context path to attribute of link tag with id="contextPahtHolder" and then obtain it in JS code. For example:

<html>
    <head>
        <link id="contextPathHolder" data-contextPath="${pageContext.request.contextPath}"/>
    <body>
        <script src="main.js" type="text/javascript"></script>
    </body>
</html>

main.js

var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
$.get(CONTEXT_PATH + '/action_url', function() {});

If context path is empty (like in embedded servlet container istance), it will be empty string. Otherwise it contains contextPath string

How to create EditText with rounded corners?

Just to add to the other answers, I found that the simplest solution to achieve the rounded corners was to set the following as a background to your Edittext.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid android:color="@android:color/white"/>
    <corners android:radius="8dp"/>

</shape>

How to use PrimeFaces p:fileUpload? Listener method is never invoked or UploadedFile is null / throws an error / not usable

bean.xhtml

    <h:form enctype="multipart/form-data">    
<p:outputLabel value="Choose your file" for="submissionFile" />
                <p:fileUpload id="submissionFile"
                    value="#{bean.file}"
                    fileUploadListener="#{bean.uploadFile}" mode="advanced"
                    auto="true" dragDropSupport="false" update="messages"
                    sizeLimit="100000" fileLimit="1" allowTypes="/(\.|\/)(pdf)$/" />

</h:form>

Bean.java

@ManagedBean

@ViewScoped public class Submission implements Serializable {

private UploadedFile file;

//Gets
//Sets

public void uploadFasta(FileUploadEvent event) throws FileNotFoundException, IOException, InterruptedException {

    String content = IOUtils.toString(event.getFile().getInputstream(), "UTF-8");

    String filePath = PATH + "resources/submissions/" + nameOfMyFile + ".pdf";

    MyFileWriter.writeFile(filePath, content);

    FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO,
            event.getFile().getFileName() + " is uploaded.", null);
    FacesContext.getCurrentInstance().addMessage(null, message);

}

}

web.xml

    <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<filter>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>PrimeFaces FileUpload Filter</filter-name>
    <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

How to check if a table exists in a given schema

Perhaps use information_schema:

SELECT EXISTS(
    SELECT * 
    FROM information_schema.tables 
    WHERE 
      table_schema = 'company3' AND 
      table_name = 'tableincompany3schema'
);

How to determine whether a given Linux is 32 bit or 64 bit?

I was wondering about this specifically for building software in Debian (the installed Debian system can be a 32-bit version with a 32 bit kernel, libraries, etc., or it can be a 64-bit version with stuff compiled for the 64-bit rather than 32-bit compatibility mode).

Debian packages themselves need to know what architecture they are for (of course) when they actually create the package with all of its metadata, including platform architecture, so there is a packaging tool that outputs it for other packaging tools and scripts to use, called dpkg-architecture. It includes both what it's configured to build for, as well as the current host. (Normally these are the same though.) Example output on a 64-bit machine:

DEB_BUILD_ARCH=amd64
DEB_BUILD_ARCH_OS=linux
DEB_BUILD_ARCH_CPU=amd64
DEB_BUILD_GNU_CPU=x86_64
DEB_BUILD_GNU_SYSTEM=linux-gnu
DEB_BUILD_GNU_TYPE=x86_64-linux-gnu
DEB_HOST_ARCH=amd64
DEB_HOST_ARCH_OS=linux
DEB_HOST_ARCH_CPU=amd64
DEB_HOST_GNU_CPU=x86_64
DEB_HOST_GNU_SYSTEM=linux-gnu
DEB_HOST_GNU_TYPE=x86_64-linux-gnu

You can print just one of those variables or do a test against their values with command line options to dpkg-architecture.

I have no idea how dpkg-architecture deduces the architecture, but you could look at its documentation or source code (dpkg-architecture and much of the dpkg system in general are Perl).

What should be the package name of android app?

Android follows the same naming conventions like Java,

Naming Conventions

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.

Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.

Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).

Packages in the Java language itself begin with java. or javax.

In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:

Legalizing Package Names:

       Domain Name                            Package Name Prefix

hyphenated-name.example.org             org.example.hyphenated_name
example.int                             int_.example
123name.example.com                     com.example._123name

Stop all active ajax requests in jQuery

Throwing my hat in. Offers abort and remove methods against the xhrPool array, and is not prone to issues with ajaxSetup overrides.

/**
 * Ajax Request Pool
 * 
 * @author Oliver Nassar <[email protected]>
 * @see    http://stackoverflow.com/questions/1802936/stop-all-active-ajax-requests-in-jquery
 */
jQuery.xhrPool = [];

/**
 * jQuery.xhrPool.abortAll
 * 
 * Retrieves all the outbound requests from the array (since the array is going
 * to be modified as requests are aborted), and then loops over each of them to
 * perform the abortion. Doing so will trigger the ajaxComplete event against
 * the document, which will remove the request from the pool-array.
 * 
 * @access public
 * @return void
 */
jQuery.xhrPool.abortAll = function() {
    var requests = [];
    for (var index in this) {
        if (isFinite(index) === true) {
            requests.push(this[index]);
        }
    }
    for (index in requests) {
        requests[index].abort();
    }
};

/**
 * jQuery.xhrPool.remove
 * 
 * Loops over the requests, removes it once (and if) found, and then breaks out
 * of the loop (since nothing else to do).
 * 
 * @access public
 * @param  Object jqXHR
 * @return void
 */
jQuery.xhrPool.remove = function(jqXHR) {
    for (var index in this) {
        if (this[index] === jqXHR) {
            jQuery.xhrPool.splice(index, 1);
            break;
        }
    }
};

/**
 * Below events are attached to the document rather than defined the ajaxSetup
 * to prevent possibly being overridden elsewhere (presumably by accident).
 */
$(document).ajaxSend(function(event, jqXHR, options) {
    jQuery.xhrPool.push(jqXHR);
});
$(document).ajaxComplete(function(event, jqXHR, options) {
    jQuery.xhrPool.remove(jqXHR);
});

commands not found on zsh

Best solution work for me for permanent change path

Open Finder-> go to folder /Users/ /usr/local/bin

open .zshrc with TextEdit

.zshrc is hidden file so unhide it by command+shift+. press

delete file content and type

export PATH=~/usr/bin:/bin:/usr/sbin:/sbin:$PATH

and save

now

zsh: command not found Gone

Create a Path from String in Java7

Even when the question is regarding Java 7, I think it adds value to know that from Java 11 onward, there is a static method in Path class that allows to do this straight away:

With all the path in one String:

Path.of("/tmp/foo");

With the path broken down in several Strings:

Path.of("/tmp","foo");

How to vertically align text with icon font?

vertical-align can take a unit value so you can resort to that when needed:

{
  display:inline-block;
  vertical-align: 5px;
}

{
  display:inline-block;
  vertical-align: -5px;
}

Are there any SHA-256 javascript implementations that are generally considered trustworthy?

For those interested, this is code for creating SHA-256 hash using sjcl:

import sjcl from 'sjcl'

const myString = 'Hello'
const myBitArray = sjcl.hash.sha256.hash(myString)
const myHash = sjcl.codec.hex.fromBits(myBitArray)

How do you define a class of constants in Java?

Or 4. Put them in the class that contains the logic that uses the constants the most

... sorry, couldn't resist ;-)

&& (AND) and || (OR) in IF statements

Yes, the short-circuit evaluation for boolean expressions is the default behaviour in all the C-like family.

An interesting fact is that Java also uses the & and | as logic operands (they are overloaded, with int types they are the expected bitwise operations) to evaluate all the terms in the expression, which is also useful when you need the side-effects.

How do you check whether a number is divisible by another number (Python)?

This code appears to do what you are asking for.

for value in range(1,1000):
    if value % 3 == 0 or value % 5 == 0:
        print(value)

Or something like

for value in range(1,1000):
    if value % 3 == 0 or value % 5 == 0:
        some_list.append(value)

Or any number of things.

MySQL count occurrences greater than 2

SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1

Select all where [first letter starts with B]

Following your comment posted to ceejayoz's answer, two things are messed up a litte:

  1. $first is not an array, it's a string. Replace $first = $first[0] . "%" by $first .= "%". Just for simplicity. (PHP string operators)

  2. The string being compared with LIKE operator should be quoted. Replace LIKE ".$first."") by LIKE '".$first."'"). (MySQL String Comparison Functions)

Callback after all asynchronous forEach callbacks are completed

Array.forEach does not provide this nicety (oh if it would) but there are several ways to accomplish what you want:

Using a simple counter

function callback () { console.log('all done'); }

var itemsProcessed = 0;

[1, 2, 3].forEach((item, index, array) => {
  asyncFunction(item, () => {
    itemsProcessed++;
    if(itemsProcessed === array.length) {
      callback();
    }
  });
});

(thanks to @vanuan and others) This approach guarantees that all items are processed before invoking the "done" callback. You need to use a counter that gets updated in the callback. Depending on the value of the index parameter does not provide the same guarantee, because the order of return of the asynchronous operations is not guaranteed.

Using ES6 Promises

(a promise library can be used for older browsers):

  1. Process all requests guaranteeing synchronous execution (e.g. 1 then 2 then 3)

    function asyncFunction (item, cb) {
      setTimeout(() => {
        console.log('done with', item);
        cb();
      }, 100);
    }
    
    let requests = [1, 2, 3].reduce((promiseChain, item) => {
        return promiseChain.then(() => new Promise((resolve) => {
          asyncFunction(item, resolve);
        }));
    }, Promise.resolve());
    
    requests.then(() => console.log('done'))
    
  2. Process all async requests without "synchronous" execution (2 may finish faster than 1)

    let requests = [1,2,3].map((item) => {
        return new Promise((resolve) => {
          asyncFunction(item, resolve);
        });
    })
    
    Promise.all(requests).then(() => console.log('done'));
    

Using an async library

There are other asynchronous libraries, async being the most popular, that provide mechanisms to express what you want.

Edit

The body of the question has been edited to remove the previously synchronous example code, so i've updated my answer to clarify. The original example used synchronous like code to model asynchronous behaviour, so the following applied:

array.forEach is synchronous and so is res.write, so you can simply put your callback after your call to foreach:

  posts.foreach(function(v, i) {
    res.write(v + ". index " + i);
  });

  res.end();

Hibernate Auto Increment ID

FYI

Using netbeans New Entity Classes from Database with a mysql *auto_increment* column, creates you an attribute with the following annotations:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "id")
@NotNull
private Integer id;

This was getting me the same an error saying the column must not be null, so i simply removed the @NotNull anotation leaving the attribute null, and it works!

Byte Array and Int conversion in Java

I found a simple way in com.google.common.primitives which is in the [Maven:com.google.guava:guava:12.0.1]

long newLong = Longs.fromByteArray(oldLongByteArray);
int newInt = Ints.fromByteArray(oldIntByteArray);

Have a nice try :)

How to add an UIViewController's view as subview

Change the frame size of viewcontroller.view.frame, and then add to subview. [viewcontrollerparent.view addSubview:viewcontroller.view]

_csv.Error: field larger than field limit (131072)

This could be because your CSV file has embedded single or double quotes. If your CSV file is tab-delimited try opening it as:

c = csv.reader(f, delimiter='\t', quoting=csv.QUOTE_NONE)

What is an unsigned char?

Some googling found this, where people had a discussion about this.

An unsigned char is basically a single byte. So, you would use this if you need one byte of data (for example, maybe you want to use it to set flags on and off to be passed to a function, as is often done in the Windows API).

How to check if a variable is empty in python?

Just use not:

if not your_variable:
    print("your_variable is empty")

and for your 0 as string use:

if your_variable == "0":
    print("your_variable is 0 (string)")

combine them:

if not your_variable or your_variable == "0":
    print("your_variable is empty")

Python is about simplicity, so is this answer :)

How to create a folder with name as current date in batch (.bat) files

Try this (an equivalent of bash backquotes):

for /f "tokens=1* delims=" %%a in ('date /T') do set datestr=%%a
mkdir %datestr%

For further information, see http://ss64.com/nt/for_cmd.html